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();
}
}
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
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With