1 回答
TA贡献1836条经验 获得超4个赞
您的程序需要进行一些更改
extends JFrame
如我上面的评论所述删除,请参阅扩展 JFrame 与在程序中创建它将您的程序放在 EDT 上,请参阅此答案的第 3 点以及
main
有关如何执行此操作的示例的方法。你对如何
ActionListeners
工作感到困惑,他们会等到你在你的程序中执行某些操作(即你按下Confirm
按钮),然后再做一些事情。程序中的“某事”意味着:打印所选项目并检查它是否是武器,然后做其他事情。
因此,在这种情况下,您无需返回main
以继续您的程序,main
仅用于初始化您的应用程序,仅此而已。你需要在事件中思考,而不是按顺序思考。这是棘手且最重要的部分。
您需要从控制台应用程序更改您的编程范例,并且do-while
一切都以顺序方式发生,而不是当用户对您的应用程序执行某些操作时触发的事件。
例如:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest implements ActionListener {
private JFrame frmInventorysystem;
private JPanel frameBottom;
private JComboBox equipList;
private JButton confirmBtn, cancelBtn;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GUITest()); //Java 8+ if using an earlier version check the point #2 in this answer and modify the code accordingly.
}
/**
* Create the application.
*/
public GUITest() {
frmInventorysystem = new JFrame();
frmInventorysystem.setTitle("InventorySystem");
frmInventorysystem.setBounds(100, 100, 450, 300);
frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));
/*
* JFrame inside another JFrame is not recommended. JPanels are used instead
* Creating a flow layout for the bottom frame
*/
frameBottom = new JPanel();
frameBottom.setLayout(new FlowLayout());
// creates comboBox to find out which of the three items player is looking to
// insert
String[] weaponCategories = { "Weapon", "Armor", "Mod" };
equipList = new JComboBox(weaponCategories);
frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);
// Converting BorderLayout.south into a flow layout
frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);
confirmBtn = new JButton("Confirm");
confirmBtn.addActionListener(this);
frameBottom.add(confirmBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(this);
frameBottom.add(cancelBtn);
frmInventorysystem.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// creates new windows to sort equipment when confirmBtn is clicked
if (e.getSource() == confirmBtn) {
String category = equipList.getSelectedItem().toString(); //Get the selected category
doSomething(category); //Pass it as a parameter
}
// Exits when cancelBtn is clicked
if (e.getSource() == cancelBtn) {
frmInventorysystem.dispose();
}
}
// Do something with the category
private void doSomething(String selectedEquipment) {
System.out.println(selectedEquipment);
if (selectedEquipment.equals("Weapon")) {
System.out.println("It's a weapon!"); //You can open dialogs or do whatever you need here, not necessarily a print.
} else {
System.out.println("Not a weapon");
}
}
}
请注意,我删除了继承,我不会返回main并仍然打印所选项目并检查它是否是武器。
我还以更安全的方式退出应用程序。
这是示例输出:
Weapon
It's a weapon!
Armor
Not a weapon
添加回答
举报