The*_*111 1 java swing jfilechooser
这是一个奇怪的问题.我有一个解决方案,但我不知道为什么问题出现在第一位.请注意以下代码:
// 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);
}
}
Run Code Online (Sandbox Code Playgroud)
它按预期工作.该按钮不执行任何操作,但它可以正确呈现.现在,我添加一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
突然间我的按钮不再呈现.为什么?我知道有两种方法可以让它再次发挥作用,但这对我来说都没有任何意义.解决它的一种方法:
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
因此,将该行移动到最后允许按钮再次渲染,但对于我来说,实例化的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
}
}
Run Code Online (Sandbox Code Playgroud)
有意义的是为什么上面的版本修复了问题...显然JFileChoose实例化的一些东西让我的按钮不可见,但这个setVisible()方法随后将它带回了光明.但这仍然没有告诉我为什么它首先变得无形.
有人可以帮我弄清楚我错过了什么吗?谢谢!
| 归档时间: |
|
| 查看次数: |
230 次 |
| 最近记录: |