Java - 在按钮按下时交换多个JFrames

3
这是我第一次研究JFrames和JPannels,现在遇到了一些问题。
我的目标是这样的,我想要一个启动屏幕,然后根据用户的按钮选择,它会切换到另一个屏幕。起初,我只有两个屏幕,但随着进展,将会有多个屏幕。我已经查看了CardLayout,虽然很好用,但不符合我的需求。这是我的代码。
Main.java
import java.awt.BorderLayout;
public class Main extends JFrame {

private JPanel contentPane;
protected boolean someCondition = false;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Main frame = new Main();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    if( someCondition == false ){
        showTest();
        someCondition = test.needToReg();
    }else{
        showTest2();
    }
}

private void showTest(){
    contentPane.removeAll();
    contentPane.add(new test());
    setContentPane(contentPane);
    revalidate();
    repaint();
}

private void showTest2(){
    contentPane.removeAll();
    contentPane.add(new test2());
    setContentPane(contentPane);
    revalidate();
    repaint();
}

}

test.java

import javax.swing.JPanel;


public class test extends JPanel {
    private JTextField textField;
    protected static boolean toReg = false;

    /**
     * Create the panel.
     */
    public test() {
        setLayout(null);

        JButton btnNewButton = new JButton("New button");
        btnNewButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("Mouse Clicked");
                System.out.println("Before " + toReg);
                toReg = true;
                System.out.println("After " + toReg);
            }
        });
        btnNewButton.setBounds(188, 166, 89, 23);
        add(btnNewButton);

        textField = new JTextField();
        textField.setBounds(150, 135, 86, 20);
        add(textField);
        textField.setColumns(10);

        JRadioButton rdbtnNewRadioButton = new JRadioButton("New radio button");
        rdbtnNewRadioButton.setBounds(6, 166, 109, 23);
        add(rdbtnNewRadioButton);
    }

    public static boolean needToReg(){
        return toReg;
    }
}

test2.java

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;


public class test2 extends JPanel {

    /**
     * Create the panel.
     */
    public test2() {
        setLayout(null);

        JButton btnNewButton = new JButton("New button");
        btnNewButton.setBounds(56, 59, 89, 23);
        add(btnNewButton);

        JLabel lblNewLabel = new JLabel("New label");
        lblNewLabel.setBounds(122, 165, 46, 14);
        add(lblNewLabel);

    }
}

使用我提供的输出运行程序,我得到了这个结果。
Mouse Clicked
Before false
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true
Mouse Clicked
Before true
After true

我希望你能看懂我的意图并且帮助我完成这个任务,谢谢。


2
我已经看过CardLayout,虽然它很好,但这不是我想走的路线,我想先尝试另一种方法。祝你好运,但我认为不使用最佳方式是愚蠢的。我投票支持关闭此问题,因为它太过局限。 - Andrew Thompson
1
@AndrewThompson 寻求通过了解其他做事的方式来扩展知识有何不妥?在我看来,仅因为你正在学习的方式不是最佳方式就限制自己的知识似乎有些愚蠢。我认为提高的方法是尝试各种方法并观察结果。仅仅做到最好的方式并不能让你变得更好。这只是我的个人观点。 - Kyle93
1
欢迎大家前来,但请不要带着拆墙锤!我们将教你如何仅凭头脑的力量拆除一堵墙。记得自备安全头盔。 - Andrew Thompson
2
@AndrewThompson 试图通过使用完全愚蠢的例子来证明自己的观点并不是证明你的方法最好的好方法,对我来说,这只能显示出不成熟。然而,根据你的情况进行操作。虽然这可能不是最好的、最简单、最安全的方法,但如果它有效,那就行了。是的,这可能很傻。但是,如果那些人使用了那种方法,发现它有多么困难和愚蠢,你不认为他们在将来使用撬棒时会更加欣赏和发现它更容易吗?值得思考。 - Kyle93
1
当你学习如何使用CardLayout时,也要学会如何使用布局管理器。Swing是设计用于与布局管理器一起使用的。你不应该使用null布局和setBounds()。 - camickr
显示剩余3条评论
1个回答

1

请尝试这个

在主框架中点击screenSwapper按钮后,将添加一个新的面板到主框架中,该面板可以有多个组件,我只添加了一个按钮

第二次点击时,此面板将被删除,并添加第二个面板到主框架中并删除上一个面板。

当您连续点击按钮时,会进行交换

如果您想要保留已创建的面板,则可以使用两个单例模式,例如MyPanel1和MyPanel2

您可以在每个面板上添加更多组件并进行测试。

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame {

    public boolean switcher;
    public JPanel currentPanel;
    public JPanel panel1;
    public JPanel panel2;

    public Test() {

        this.switcher = false;
        this.currentPanel = null;
        this.setSize(200, 200);

        panel1 = new JPanel();

        JButton screenSwapper = new JButton("Screen Swapper");

        panel1.add(screenSwapper);

        panel2 = new JPanel();

        this.getContentPane().setLayout(new GridLayout(2, 2));
        this.getContentPane().add(panel1);
        this.getContentPane().add(panel2);

        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        screenSwapper.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {

                if (switcher == false) {
                    currentPanel = new MyPanel1();
                    switcher = true;

                    if (panel2.getComponentCount() != 0) {
                        panel2.removeAll();
                    }

                } else {

                    switcher = false;
                    currentPanel = new MyPanel2();

                    if (panel2.getComponentCount() != 0) {
                        panel2.removeAll();
                    }

                }

                panel2.add(currentPanel);
                panel2.repaint();
                panel2.revalidate();
            }

        });

    }

    public static void main(String[] args) {
        Test t = new Test();
    }

}

这是第一个面板。
import java.awt.BorderLayout;
import java.awt.Button;

import javax.swing.JPanel;


public class MyPanel1 extends  JPanel{



     public MyPanel1() {
        // TODO Auto-generated constructor stub

        this.setLayout(new BorderLayout());

        this.add(new Button("Button1"));

    }




}

这是第二个面板。
import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JPanel;


public class MyPanel2 extends JPanel {



    public MyPanel2() {
        this.setLayout(new BorderLayout());

        this.add(new JButton("button2"));
    }
}

这可能有效,但是应该在repaint()之前进行revalidate()。另外,对于多个面板的要求怎么样?每当您看到使用if/else语句或硬编码面板名称的代码时,您都知道随着面板数量的增加,该代码将不易修改。 CardLayout已经有一个API来管理它。没有必要试图重新发明轮子。 - camickr
@camickr 是的,我完全同意你的观点。在重新验证方面有一点小错误,对此我很抱歉。但是用户不喜欢卡片布局,所以这是一个我可以快速提供的替代解决方案。 - Sanyam Goel
@camickr 这里我没有使用任何设计模式,这样我们肯定可以避免很多修改。我可以发布一个包括最佳软件工程实践的好解决方案,但我想让思考过程更容易,并让用户使用适当的模式并从中得出完美的解决方案 :)。希望您同意这一点。我们不相信喂食,这是我在stackoverflow上一直被告知的 :)。 - Sanyam Goel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接