我一直在寻找,包括在Java文档中,但我没有找到我的问题的明确答案:我想从一个JFrame切换到另一个JFrame点击按钮;也就是说,在新的JFrame打开时关闭旧的JFrame。我听说过" CardLayout"但我不太确定它的工作原理。有人会介意解释它,或其他一些方法吗?
由于
答案 0 :(得分:3)
以下是CardLayout
的示例正如你所听到的那样,don't use multiple JFrames.
import javax.swing.*;
import java.awt.*;
public class MainFrame
{
static JPanel homeContainer;
static JPanel homePanel;
static JPanel otherPanel;
static CardLayout cl;
public MainFrame()
{
JFrame mFrame = new JFrame("CardLayout Example");
JButton showOtherPanelBtn = new JButton("Show Other Panel");
JButton backToHomeBtn = new JButton("Show Home Panel");
cl = new CardLayout(5, 5);
homeContainer = new JPanel(cl);
homeContainer.setBackground(Color.black);
homePanel = new JPanel();
homePanel.setBackground(Color.blue);
homePanel.add(showOtherPanelBtn);
homeContainer.add(homePanel, "Home");
otherPanel = new JPanel();
otherPanel.setBackground(Color.green);
otherPanel.add(backToHomeBtn);
homeContainer.add(otherPanel, "Other Panel");
showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));
mFrame.add(homeContainer);
cl.show(homeContainer, "Home");
mFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mFrame.setLocationRelativeTo(null);
mFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mFrame.pack();
mFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
答案 1 :(得分:0)
在这种情况下,您不需要使用CardLayout进行任何操作。事实上,JFrame没有布局。
这里有一些代码来说明这个想法(假设你正在使用Java 8;否则,将final
修饰符添加到oldFrame
和newFrame
:
JFrame parent = new JFrame();
JDialog oldFrame = new JDialog("My Old Frame's Title");
JDialog newFrame = new JDialog("My New Frame's Title");
JPanel panel = new JPanel();
JButton myButton = new JButton();
myButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
oldFrame.dispose(); //closes your old frame
newFrame.setVisible(true); //opens your new frame
}
});
panel.add(myButton);
oldFrame.add(panek);
oldFrame.setVisible(true);
每当您单击按钮时,旧框架将关闭,新框架将打开。