Resize JPanel from JFrame

I want to create a little Java game using Netbeans. At the moment I have a JFrame and two JPanels.
JFrame contains both JPanels and a button. I intend to click this button and resize one of the JPanels (from 0 to> 0).
So far I have managed to resize the frame, but I cannot figure out how to resize the JPanel.
This is what I have done so far:

Structure frame |_ panel 1 |_ panel 2 |_ button __________________ | _ _ | | | | | | _| | | | | | | | | | | | | |>| | | | | | |_| | |_| |_| | |__________________| on click should expand frame and panel ______________________ | _ _____ | | | | | | _| | | | | | | | | | | | | |>| -> | | | | | |_| | |_| |_____| | |______________________| 

This is a JPanel for resizing

 public class ToResize extends javax.swing.JPanel { ... public void resize(int width) { this.setSize(new Dimension(this.getWidth() + width, this.getHeight())); } } 

This is a jframe with a 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(); } } 
+6
source share
5 answers

1) if you also resize the jframe you need to call

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

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

2 / if you only resize the betweens JPanels and JFrame , the remaining remains, you must call revalidate() plus repaint() in panelToResize ,

3 /, but it all depends on the used LayoutManager

+5
source

I intend to click this button and resize one of the JPanels (from 0 to> 0).

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

+1
source

Change setSize() to setPreferredSize()

0
source

I would do the same thing differently.

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

Why?

1 - The hidden panel still works as visible.

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

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

0
source

You can simply use:

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

and your problem will be solved.

-2
source

Source: https://habr.com/ru/post/892584/


All Articles