我在Eclipse中创建了一个用户界面,我要求用户在JComboBox
中选择一个选项,然后单击JButton
以启动该事件。根据他们选择的选项,将运行不同的类并输出其结果。一切都设置得很好JButtons
自己工作,但我不能让他们回应JComboBox
的变化。
这是代码和启动界面的类的示例(完整代码更长,包含更多按钮等,因此额外的列和行):
package projectFinal;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test extends JFrame {
public test() {
setTitle("BIM Representative GUI");
JPanel pane = new JPanel(new BorderLayout());
int numberOfRows = 8;
int numberOfColumns = 4;
pane.setLayout(new GridLayout(numberOfRows, numberOfColumns));
JLabel metric1label = new JLabel(" Greenhouse Gas Emissions: ");
pane.add(metric1label);
JLabel metric1alabel = new JLabel(" ");
pane.add(metric1alabel);
String[] pollutants = { "Total","CO2", "CH4","N2O"};
final JComboBox<String> cb1 = new JComboBox<String>(pollutants);
cb1.setVisible(true);
getContentPane().add(cb1);
JButton button1 = new JButton("Check");
pane.add(button1);
getContentPane().add(pane);
pack();
button1.setToolTipText("This button will show the Greenhouse Gas Emissions");
button1.addActionListener(new MyActionListener1());
}
public class MyActionListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String choice = (String)cb1.getSelectedItem();
if(choice.equals("Total"))
{
GHGEmissions.UI();
}
if(choice.equals("CO2"))
{
CO2Emissions.UI();
}
if(choice.equals("CH4"))
{
CH4Emissions.UI();
}
if(choice.equals("N2O"))
{
N2OEmissions.UI();
}
}
}}
运行界面的代码:
package projectFinal;
import projectFinal.test;
public class testRun {
public static void main(String[] args) {
test view = new test();
view.setVisible(true);
}
}
JComboBox
根本没有出现在接口上(当删除String选项和if语句时会这样做)。有没有人知道如何解决这个问题,以便根据JComboBox
运行不同的类。
显示问题的唯一部分是行中的cb1:
String choice = (String)cb1.getSelectedItem();
由于
答案 0 :(得分:1)
cb1是构造函数中的局部变量,因此您需要将ActionListener声明为annoynimus类才能访问cb1变量,
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// you code.
}
});
还需要使用.equals()
方法而不是==
来比较字符串。
因此,请尝试将代码更改为:
if(choice.equals("Total"))
{
GHGEmissions.UI();
}
有关详细信息,请参阅this。