I am writing code that lets the user enter, search for and remove participants. Right now I have the JFrame that has a JMenu on it with a few JMenuItems. When I ran the program and have the JMenuItems print something, it works fine. But, for example with the addItem JMenuItem, when addItem is clicked, I want it to open up a JTextField. The code I have isn't working. Can anyone explain why? Or offer a solution where when the JMenuItems are clicked JTextFields will open? Thank you.
public class MyFrame extends JFrame implements ActionListener{
JMenuBar menuBar;
JMenu fileMenu;
JMenu exitMenu;
JMenuItem addItem;
JMenuItem searchItem;
JMenuItem groupItem;
JMenuItem removeItem;
JMenuItem exitItem;
MyFrame(){
this.setTitle("Swim Lessons");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(250, 250);
//this.setSize(1436, 810);
this.setLayout(null);
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
exitMenu = new JMenu("Exit");
addItem = new JMenuItem("Add Child");
searchItem = new JMenuItem("Find Child");
groupItem = new JMenuItem("Find Group");
removeItem = new JMenuItem("Remove Child");
exitItem = new JMenuItem("Exit");
addItem.addActionListener(this);
searchItem.addActionListener(this);
groupItem.addActionListener(this);
removeItem.addActionListener(this);
exitItem.addActionListener(this);
fileMenu.add(addItem);
fileMenu.add(searchItem);
fileMenu.add(groupItem);
fileMenu.add(removeItem);
exitMenu.add(exitItem);
menuBar.add(fileMenu);
menuBar.add(exitMenu);
this.setJMenuBar(menuBar);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addItem) {
JTextField name = new JTextField();
name.setPreferredSize(new Dimension(100,100));
this.add(name);
this.setVisible(true);
}
if(e.getSource() == searchItem) {
System.out.print("pee ");
}
if(e.getSource() == groupItem) {
System.out.print("beep ");
}
if(e.getSource() == removeItem) {
System.out.print("boop ");
}
if(e.getSource() == exitItem) {
System.exit(0);
}
}
}
Side note: I do have all my imports and the class header. This site just isn't letting me add them to the code section for some reason.
Start by taking a look at How to Make Dialogs
if (e.getSource() == addItem) {
String input = JOptionPane.showInputDialog(this, "Item description", "Add item", JOptionPane.PLAIN_MESSAGE);
if (input != null) {
System.out.println("You have entered " + input);
}
}
Don't use null
layouts, these will come back to haunt you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.