Swing滑鼠懸停時巧用上下文選單顯示提示資訊
阿新 • • 發佈:2019-02-04
//新建一個button JButton bt = new JButton(); //新增監聽 bt.addMouseMotionListener(new MouseAdapter(){ public void mouseMoved(MouseEvent e) { bt .setToolTipText("你想要顯示的內容"); } } });
import javax.swing.JFrame; import java.awt.Dimension; import javax.swing.JPanel; import java.awt.GridBagLayout; import javax.swing.JButton; import java.awt.Rectangle; public class HideButton extends JFrame { private JPanel jPanel = null; private JButton jButton = null; /** * This method initializes * */ public HideButton() { super(); initialize(); } /** * This method initializes this * */ private void initialize() { this.setSize(new Dimension(239, 129)); this.setContentPane(getJPanel()); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { jPanel = new JPanel(); jPanel.setLayout(null); jPanel.add(getJButton(), null); } return jPanel; } /** * This method initializes jButton * * @return javax.swing.JButton */ private JButton getJButton() { if (jButton == null) { jButton = new JButton(); jButton.setBounds(new Rectangle(72, 29, 109, 39)); jButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent e) { jButton.setVisible(false); } public void mouseExited(java.awt.event.MouseEvent e) { jButton.setVisible(true); } }); } return jButton; } public static void main(String args[]){ new HideButton().setVisible(true); } }