当我将子面板之一设置为不可见时,如何使主面板中的子面板保持在原来的位置?
我所拥有的看起来像:
[ (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 http://download.oracle.com/javase/tutorial/uiswing/layout/card.html在各个单元格内,不要将其设置为不可见,而是切换到空面板。
下面的代码演示了这一点。之内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");
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)