gpt4 book ai didi

java - ActionListener 在按钮单击时不执行任何操作

转载 作者:行者123 更新时间:2023-12-02 10:32:50 25 4
gpt4 key购买 nike

public class ReadGameDetailsWindow extends JFrame implements ActionListener {

private GameFactory theFactory = GameFactory.getInstance();
private HashMap<String, Game> theListOfGames = theFactory.listOfGames();

JTable table;

// Delete game panel
JPanel deletePanel = new JPanel(new GridLayout(2,2));
JLabel theDeleteGameName = new JLabel("Game Name:");
JTextField theDeleteGameNameField = new JTextField();
JButton theDeleteCancelButton = new JButton("Clear");
JButton theDeleteOKButton = new JButton("Delete");

String[] columns = {"Name", "Developer", "Genre", "Rating"};
Object[][] tableData = new Object[theListOfGames.keySet().size()][4];

public void fillDetails() {
int index = 0;
for (String key : theListOfGames.keySet())
{
Game game = theListOfGames.get(key);
tableData[index][0] = game.getName();
tableData[index][1] = game.getDeveloper();
tableData[index][2] = game.getGenre();
tableData[index][3] = game.getOutOfTen() + "/10";
index++;
}
}

public ReadGameDetailsWindow() {
fillDetails();

deletePanel.add(theDeleteGameName);
deletePanel.add(theDeleteGameNameField);
deletePanel.add(theDeleteCancelButton);
deletePanel.add(theDeleteOKButton);

TitledBorder deleteBorder = BorderFactory.createTitledBorder("Delete Section");

table = new JTable(tableData, columns);
table.setPreferredScrollableViewportSize(new Dimension(500, 50));
JScrollPane scrollPane = new JScrollPane(table);

JPanel controls = new JPanel();
controls.setLayout(new GridLayout(1,3));

controls.add(deletePanel);

setLayout(new GridLayout(2,1));

getContentPane().add(scrollPane);
getContentPane().add(controls);
setVisible(true);
setSize(800,800);


}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(theDeleteOKButton)) {
try {
System.out.println("Delete Button Pressed");
String aGameName = theDeleteGameNameField.getText();
theFactory.deleteGame(aGameName);
fillDetails();
table.repaint();
JOptionPane.showMessageDialog(new JFrame(), aGameName + " has been deleted!");
} catch (Exception aException) {
aException.printStackTrace();
}
}
}
}

因此,实际上,当我单击“DeleteOKButton”时,什么也没有发生。我正在尝试从显示信息的 HashMap 中删除一条记录。

我尝试在主构造函数内部和外部创建和实例化按钮,并尝试单独添加actionListener,但我似乎根本没有反应。

我需要移动按钮还是有我缺少的替代方法?抱歉,我对 Swing 还很陌生,只是想让它发挥作用。

最佳答案

您需要向按钮添加操作监听器。这样做:

theDeleteCancelButton.addActionListener(this); //detects button press action for theDeleteCancelButton
theDeleteOKButton.addActionListener(this); //detects button press action for theDeleteOKButton

关于java - ActionListener 在按钮单击时不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53509987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com