Add a scroll bar to text area

后端 未结 2 1010
灰色年华
灰色年华 2021-01-23 10:37

I use Eclipse Window Builder. When I click the button, something will be written on the screen. But since my prints are long, I want to use a scroll pane.

public         


        
相关标签:
2条回答
  • 2021-01-23 11:28

    So, based on...

    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); is irrelevant as the layout manager will deal with it. You can provide sizing hints via the JTextArea(String, int, int) constructer, but remember, this is the number of characters in width/height, not pixels.

    The following are giving you issues...

    frame.getContentPane().add(scroll);
    frame.setVisible(true);
    

    because frame is undefined. Since the class extends from JFrame, they are pointless, it should just be

    getContentPane().add(scroll);
    setVisible(true);
    

    but, I'd add...

    pack();
    setLocationRelativeTo(null);
    

    before it, as it will give you a generally better experience

    0 讨论(0)
  • 2021-01-23 11:33

    You need to add the TextArea to the ScrollPane. Don't add the textarea tho the contentpane.

    0 讨论(0)
提交回复
热议问题