import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Combo extends JFrame implements ActionListener {
public Combo() {
setSize(500,500);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
String[] country=new String[]{"INDIA","AMERICA","NIGERIA"};
JComboBox comboBox=new JComboBox<String>(country);
comboBox.setEditable(true);
comboBox.addActionListener(this);
add(comboBox);
}
public void actionPerformed(ActionEvent e) {
JComboBox comboBox=(JComboBox) e.getSource();
String s1=(String) comboBox.getSelectedItem();
String s2=(String) comboBox.getActionCommand();
System.out.println(s1);
System.out.println(s2);
}
public static void main(String args[]) {
new Combo();
}
}
这段代码完全编译但是在运行代码时,comboBox无法运行....它不会在秋千上显示:(帮助
答案 0 :(得分:0)
您应该从EDT主题运行程序:
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Combo();
}
});
}
在挥杆过程中,挥杆物体上的每一次操控都应该在EDT内部进行。请参阅swing tutorial。
EDT是事件调度程序线程。在这个线程中,swing完成所有奇迹:处理点击事件将其传递给听众,重新绘制所有内容。由于swing不是线程安全的,因此不应该访问EDT之外的swing对象。关于EDT的资源很多,例如Swing tutorial from sun/oracle。
答案 1 :(得分:0)
如上所述,在EDT线程中运行程序是正确的方法,但是如果你想以不同的方式执行它(尽管不太推荐),你可以在更新值后调用这些方法:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Combo extends JFrame implements ActionListener {
public Combo() {
setSize(500,500);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
String[] country=new String[]{"INDIA","AMERICA","NIGERIA"};
JComboBox comboBox=new JComboBox<String>(country);
comboBox.setEditable(true);
comboBox.addActionListener(this);
add(comboBox);
revalidate();
repaint();
}
public void actionPerformed(ActionEvent e) {
JComboBox comboBox=(JComboBox) e.getSource();
String s1=(String) comboBox.getSelectedItem();
String s2=(String) comboBox.getActionCommand();
System.out.println(s1);
System.out.println(s2);
}
public static void main(String args[]) {
new Combo();
}
}
答案 2 :(得分:0)
您的代码应该是这样的
public class Combo extends JFrame implements ActionListener {
public Combo() {
String[] country=new String[]{"INDIA","AMERICA","NIGERIA"};
JComboBox comboBox=new JComboBox<String>(country);
comboBox.setEditable(true);
comboBox.addActionListener(this);
add(comboBox);
setSize(500,500);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}