JPopupMenu是对于Swing开发者是在熟悉不过的组件了,不过大部分人只将其作为右击弹出菜单使用,其实JPopupMenu还可以有很多用途,可以说只要是需要弹出式效果的都可以用其实现。例如我们用开发工具输入import java.util.当输入“.”时会自动弹出提示框选项,以下的小程序展示了这样的效果:
import java.awt.BorderLayout;
import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingConstants;
public class PopupTip extends JFrame {
String[] messages = new String[] { "getNetworkFromTWaver", "getTreeFromTWaver", "getTableFromTWaver", "getPropertySheetFromTWaver", "getTreeTableFromTWaver", "getChartFromTWaver", "getRPCFromTWaver", "getGUIFrameworkFromTWaver", "getFantasticIdeaFromTWaver", }; JLabel label = new JLabel("TWaver make everything easy!"); JList list = new JList(messages); JComponent tip = new JScrollPane(list); JTextArea text = new JTextArea(); JPopupMenu popup = new JPopupMenu(); public PopupTip() { super(" www.servasoft.com "); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(new JScrollPane(text), BorderLayout.CENTER);
this.tip.setPreferredSize(new Dimension(400, 100));
this.label.setForeground(Color.BLUE); this.label.setHorizontalAlignment(SwingConstants.CENTER); this.popup.setLayout(new BorderLayout()); this.popup.add(label, BorderLayout.NORTH); this.popup.add(tip, BorderLayout.CENTER); this.text.setBackground(Color.BLACK); this.text.setForeground(Color.GREEN); this.text.setCaretColor(Color.WHITE); this.text.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { if(popup.isShowing()){ popup.setVisible(false); }else if (e.getKeyCode() == KeyEvent.VK_PERIOD){ Point point = text.getCaret().getMagicCaretPosition(); if(point != null){ popup.show(text, point.x, point.y); } text.requestFocus(); } } }); }
public static void main(String[] args) {
PopupTip ui = new PopupTip(); ui.setSize(400, 200); ui.show(); } } | ||
|
巧用JPopupMenu(一)
最新推荐文章于 2019-08-06 22:03:34 发布