【发布时间】:2021-01-01 15:59:30
【问题描述】:
我正在尝试根据其他 JCombobox(城市)的值更改 JCombobox 项目列表(城镇)。当我更改城市列表中的值时,它会更改城镇列表中的项目。但是有两个问题。
- 更新后的列表(城镇)显示了双倍的项目,但当单击它时,它会显示正确的项目数量,如第一个屏幕截图所示。
- 更新后的列表不允许我选择其中一项,它只选择了第一项
这是我的代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Testing extends JFrame implements ActionListener {
public static void main(String[] args )
{
new Testing();
}
JComboBox cb,cb1,cb2;
JFrame f;
JLabel label1,label2;
JButton b1;
JTextField name,ID,birth;
Testing(){
f=new JFrame("Information Example");
label1 = new JLabel("Please input your information below");
label1.setBounds(10, 20, 260, 30);
f.add(label1);
String question[]={"Calculate my Age","When do I drive","When do I vote"};
String city[]={"Asimah","Ahmadi","Hawalli"};
name= new JTextField("NAME");
name.setBounds(10,50,264,25);
f.add(name);
ID= new JTextField("CIVIL ID");
ID.setBounds(10,80,264,25);
f.add(ID);
birth= new JTextField("DATE OF BIRTH");
birth.setBounds(10,110,264,25);
f.add(birth);
cb=new JComboBox(question);
cb.setBounds(50, 150,180,20);
f.add(cb);
b1= new JButton("Get");
b1.setBounds(100,250,60,20);
f.add(b1);
cb1=new JComboBox(city);
cb1.setBounds(10, 200,120,20);
f.add(cb1);
cb2=new JComboBox();
cb2.setBounds(150, 200,120,20);
f.add(cb2);
f.setLayout(null);
f.setSize(300,400);
f.setVisible(true);
cb.addActionListener(this);
cb1.addActionListener(this);
cb2.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent event)
{
if(cb1.getSelectedIndex() == 0)
{
cb2.removeAllItems();
cb2.addItem("Rawdhah");
cb2.addItem("Abdahll");
}
else if(cb1.getSelectedIndex() == 1)
{
cb2.removeAllItems();
cb2.addItem("Siddiq");
cb2.addItem("Aljabryha");
}
else
{
cb2.removeAllItems();
cb2.addItem("Fintas");
cb2.addItem("Abdahll");
}
}
}
【问题讨论】:
-
您的
ActionListener被触发了两次,一次用于cb1,一次用于cb2.cb2` 是触发ActionEvent,因为addItem正在更改所选项目,所以,您addItems,事件被触发,你添加了两个新项目,然后你又添加了两个项目。它没有进入无限循环,因为您添加的第二个项目不会更改所选项目 - 因为现在第一个项目已被选中 -
这是一种改变模型的方法:stackoverflow.com/questions/4982260/binding-comboboxes-in-swing/…。它还将支持在不使用嵌套 if/else 语句的情况下为无限数量的城市更改模型。
-
Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同的语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。