我正在开发一些应用程序。在主页(注册页面)上有一个组合框,几乎没有可供选择的选项。根据选择的内容,具体内容将出现在下一个窗口中。 问题是如何从其他类中的组合框获取内容。
我假设需要添加一些 if 控制指令,但每次我添加一些东西时它都会返回一个错误。
有人可以帮忙看看代码应该是什么样子吗? 例如,如果选项“1”将被选中,则将背景设置为黑色,如果“2”将背景设置为粉红色等。
注册窗口:
public Main() throws Exception {
registerWindowFrame = new JFrame("xxx");
//registerWindowFrame.setSize(1440,2960);
registerWindowFrame.setSize(500, 750);
registerWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
registerWindowFrame.setLayout(null);
registerWindowFrame.getContentPane().setBackground(Color.RED);
BloodList bloodList = new BloodList();
bloodList.setSize(bloodList.getPreferredSize());
bloodList.setLocation(10, 365);
registerWindowFrame.add(bloodList);
组合框类:
public class BloodList extends JComboBox <String> {
int i;
public String[] bloodList =
{
"1",
"2",
"3",
};
public BloodList() {
for (i=0; i < bloodList.length; i++)
{
this.addItem(bloodList[i]);
};
}
}
注册窗口之后的窗口:
public mainWindowBplus() {
super();
bloodBplusFrame = new JFrame("SETTINGS");
bloodBplusFrame.setSize(500, 750);
bloodBplusFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
bloodBplusFrame.setLayout(null);
bloodBplusFrame.getContentPane().setBackground(Color.BLUE);
bloodBplusFrame.setVisible(true);
最佳答案
你应该添加一个action listener
给你的jcombobox
,它获取所选String
的值,然后在其他类中使用该值,试试这个:
public class BloodList extends JComboBox <String> {
private String s="";
private String[] bloodList =
{
"1",
"2",
"3",
};
public BloodList() {
for (int i=0; i < bloodList.length; i++)
{
this.addItem(bloodList[i]);
};
}
ActionListener cbActionListener = new ActionListener() {//add actionlistner to listen for change
@Override
public void actionPerformed(ActionEvent e) {
s = (String) BloodList.this.getSelectedItem();//get the selected string
}
};
this.addActionListener(cbActionListener);
public String getS(){return s;}
}
现在您可以使用 getS()
方法在另一个类中使用该 String
。
关于java - 如何从另一个类的 JComboBox 中获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57711164/