Continuous modify JFrameWin.java from last exercise "Example of using Swing JMenu". But, I can't setBackground on JFrame - I don't know why! So I add a JPanel over the JFrame.
package javatestswing; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; /** * * @web http://java-buddy.blogspot.com/ */ public class JFrameWin extends JFrame{ public JFrameWin(){ final JPanel jPanel = new JPanel(); this.setTitle("java-buddy.blogspot.com"); this.setSize(500, 400); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton buttonExit = new JButton(" Exit "); buttonExit.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { System.exit(0); } }); jPanel.add(buttonExit); add(jPanel); JMenuBar menuBar = new JMenuBar(); JMenu menuA = new JMenu("Choose Color"); JMenuItem menuItemDoColorChooser = new JMenuItem("Open JColorChooser"); menuItemDoColorChooser.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { doColorChooser(jPanel); } }); menuA.add(menuItemDoColorChooser); JMenu menuB = new JMenu("Quit..."); JMenuItem menuItemB1 = new JMenuItem("Exit"); menuItemB1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { System.exit(0); } }); menuB.add(menuItemB1); menuBar.add(menuA); menuBar.add(menuB); this.setJMenuBar(menuBar); } private void doColorChooser(JPanel panel){ Color color = JColorChooser.showDialog( panel, "JColorChooser", panel.getBackground()); if (color != null){ panel.setBackground(color); } } }
No comments:
Post a Comment