我有一个java程序,它将根据用户输入创建一个JComboBoxes数组。如果用户输入为1,则显示comboBox。如果输入大于1,我似乎得到一个普通的JFrame。
import javax.swing.*;
import java.awt.*;
class test
{
public static void main (String Args [])
{
JFrame processDetail = new JFrame("Enter information for processes");
JPanel panelDetail = new JPanel(new FlowLayout());
String [] Processes = {"1","2","3","4","5","6","7","8","9","10"};
processDetail.setSize(500,500);
processDetail.setVisible(true);
JComboBox [] AT = new JComboBox[4]; //initailse drop down, numProcc is user integer...
for (int i = 0; i < 4; i++){
AT[i] = new JComboBox(Processes); //processes is array of numbers
System.out.println(i); //a check to see it was looping
panelDetail.add(AT[i]);
}
//add the panel to the frame
processDetail.add(panelDetail);
}
}
为什么我似乎没有得到所需数量的组合框?
答案 0 :(得分:1)
您刚刚发现了在AWT事件调度线程中执行Swing操作失败的一个陷阱。
Swing is single-threaded.几乎所有Swing方法都必须才能在事件调度线程中执行。
如果他们不是,他们可能似乎工作,但你会得到不可预知的行为,就像你现在看到的那样。
如果将所有代码移动到Runnable并将Runnable传递给EventQueue.invokeLater(或SwingUtilities.invokeLater,这是EventQueue.invokeLater的同义词),您的问题就会消失。
答案 1 :(得分:0)
如果您在processDetail.setVisible(true);
之后放置processDetail.add(panelDetail);
,它应该可以正常工作。
JFrame processDetail = new JFrame("Enter information for processes");
JPanel panelDetail = new JPanel(new FlowLayout());
processDetail.setSize(500, 500);
//processDetail.setVisible(true); Not here,
String[] processes = {"1" , "2", "3", "4"};
JComboBox[] AT = new JComboBox[4]; //initailse drop down, numProcc is user integer...
for (int i = 0; i < 4; i++) {
AT[i] = new JComboBox(processes); //processes is array of numbers
System.out.println(i); //a check to see it was looping
panelDetail.add(AT[i]);
}
//add the panel to the frame
processDetail.add(panelDetail);
processDetail.setVisible(true); // <--- but here.
因为如果你将它设置为可见然后添加一些组件,它们就不会显示,因为没有任何东西告诉它将它们设置为可见。