9

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(); } } 
0

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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).

1 Comment

finally looks like as Dockable Panel +1
0

Change setSize() to setPreferredSize()

Comments

0

I would do that same thing in a different way.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { panelToResize.setVisible(!panelToResize.isVisible()); if(panelToResize.isVisible()) { jButton1.setText("<<"); } else { jButton1.setText(">>"); } } 

Why?

1 - Hidden panel still work just like a visible one.

2 - Need to know rather the panel is extended or not? panelToResize.isVisible();

3 - The layout on your JFrame still works as intended.

Comments

-2

You can just use:

mainPanel.setResizeHorizontal(true); mainPanel.setResizeVertical(true) 

and your problem will be solved.

1 Comment

Please clean up this answer; good grammar and English is useful, along with using the provided formatting tools - but in particular you should cite why this fixes the problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.