我在Java中有一个应用程序,在JFrame内的LayeredPane中有2个JPanel。当我调整窗框尺寸时,所有面板都会根据其组件调整大小。这是我调整大小的函数的代码:
mainFrame.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void componentResized(ComponentEvent e) {
// Resize components of JFrame to fit new size
int width = e.getComponent().getWidth();
int height = e.getComponent().getHeight();
if(containerJPanel != null) {
containerJPanel.setBounds(0, 0,
width-DEFAULT_PANEL_MINUS_WITDH, height-DEFAULT_PANEL_MINUS_HEIGHT);
containerJPanel.setPreferredSize(new Dimension(width-DEFAULT_PANEL_MINUS_WITDH, height-DEFAULT_PANEL_MINUS_HEIGHT));
}
if(mainJPanel != null) {
mainJPanel.setBounds(0, 0,
width-DEFAULT_PANEL_MINUS_WITDH, height-DEFAULT_PANEL_MINUS_HEIGHT);
mainJPanel.setPreferredSize(new Dimension(width-DEFAULT_PANEL_MINUS_WITDH, height-DEFAULT_PANEL_MINUS_HEIGHT));
}
if(loadingPanel != null) {
loadingPanel.setBounds(0, 0,
width-DEFAULT_PANEL_MINUS_WITDH, height-DEFAULT_PANEL_MINUS_HEIGHT);
loadingPanel.setPreferredSize(new Dimension(width-DEFAULT_PANEL_MINUS_WITDH, height-DEFAULT_PANEL_MINUS_HEIGHT));
}
}
@Override
public void componentMoved(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void componentHidden(ComponentEvent e) {
// TODO Auto-generated method stub
}
});
以下是变量定义:
/** Main frame **/
mainFrame = new JFrame();
mainFrame.setBounds(100,100,DEFAULT_WINDOW_WIDTH,DEFAULT_WINDOW_HEIGHT);
mainFrame.setPreferredSize(new Dimension(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT));
mainFrame.getContentPane().setLayout(new BorderLayout(0, 0));
containerJPanel = new JLayeredPane();
mainFrame.getContentPane().add(containerJPanel, BorderLayout.CENTER);
containerJPanel.setBounds(0,0,
DEFAULT_WINDOW_WIDTH-DEFAULT_PANEL_MINUS_WITDH, DEFAULT_WINDOW_HEIGHT-DEFAULT_PANEL_MINUS_HEIGHT);
/** Main Panel **/
mainJPanel = new JPanel();
mainJPanel.setBounds(0,0,
DEFAULT_WINDOW_WIDTH-DEFAULT_PANEL_MINUS_WITDH, DEFAULT_WINDOW_HEIGHT-DEFAULT_PANEL_MINUS_HEIGHT);
containerJPanel.add(mainJPanel, new Integer(0), 0);
/** Loading Panel **/
loadingPanel = new JPanel();
containerJPanel.add(loadingPanel, new Integer(1), 0);
loadingPanel.setBounds(0,0,
DEFAULT_WINDOW_WIDTH-DEFAULT_PANEL_MINUS_WITDH, DEFAULT_WINDOW_HEIGHT-DEFAULT_PANEL_MINUS_HEIGHT);
loadingPanel.setLayout(new BorderLayout(0, 0));
loadingPanel.setOpaque(false);
关键是要有两个面板,这样一个面板一次可见。 我确定我做错了什么,但我无法实现它! 谢谢你的帮助。
答案 0 :(得分:0)
正如c0der所说:请参阅使用CardLayout的示例。