我有一个带有各种按钮的各种面板。某些按钮应调用通过数组列表启动搜索的方法,其他按钮应调用将信息发送到不同 JTextArea 框的方法。 为每个按钮添加事件监听器后,如何根据在 actionPerformed 方法中单击的按钮创建特定操作?下面是我的各种 gui 属性的代码,您可以看到有 3 个不同的 JPanel,每个 JPanel 的按钮需要执行不同的功能。我只需要知道如何确定单击了哪个按钮,以便我可以将其链接到适当的方法(已在另一个类中编写)。这需要 if 语句吗?如果我将其公开,我的其他类可以访问 GUI 上的按钮吗?或者是否有更有效的方法来执行此操作。
JPanel foodOptions;
JButton[] button= new JButton[4]; //buttons to send selected object to info panel
static JComboBox[] box= new JComboBox[4];
JPanel search;
JLabel searchL ;
JTextField foodSearch;
JButton startSearch; //button to initialize search for typed food name
JTextArea searchInfo;
JPanel foodProfile;
JLabel foodLabel;
JTextArea foodInfo;
JButton addFood; //but to add food to consumed calories list
JPanel currentStatus;
JLabel foodsEaten;
JComboBox foodsToday;
JLabel calories;
JTextArea totalKCal;
JButton clearInfo; //button to clear food history
最佳答案
根据人们的评论,您需要使用某种类型的监听器,这是一个真正的基本示例来帮助您入门,但是在大多数情况下,我会在其他地方定义您的监听器,而不是即时定义:
JButton startSearch = new JButton("startSearch");
JButton addFood = new JButton("addFood");
startSearch.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//DO SEARCH RELATED THINGS
}
});
addFood.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//DO FOOD ADD RELATED THINGS
}
});
关于java - 操作不同 Jpanel 中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14468958/