问题描述:

The above frame contains gridlayout with two rows. First row is text area,second is a panel with two checkboxes. I want to increase height of first row so that first row should be 75% of Total height and second row should be 25%. How can I do that? Here is my code snippet:

 setLayout(new GridLayout(2, 0, 0, 0));

Panel text_panel = new Panel();

add(text_panel);

text_panel.setLayout(new GridLayout(1, 0, 0, 0));

JTextArea textArea = new JTextArea();

textArea.setText("text to be displayed");

JScrollPane scroll = new JScrollPane (textArea);

text_panel.add(scroll);

textArea.setLineWrap(true);

textArea.setWrapStyleWord(true);

textArea.setEditable(false);

Border border = BorderFactory.createLineBorder(Color.GRAY);

textArea.setBorder(border);

textArea.setFont(new Font("Arial",Font.PLAIN,12));

textArea.setCaretPosition(0);

textArea.requestFocus();

Panel checebox_panel = new Panel();

checebox_panel.setBackground(Color.WHITE);

add(checebox_panel);

checebox_panel.setLayout(new GridLayout(1, 0, 0, 0));

androidCheckBox = new JCheckBox("Open start page");

androidCheckBox.setBackground(Color.WHITE);

androidCheckBox.addItemListener(itemListener);

androidCheckBox.setSelected(true);

checebox_panel.add(androidCheckBox);

eclipseCheckBox = new JCheckBox("register for updates");

eclipseCheckBox.setBackground(Color.WHITE);

eclipseCheckBox.addItemListener(itemListener);

eclipseCheckBox.setSelected(true);

checebox_panel.add(eclipseCheckBox);

网友答案:

This is not possible with GridLayout. GridLayout will always use even spacing. Look into another layout manager.

Here is a good reference:

https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

网友答案:

With GridLayout you can't have two rows that are different sizes. Look into BoxLayout. Something like this:

JPanel content = new JPanel();
frame.getContentPane().add(content);
LayoutManager layout = new BoxLayout(content, BoxLayout.Y_AXIS);
Box boxes[] = new Box[2];
boxes[0] = Box.createHorizontalBox();
boxes[1] = Box.createHorizontalBox();

boxes[0].createGlue();
boxes[1].createGlue();

content.add(boxes[0]);
content.add(boxes[1]);  

JPanel panel = new JPanel();    
JPanel panel2 = new JPanel();

panel.setPreferredSize(new Dimension(500,300));
panel2.setPreferredSize(new Dimension(500,200));

boxes[0].add(panel);
boxes[1].add(panel2);

Using setPreferredSize is never optimal, but it works. This is just an example of how you could do it, I'm sure there is better ways though! ;)

相关阅读:
Top