这是一个奇怪的问题。我有一个解决方案,但我不知道为什么首先会出现问题。观察下面的代码:
// VERSION 1
public class test {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test");
JPanel inputPanel = new JPanel();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.CENTER, inputPanel);
mainFrame.setBounds(100, 50, 200, 100);
mainFrame.setVisible(true);
JButton inputFileButton = new JButton("BROWSE");
inputPanel.add(inputFileButton);
}
}
它按预期工作。该按钮什么都不做,但它正确呈现。现在,我添加了一个 JFileChooser(我打算稍后用它做一些事情,但现在我所做的只是实例化它)。
// VERSION 2
public class test {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test");
JPanel inputPanel = new JPanel();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.CENTER, inputPanel);
mainFrame.setBounds(100, 50, 200, 100);
mainFrame.setVisible(true);
JFileChooser inputFileChooser = new JFileChooser(); // NEW LINE
JButton inputFileButton = new JButton("BROWSE");
inputPanel.add(inputFileButton);
}
}
突然之间,我的按钮不再呈现。为什么?我知道有两种方法可以让它再次工作,但对我来说都不是 100% 有意义的。一种修复方法:
// VERSION 3
public class test {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test");
JPanel inputPanel = new JPanel();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.CENTER, inputPanel);
mainFrame.setBounds(100, 50, 200, 100);
mainFrame.setVisible(true);
JButton inputFileButton = new JButton("BROWSE");
inputPanel.add(inputFileButton);
JFileChooser inputFileChooser = new JFileChooser(); // MOVE LINE TO END
}
}
所以将该行移到末尾允许按钮再次呈现,但对我来说,实例化的 JFileChooser 与未连接的按钮有什么关系仍然没有意义。解决此问题的另一种方法:
// VERSION 4
public class test {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Test");
JPanel inputPanel = new JPanel();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.CENTER, inputPanel);
mainFrame.setBounds(100, 50, 200, 100);
JFileChooser inputFileChooser = new JFileChooser();
JButton inputFileButton = new JButton("BROWSE");
inputPanel.add(inputFileButton);
mainFrame.setVisible(true); // MOVE *THIS* LINE TO THE END
}
}
为什么上面的版本解决了这个问题是有道理的……显然 JFileChoose 实例化的某些东西使我的按钮不可见,但是此 setVisible() 方法随后将其重新显示出来。但这仍然没有告诉我为什么它首先变得不可见。
有人可以帮我弄清楚我错过了什么吗?谢谢!
最佳答案
您正在使您的 mainFrame
可见,然后添加按钮。看看this SO question关于您需要采取哪些步骤来确保您的按钮可见。
它在您的第一个示例中起作用的原因可能是纯粹的运气。您添加按钮的调用将在 EDT 显示您的组件之前执行。
注意:请在EDT上进行Swing操作
关于java - 添加 JFileChooser 而不执行任何操作会导致面板不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052647/