Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

swing - Adding a Scrollable JTextArea (Java)

I am trying to add a scroll bar to a JTextArea. Would someone please tell me what I did wrong with the code below?

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scrollV = new JScrollPane (textArea);
JScrollPane scrollH = new JScrollPane (textArea);

scrollV.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollH.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.setVisible (true);

Thank you in advance.

EDIT: I fixed the code with the Adel Boutros' advice below.

    //FRAME
JFrame frame = new JFrame ("Test");
frame.setSize(500,500);
frame.setResizable(false);
//

//TEXT AREA
JTextArea textArea = new JTextArea("TEST");
textArea.setSize(400,400);    

    textArea.setLineWrap(true);
    textArea.setEditable(false);
    textArea.setVisible(true);

    JScrollPane scroll = new JScrollPane (textArea);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    frame.add(scroll);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't work because you didn't attach the ScrollPane to the JFrame.

Also, you don't need 2 JScrollPanes:

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scroll = new JScrollPane (textArea, 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...