出于某种原因,当我运行此代码时,我的 JFrame 显示为空白。我已经尝试在线教程大约一个小时了,我想知道我是否误解了某些内容。
这是代码:
public class Application {
public static JFrame f;
public static JButton submit;
public static JTextField unscramblee;
public static String scrambledWord, possibleWords;
public static JLabel possibleWordsDisplay;
public static JPanel UI;
public static JScrollPane scrollPane;
Application() {
f = new JFrame("test");
f.setResizable(true);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
UI = new JPanel();
scrollPane = new JScrollPane(UI);
unscramblee = new JTextField("test");
unscramblee.setBounds(240, 200, 400, 50);
submit = new JButton("Submit");
submit.setBounds(240, 350, 400, 100);
possibleWordsDisplay = new JLabel("possibleWordsDisplay - this is a display for words that are possible");
possibleWordsDisplay.setBounds(240, 0, 200, 200);
scrollPane.add(unscramblee);
scrollPane.add(submit);
scrollPane.add(possibleWordsDisplay);
f.getContentPane().add(scrollPane);
f.pack();
f.setSize(1280,720);
}
}
我希望这些信息足以提供帮助。谢谢。
(如果有人想知道为什么 setSize 方法出现在 pack 方法之后,那是因为当我运行它时,JFrame 不断自行崩溃。如果您也知道如何解决这个问题,请告诉我!我将非常感激。 )
最佳答案
手动设置绑定(bind)并不是一个可行的做法。
而是使用适当的Layout Managers以获得所需的布局。
以下为mre 1(注意注释):
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Application {
Application() {
JFrame f = new JFrame("test");
//f.setSize(1280,720); f.pack should automatically set the size
f.setResizable(true);
//f.setLayout(null); do not use null layout
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel UI = new JPanel(); // uses flowlayout by default
//UI.setBounds(0, 0, 1280, 720); do not set bounds. that the job of the layout manager
JTextField unscramblee = new JTextField("test", 10);
//unscramblee.setBounds(240, 200, 400, 50);
JButton submit = new JButton("Submit");
//submit.setBounds(240, 350, 400, 100);
JLabel possibleWordsDisplay = new JLabel("possibleWordsDisplay - this is a display for words that are possible");
//possibleWordsDisplay.setBounds(240, 0, 200, 200);
UI.add(unscramblee);
UI.add(submit);
UI.add(possibleWordsDisplay);
JScrollPane scrollPane = new JScrollPane(UI);
f.getContentPane().add(scrollPane); //uses borderlayout by default
f.pack();
f.setVisible(true); //make frame visible after construction is completed
}
public static void main(String[] args) {
new Application();
}
}
<小时/>
1 在发布问题或答案时始终考虑 mre
关于java - 这段代码有什么问题? (JScrollPane 和 JFrame),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59403275/