0

I want to set the size of the JTextPane according to the size of the panel so that when i add other panels, it changes accordingly. But it just gives a small text pane in the center and when i add some text, it's size changes accordingly.

JPanel panel = new JPanel();
JTextPane txt = new JTextPane();
JScrollPane pane = new JScrollPane();
pane.add(txt);
panel.add(pane,BorderLayout.CENTER);
add(pane);

now the jtextpane just appears at the center of the screen like a small box. I want it to appear according to the size of the panel

kiheru
  • 6,588
  • 25
  • 31
UsamaMan
  • 695
  • 10
  • 28
  • Almost but not quite a full question -- if I put this into a method in a class that extends JFrame and run it, it terminates without showing anything. I can add calls to pack() and setVisible(), but it still doesn't make the panels visible. You're calling add() on an unknown class. This is why posters are so often requested to give an *executable* example; one we can paste into an IDE and RUN, to demonstrate what the problem is. While we're at it, the phrase "according to the size of the panel" leaves us guessing a little bit; do you mean you want the text pane to fill the panel? – arcy Sep 24 '13 at 11:24
  • Related [example](http://stackoverflow.com/a/17510427/1057230) – nIcE cOw Sep 24 '13 at 11:55

2 Answers2

6

JPanel uses FlowLayout by default which sizes components according to their preferred sizes. You can use BorderLayout which will use the maximum area possible.

Also using constraints such as BorderLayout.CENTER has no effect unless the container is actually using BorderLayout. Dont add components to the JScrollPane. This will replaces all components within the view of the component. Instead set the JTextPane as the ViewPortView, for example

JPanel panel = new JPanel(new BorderLayout());
JTextPane txt = new JTextPane();
JScrollPane pane = new JScrollPane(txt);
// pane.add(txt); remove
panel.add(pane, BorderLayout.CENTER);

Read:

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Is this edit valid : `JPanel panel = new JPanel(new GridLayout());` now panel is using `GridLayout`, though `panel.add(pane, BorderLayout.CENTER);` here it seems like it's using `BorderLayout` !!! – nIcE cOw Sep 24 '13 at 14:12
3

You added pane twice. Add panel to your base (a JFrame?) instead and remember to actually set your JPanel to use BorderLayout.

Birb
  • 866
  • 10
  • 23