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?
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:"));
}
}
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:"));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.