问题描述
当我将其中一个子面板设置为不可见时,如何使主面板中的子面板保持原样?
How do I make the subpanels within my main panel stay where they are when I set one of the subpanels to be invisible?
我的样子: / p>
What I have looks like:
[ (Panel1) (Panel2) (Panel3) (Panel4) ]
当我执行 panel3.setVisible(false)
时,它看起来像:
When I do panel3.setVisible(false)
it then looks like:
[ (Panel1) (Panel2) (Panel4) ]
我希望它看起来像:
[ (Panel1) (Panel2) (Panel4) ]
我使用的是GridBagLayout,我的mainPanel声明如下:
I am using the GridBagLayout and my mainPanel declaration looks like:
final JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
我添加了一个新的面板,如:
and I add an new panel like:
final JTextField valueTextField = new JTextField();
valueTextField.setPreferredSize(new Dimension(80, 25));
valueTextField.setName("Value");
c.gridx =0;
panel.add(valueTextField, c);
如果需要,我会提供更多代码,我不关心我使用哪种布局它得到了我想要的东西。
I'll provide more code if needed and I don't care which layout I use as long as it gets me what I want.
推荐答案
我建议使用,而不是将其设置为不可见,改为切换到空面板。
I suggest using a CardLayout
within the individual cells, and instead of setting it to invisible, switch to an empty panel instead.
下面的代码演示了这一点。在 hidePanel()
中,有两个选项可以隐藏当前启用 CardLayout
路径的单元格。
The code below demonstrates this. Within hidePanel()
there are two options to hide the cell with the CardLayout
route currently enabled.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class InvisiblePanels {
public static void main(String... args) throws Exception {
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
frame.add(new MyPanel(), c);
c.gridx = 1;
frame.add(new MyPanel(), c);
c.gridx = 2;
frame.add(new MyPanel(), c);
frame.pack();
frame.setVisible(true);
}
private static class MyPanel extends JPanel {
CardLayout layout;
public MyPanel() {
layout = new CardLayout();
setLayout(layout);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hidePanel();
}
});
add(button, "visible");
add(new JPanel(), "invisible");
layout.show(this, "visible");
}
public void hidePanel() {
// setVisible(false);
layout.show(this, "invisible");
}
}
}
这篇关于SetVisible(false)更改我的Panel中组件的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!