Code Completion 11.103 Add listeners to menu
Add the menu items shown below.
Add a listener to the second menu item that turns the content pane yellow.
Here is a sample program output:
Complete the following code:
import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MenuFrame extends JFrame { private JMenuBar menuBar; private JMenu fileMenu; private JMenu editMenu; private JMenu aboutMenu; public MenuFrame() { menuBar = new JMenuBar(); fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); editMenu = new JMenu("Edit"); aboutMenu = new JMenu("About"); // TODO: Add menu items // TODO: Add listener to second menu item setJMenuBar(menuBar); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(aboutMenu); } }
The following class is used to check your work:
import javax.swing.JFrame; public class MenuFrameViewer { public static void main(String[] args) { MenuFrame frame = new MenuFrame(); frame.setBounds(50,50,400,200); frame.setTitle("MenuFrameViewer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Expert Answer
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MenuFrame extends JFrame implements ActionListener
{
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenu editMenu;
private JMenu aboutMenu;
private JMenuItem mi1,mi2;
public MenuFrame()
{
menuBar = new JMenuBar();
fileMenu = new JMenu(“File”);
fileMenu.setMnemonic(‘F’);
editMenu = new JMenu(“Edit”);
aboutMenu = new JMenu(“About”);
// TODO: Add menu items
mi1=new JMenuItem(“Open file”);
mi2=new JMenuItem(“Turn background yello”);
fileMenu.add(mi1);
fileMenu.add(mi2);
// TODO: Add listener to second menu item
mi2.addActionListener(this);
setJMenuBar(menuBar);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(aboutMenu);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(“hello”);
getContentPane().setBackground(Color.yellow);
}
}