当我将其中一个子面板设置为不可见时,如何使主面板中的子面板保持原样?
我看起来像:
[ (Panel1) (Panel2) (Panel3) (Panel4) ]
当我执行panel3.setVisible(false)时,它看起来像:
[ (Panel1) (Panel2) (Panel4) ]
我希望它看起来像:
[ (Panel1) (Panel2) (Panel4) ]
我正在使用GridBagLayout,我的mainPanel声明如下所示:
final JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints();
我添加了一个新的面板,如:
final JTextField valueTextField = new JTextField(); valueTextField.setPreferredSize(new Dimension(80,25)); valueTextField.setName("Value"); c.gridx =0; panel.add(valueTextField,c);
如果需要我会提供更多代码,我不关心我使用哪种布局,只要它能得到我想要的东西.
解决方法
我建议在单个单元格中使用
CardLayout
,而不是将其设置为不可见,而是切换到空面板.
下面的代码演示了这一点.在hidePanel()中,有两个选项可以隐藏当前启用了CardLayout路径的单元格.
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"); } } }