Reputation: 2873
I'm printing a text that I scanned from a text file to a JPanel. The text is showing up, but it's not scrolling down. Any ideas? Here is my code:
rFrame = new JFrame();
rFrame.setBounds(10, 10, 502, 502);
rFrame.getContentPane().setLayout(null);
JPanel pan = new JPanel();
pan.setBackground(Color.WHITE);
pan.setBounds(100, 100, 400, 400);
rFrame.getContentPane().add(pan);
pan.setEnabled(false);
JScrollPane scrollBar=new JScrollPane(pan,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
rFrame.add(scrollBar);
JTextArea area = new JTextArea();
area.setText(printToFrame()); //Function prints from text file
pan.add(area);
rFrame.add(pan);
rFrame.setVisible(true);
rFrame.setLayout(new FlowLayout());
rFrame.getContentPane().add(pan);
rFrame.pack();
ClientWindow window = new ClientWindow();
window.rFrame.setVisible(true);
Upvotes: 1
Views: 4506
Reputation: 3181
It's not scrolling down because the dimensions of the JPanel
is not larger than the viewport of the JScrollPane
. You either have to increase the dimensions of the JPanel
by calling *Object name*.setPreferredSize(new Dimension(int w, int h))
, OR do it the proper way by displaying the text inside a JTextArea
, which is a component made for this purpose.
Ex:
public static void main(String[] args) {
JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);
// disables editing
ta.setEditable(false);
// enable line wrap to wrap text around
ta.setLineWrap(true);
// words will not be cut off when wrapped around
ta.setWrapStyleWord(true);
// displays the text you read in
ta.append( *text you read in* );
}
Oracle has a page on how to use JTextAreas, and you can also take a look at the API for other methods to use
Upvotes: 2