How to make that JPanel on JScrollPanel with GridLayout fill only width but not fill height?

StackOverflow https://stackoverflow.com/questions/23409503

  •  13-07-2023
  •  | 
  •  

Question

I try to make layout as shown below. But I have a poroblem with adding new MyPanels. The first MyPanel fill all its parent (midPanel). How to make that MyPanel take only what is needed height and fill width?

enter image description here

public class Main extends JFrame {

JPanel upPanel = new JPanel();
JPanel midPanel = new JPanel();
JPanel downPanel = new JPanel();
JButton button = new JButton("add new Panel");

Main() {
    this.setSize(800, 600);
    this.setLayout(new BorderLayout());

    this.add(upPanel, BorderLayout.PAGE_START);
    JScrollPane jsp = new JScrollPane(midPanel);
    this.add(jsp, BorderLayout.CENTER);
    this.add(downPanel, BorderLayout.PAGE_END);
    this.midPanel.setLayout(new GridLayout(0, 1, 3, 3));

    upPanel.add(button);

    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            midPanel.add(new MyPanel());
            midPanel.updateUI();

        }
    });

}

public static void main(String[] args) {
    new Main().setVisible(true);
}
}
class MyPanel extends JPanel {

    MyPanel() {
        this.setLayout(new GridLayout(2, 5, 5, 5));
        this.setBorder(BorderFactory.createRaisedBevelBorder());

        this.add(new JLabel("Nomo:"));
    }
}
Was it helpful?

Solution

The problem is that you add the mid-Panel in CENTER. Center use the full free space. Set the midPanel to BorderLayout and add another panel to it on North and than add there the MyPanels that works.

public class Main extends JFrame {

JPanel upPanel = new JPanel();
JPanel newMidPanel = new JPanel();
JPanel downPanel = new JPanel();
JButton button = new JButton("add new Panel");

Main() {
    this.setSize(800, 600);
    this.setLayout(new BorderLayout());
    JPanel midPanel = new JPanel(new BorderLayout());
    this.add(upPanel, BorderLayout.PAGE_START);
    JScrollPane jsp = new JScrollPane(midPanel);
    this.add(jsp);
    this.add(downPanel, BorderLayout.PAGE_END);
    this.newMidPanel = new JPanel(new GridLayout(0, 1, 3, 3));
    upPanel.add(button);
    midPanel.add(newMidPanel, BorderLayout.NORTH);
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            newMidPanel.add(new MyPanel());
            newMidPanel.updateUI();

        }
    });
}

public static void main(String[] args) {
    new Main().setVisible(true);
}
}

class MyPanel extends JPanel {

MyPanel() {
    this.setLayout(new GridLayout(2, 5, 5, 5));
    this.setBorder(BorderFactory.createRaisedBevelBorder());

    this.add(new JLabel("Nomo:"));
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top