Swing-右键菜单
生活随笔
收集整理的這篇文章主要介紹了
Swing-右键菜单
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
MyFrame :
設(shè)計思路:
1、創(chuàng)建JPopup右鍵菜單對象;
2、添加內(nèi)容面板JPanel;
3、創(chuàng)建一個自定義的右鍵菜單項目鍵,包括圖片+名字+事件;
4、將菜單項添加到右鍵菜單;
5、添加面板事件處理:當(dāng)右鍵點(diǎn)擊面板時,出現(xiàn)右鍵菜單;
6、創(chuàng)建一個監(jiān)聽器,用于表示點(diǎn)擊菜單項操作;
package swing01;import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.URL;import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JToolBar;public class MyFrame extends JFrame {//彈出式菜單JPopupMenu popup=new JPopupMenu();public MyFrame(String title){super(title);//內(nèi)容面板JPanel root=new JPanel();this.setContentPane(root);root.setLayout(new BorderLayout());//右鍵菜單popup.add( createMenuItem("ic_open.png", "fileOpen","打開"));popup.add( createMenuItem("ic_save.png", "fileSave","保存"));popup.add( createMenuItem("ic_saveas.png","fileSaveAs","另存為"));popup.addSeparator();popup.add( createMenuItem("ic_help.png", "fileHelp","幫助"));//添加鼠標(biāo)響應(yīng)事件,當(dāng)點(diǎn)擊右鍵時,彈出菜單root.addMouseListener(new MouseAdapter() {@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stubsuper.mouseClicked(e);if(e.getButton()==MouseEvent.BUTTON3){popup.show(e.getComponent(), e.getX(), e.getY());}}});}protected JMenuItem createMenuItem(String iceName,String action,String text){JMenuItem item=new JMenuItem(text);item.setActionCommand(action);item.addActionListener(actionListener);if(iceName!=null){String imagePath="/images/"+iceName;URL imageURL=getClass().getResource(imagePath);item.setIcon(new ImageIcon(imageURL));}return item;}//創(chuàng)建一個監(jiān)聽器//注意:actionListener是類的屬性private ActionListener actionListener=new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString action=e.getActionCommand();System.out.println("執(zhí)行命令:"+action);//當(dāng)是打開命令時,再彈出一個窗口if(action.equals("fileOpen")){JOptionPane.showMessageDialog(MyFrame.this, action);}}};}main
package swing01;import java.awt.Container; import java.awt.FlowLayout;import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel;public class MyDemo {private static void createGUI(){// JFrame指一個窗口,構(gòu)造方法的參數(shù)為窗口標(biāo)題JFrame frame = new MyFrame("Swing Demo");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 設(shè)置窗口的其他參數(shù),如窗口大小frame.setSize(400, 300);// 顯示窗口frame.setVisible(true);}public static void main(String[] args){javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run(){createGUI();}});} }?
總結(jié)
以上是生活随笔為你收集整理的Swing-右键菜单的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 腾讯俞栋:AI发展不是独角戏,要与合作伙
- 下一篇: 微信引流软件哪里找?哪个引流软件比较可靠