Reputation: 401
I've seen several posts about this subject but I cannot solve the problem with the information provided there. I'm trying to add scroll bars (vertical and horizontal) with the following code into a JTextArea
as follows:
public FPrincipale() {
JFrame wframe = new JFrame();
JPanel wpanel = new JPanel(new BorderLayout());
JPanel tpanel = new JPanel();
JPanel bpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
textzone = new JTextArea(" ",20, 50);
textzone.setLineWrap(true);
textzone.setWrapStyleWord(true);
//Here I try to add the scroll bar
JScrollPane wscroll = new JScrollPane(textzone, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
wscroll.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
wscroll.setBorder(BorderFactory.createLineBorder(Color.black));
wframe.add(wscroll);
wframe.setVisible(true);
JButton b1 = new JButton("B1");
JButton b2 = new JButton("B2");
JButton b3 = new JButton("Close");
bpanel.add(b1);
bpanel.add(b2);
bpanel.add(b3);
bpanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
tpanel.add(textzone);
tpanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
tpanel.add(wscroll, BorderLayout.CENTER);
wpanel.add(bpanel, BorderLayout.SOUTH);
wpanel.add(tpanel, BorderLayout.CENTER);
wframe.setLocation(150, 100);
wframe.setPreferredSize(new Dimension(640, 480));
b1.addActionListener(new b1Listener());
b2.addActionListener(new b2Listener());
b3.addActionListener(new b3Listener());
this.getContentPane().setPreferredSize(new Dimension(500,500));
wframe.add(wpanel);
wframe.setVisible(true);
wframe.setSize(640, 640);
wframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
wframe.setTitle("Main Window");
pack();
}
Nevertheless, when the window is created the scroll bar doesn't work even if I reduce the window's size:
Normal Window:
Reduced size:
How can I fix this problem?
Upvotes: 0
Views: 57
Reputation: 347184
Start by getting rid of the class to setPreferredSize
, this are going to mess you up. Later in your code you're calling tpanel.add(textzone);
, which is removing the JTextArea
from the JScrollPane
and adding it to tpanel
(you then add the JScrollPane
to it was well, which is why you have that little square next to it).
Start by applying a BorderLayout
to tpanel
JPanel tpanel = new JPanel(new BorderLayout());
Remove the line where you add the scroll pane to the frame...
//wFrame.add(wscroll);
Then add only the JScrollPane
to tpanel
//tpanel.add(textzone);
tpanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
tpanel.add(wscroll, BorderLayout.CENTER);
Upvotes: 1