Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize JPanel from JFrame

I want to create a little game in Java using Netbeans. For now I have a JFrame and two JPanels.
The JFrame contains both JPanels and a button. My intent is to click on this button and resize one of the JPanels (from 0 to >0 width).
Till now I menaged to resize the frame but I can't figure out how to resize the JPanel.
This is what I've done so far:

Structure
   frame
    |_ panel 1
    |_ panel 2
    |_ button

 __________________
|  _        _      |
| | |      | |    _|
| | |      | |   | |
| | |      | |   |>|  
| | |      | |   |_|
| |_|      |_|     |
|__________________|

on click should expand frame and panel
 ______________________
|  _        _____      |
| | |      |     |    _|
| | |      |     |   | |
| | |      |     |   |>|  ->
| | |      |     |   |_|
| |_|      |_____|     |
|______________________|

This is the JPanel to resize

public class ToResize extends javax.swing.JPanel {

    ...

    public void resize(int width) {
        this.setSize(new Dimension(this.getWidth() + width, this.getHeight()));
    }
}

This is the JFrame with the button

public class MyFrame extends javax.swing.JFrame {

    ...

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        if (panelToResize.getWidth() == 0) {
            panelToResize.resize(100);
        } else {
            panelToResize.resize(-100);
        }
        validate();
    }
}
like image 550
mastaH Avatar asked Jul 12 '11 15:07

mastaH


2 Answers

1) if you'll resize JFrame too, then you have to call

a/ setPrefferedSize(getPrefferedSize()+-) for JFrame.pack();

b/ setPrefferedSize(getPrefferedSize()+-) for panelToResize and then call JFrame.pack();

2/ if you only change size betweens JPanels and JFrame size stays remained, then you have to call revalidate() plus repaint() to the panelToResize,

3/ but everything depends of used LayoutManager

like image 65
mKorbel Avatar answered Oct 23 '22 00:10

mKorbel


My intent is to click on this button and resize one of the JPanels (from 0 to >0 width).

Use a CardLayout, or a JSplitPane, or call panel.setVisible(boolean).

like image 42
Andrew Thompson Avatar answered Oct 23 '22 00:10

Andrew Thompson