![](/img/trans.png)
[英]How can I make a number appear in a JTextField when I click an option in a JList
[英]How can I make a JMenuItem open a JTextField when I click it?
我正在編寫允許用戶輸入、搜索和刪除參與者的代碼。 現在我有一個 JFrame,上面有一個 JMenu 和幾個 JMenuItem。 當我運行程序並讓 JMenuItems 打印一些東西時,它工作正常。 但是,例如使用 addItem JMenuItem,當單擊 addItem 時,我希望它打開一個 JTextField。 我的代碼不起作用。 誰能解釋為什么? 或者提供一個解決方案,當單擊 JMenuItems 時 JTextFields 將打開? 謝謝你。
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);
}
}
}
旁注:我確實有所有的導入和類頭。 由於某種原因,該站點不允許我將它們添加到代碼部分。
首先看看如何制作對話框
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);
}
}
不要使用null
布局,這些會回來困擾你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.