向文本区域添加滚动条

我使用 Eclipse Window Builder。当我点击按钮时,屏幕上会写一些东西。但是由于我的打印件很长,所以我想使用滚动窗格。


public class uyg2 extends JFrame {


private JPanel contentPane;


/**

 * Launch the application.

 */

public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {

        public void run() {

            try {

                uyg2 frame = new uyg2();

                frame.setVisible(true);

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    });

}


/**

 * Create the frame.

 */

public uyg2() {

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setBounds(100, 100, 450, 300);

    contentPane = new JPanel();

    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

    setContentPane(contentPane);

    contentPane.setLayout(null);


    JButton btnNewButton = new JButton("New button");

    btnNewButton.setBounds(32, 29, 89, 23);

    contentPane.add(btnNewButton);


    JTextArea textArea = new JTextArea();

    textArea.setBounds(10, 63, 233, 173);

    contentPane.add(textArea);


    ScrollPane scrollPane = new ScrollPane();

    scrollPane.setBounds(249, 10, 173, 118);

    contentPane.add(scrollPane);

}


一只萌萌小番薯
浏览 144回答 2
2回答

ABOUTYOU

所以,基于...public class uyg1 extends JFrame {    private JPanel contentPane;    /**     * Launch the application.     */    public static void main(String[] args) {        EventQueue.invokeLater(new Runnable() {            public void run() {                try {                    uyg1 frame = new uyg1();                    frame.setVisible(true);                } catch (Exception e) {                    e.printStackTrace();                }            }        });    }    /**     * Create the frame.     */    public uyg1() {        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setBounds(100, 100, 450, 300);        contentPane = new JPanel();        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));        contentPane.setLayout(new BorderLayout(0, 0));        setContentPane(contentPane);        JTextArea textArea = new JTextArea("Test");        textArea.setSize(400, 400);        JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);        frame.getContentPane().add(scroll);        frame.setVisible(true);    }}textArea.setSize(400, 400);无关紧要,因为布局管理器将处理它。您可以通过构造函数提供大小调整提示JTextArea(String, int, int),但请记住,这是宽度/高度中的字符数,而不是像素数。以下是给你的问题......frame.getContentPane().add(scroll);frame.setVisible(true);因为frame未定义。由于该类是从 扩展的JFrame,因此它们毫无意义,应该只是getContentPane().add(scroll);setVisible(true);但是,我要补充...pack();setLocationRelativeTo(null);在它之前,因为它会给你一个总体上更好的体验

达令说

您需要将 TextArea 添加到 ScrollPane。不要在内容窗格中添加文本区域。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java