我有一个有三个面板的JFrame:
======================================
| |
| |
| Green Panel |
| |
| |
| |
======================================
| Blue Panel |
| |
======================================
| Button1 Button2 |
| |
======================================
当我点击Button1时,我想隐藏蓝色面板并禁用Button1。当我点击Button2时,我想显示蓝色面板并禁用Button2。
我知道我可以使用setVisible(boolean)来显示和隐藏组件。
我的问题是,当我隐藏蓝色面板时,如何使绿色面板扩展并占用以前由蓝色面板占用的空间?相反,当我点击Button2时,我希望蓝色面板重新出现,绿色面板又回到之前的尺寸?
如果不对面板的尺寸进行硬编码,可能会出现这种情况,因为我可能想要增加窗口尺寸。
答案 0 :(得分:0)
您可以使用JPanel的getHeight()方法,如下所示
JPanel pnlGreen = new JPanel();
JPanel pnlRed = new JPanel();
if(e.getSource() == btnOne){
pnlRed.setHeight(pnlRed.getHeight()+pnlGreen.getHeight());
//Panel and Button show/hide code
}
else if(e.getSource() == btnTwo){
pnlGreen.setHeight(pnlRed.getHeight()+pnlGreen.getHeight());
//Panel and Button show/hide code
}
if you want to apply this on window resize then add this code to window minimize and maximize event
答案 1 :(得分:0)
此代码使用BorderLayout
执行您所需的操作。
它不漂亮但是有效。
public class TESTMAIN extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TESTMAIN frame = new TESTMAIN();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TESTMAIN() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
JPanel greenPanel = new JPanel();
greenPanel.setBackground(Color.GREEN);
panel.add(greenPanel, BorderLayout.CENTER);
final JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.BLUE);
panel.add(bluePanel, BorderLayout.SOUTH);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new BorderLayout(0, 0));
JButton button1 = new JButton("New button");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
bluePanel.setVisible(false);
}
});
panel_1.add(button1, BorderLayout.WEST);
JButton button2 = new JButton("New button");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bluePanel.setVisible(true);
}
});
panel_1.add(button2, BorderLayout.EAST);
}
}