これは奇妙な問題です。解決策はありますが、そもそもなぜ問題が発生するのかわかりません。以下のコードを確認してください。
// 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);
}
}
突然、ボタンがレンダリングされなくなりました。なんで?再び機能させる方法は 2 つありますが、どちらも 100% 意味がありません。それを修正する1つの方法:
// 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() メソッドは後でそれを明らかにします。しかし、そもそもなぜそれが見えなくなったのかはまだわかりません。
誰かが私が欠けているものを理解するのを手伝ってもらえますか? ありがとう!