开发者

add a scrollable jpanel to a gridlayout

I'm building a grid filled with labels. One of them contains html-text and should resize to maximum format and be scrollable. I found how to add a JScrollPane but it stays one line height, I just can't find how to resize it even when I give it开发者_运维知识库 a size of 400x400 ...

Removing getViewport() gives the same result.

JPanel grid = new JPanel(new GridLayout(1,2));

// first cell of the grid
grid.add(new JLabel("title"));

// second cell of the grid, this should be the scrollable one   
JScrollPane scroll = new JScrollPane();
scroll.getViewport().setSize(400, 400);
scroll.getViewport().add(new JLabel("<html>long<br>html<br>text</html>"));
grid.add(scrollVersion, BorderLayout.CENTER);   

Any ideas ?

Thanks a lot ...


GridLayout does not respect preferred size of the components which it lays out. It aims to make all grid cells the same size. An alternative is to use GridBagLayout, however I personally would recommend ZoneLayout which (in my opinion) is simpler, just as powerful, and much more intuitive. With the cheatsheet you can't go wrong.

As a side note, BorderLayout.CENTER is a constraint used for BorderLayout and is not compatible with GridLayout. When components are added to the owner of a GridLayout, you need not provide constraints. Components are added left to right starting at the top left corner cell using GridLayout.


Replace your GridLayout with a GridBagLayout. With the correct set of constraints, it should work like a charm. And obviously, take a look at some examples, as GridBagLayout seems quite complex, but is rather simple with some examples.


All cells of the GridLayout are designed to have the same size, so if you want one to be bigger than teh othes you must use another LayoutManager, like the GridBagLayout that Riduel suggest.

Also if your JLabel is going to have more than one line i suggest you to replace it by an uneditable JTextPane o JTextArea

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜