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)
.
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.
Change setSize()
to setPreferredSize()
You can just use:
mainPanel.setResizeHorizontal(true);
mainPanel.setResizeVertical(true)
and your problem will be solved.
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.