将滚动条添加到文本区域

时间:2019-06-28 06:24:33

标签: java swing layout-manager jscrollpane jtextarea

我使用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);
}

2 个答案:

答案 0 :(得分:0)

您需要将TextArea添加到ScrollPane。不要在内容窗格中添加文本区域。

答案 1 :(得分:0)

所以,基于...

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);

在此之前,它将为您提供总体上更好的体验

相关问题