问题描述
带有 Textarea 的滚动窗格没有显示。 (我也有 gif 在后台运行)。 我试图将它单独添加到另一个框架中它可以工作,但不知何故我无法将它添加到容器中
static class UserGUI extends JFrame implements ActionListener {
PlaceHolder p1,p2,p3,p4,p5,p6;
// Components of the Form
private Container c;
private JLabel title;
private JTextArea textarea1;
public UserGUI () throws IOException {
setTitle("User Panel");
setBounds(300,90,1000,1000);
setDefaultCloSEOperation(EXIT_ON_CLOSE);
setLocationRelativeto(null);
setResizable(false);
c = getContentPane();
c.setLayout(null);
textarea1 = new JTextArea();
textarea1.setFont(new Font("Arial",Font.PLAIN,15));
textarea1.setSize(300,400);
textarea1.setLocation(500,100);
textarea1.setLineWrap(true);
textarea1.setEditable(false);
textarea1.setVisible(true);
JScrollPane scroll = new JScrollPane (textarea1);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(scroll);
c.add(textarea1);
}
}
解决方法
当您从 JFrame 扩展并调用 add() 时,组件将添加到 JFrame 的 ContentPane,因此您的代码没有意义。
Container c = getContentPane();
c.add(); //Same as add()
正如@AndrewThompson 在评论中所建议的,您应该始终使用布局(因为您的 GUI 必须在不同的屏幕尺寸、操作系统等上工作)。所以最好不要使用 setLayout(null)。
您想要做的正确示例是:
public class UserGUI extends JFrame{
private JTextArea textArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new UserGUI();
}
});
}
public UserGUI(){
textArea = new JTextArea();
textArea.setFont(new Font("Arial",Font.PLAIN,15));
textArea.setLineWrap(true);
//textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea); //Add the textArea to the scrollPane
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(scrollPane); //Add the scrollPane to the JFrame's Content Pane
setTitle("User Panel");
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
}