繁体   English   中英

Container 内带有 TextArea 的 ScrollPane 不显示

[英]ScrollPane with TextArea inside Container doesn't show up

带有 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);
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM