简体   繁体   English

带有CardLayout的Java Swing GUI:返回第1张时,窗口未在第二张卡中关闭

[英]Java Swing GUI with CardLayout: Window not closing in 2nd Card when going back to 1st

I have a Swing GUI that uses a CardLayout with two cards: 我有一个使用带有两张卡的CardLayoutSwing GUI

  • main_card main_card

  • aisle_card aisle_card

When I go to the aisle_card , it properly switches to the aisle_card and closes the main_card: 当我转到aisle_card时 ,它会正确切换到aisle_card并关闭main_card:

public class Runner
{

    private static JFrame frame;
    private static JPanel cards;

    void createAndShowGUI()
    {
                //ItemsInAisleGUI gui = new ItemsInAisleGUI();
        // Create and set up the window.
        ItemsInAisleGUI gui = new ItemsInAisleGUI();

        frame = new JFrame("Shopping List");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cards = new JPanel(new CardLayout());
        JPanel mainCard = buildMainPanel();

        //JPanel aisleCard = new ItemsInAisleGUI(mainCard).aisleCard;
        JPanel aisleCard = gui.createAndShowGUI();

        cards.add(mainCard, MAIN_CARD);
        cards.add(aisleCard, AISLE_CARD);
        // Display the window.
        frame.getContentPane().add(cards);
        frame.pack();
        frame.setVisible(true);
    }


    private JPanel buildMainPanel()
    {
        JPanel mainCard = new JPanel();
        mainCard.setLayout(new GridLayout());
        mainCard.setName(MAIN_CARD);
        JPanel topRowPanel = new JPanel();
        topRowPanel.setLayout(new GridLayout(12, 2));
        topRowPanel.setName("TopRowPanel");

        //Button for the Search by Aisle Card
        JButton aisleButton = new JButton("\u25BA Search by Aisle");
        aisleButton.setName(AISLE_BUTTON);
        aisleButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                CardLayout cl = (CardLayout) (cards.getLayout());
                cl.show(cards, AISLE_CARD);
            }
        });

        //panels and labels of mainCard

        mainCard.add(topRowPanel);
        return mainCard;
    }

    public static void main(String[] args)
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                Runner r = new Runner();
                r.createAndShowGUI();
            }
        });

    }

    /**
     * @return the frame containing the application view
     */
    static JFrame getFrame()
    {

        return frame;
    }

    /**
     * @return the card that is current visible
     */
    Component getVisibleCard()
    {
        for (int i = 0; i < cards.getComponentCount(); i++)
        {
            if (cards.getComponent(i).isVisible())
            {
                return cards.getComponent(i);
            }
        }
        return null;
    }

}

However, when I am in the aisle_card and want to go back, it does open the main_card but not close the aisle_card and the console shows a NPE: 但是,当我在aisle_card中并想要返回时,它会打开main_card但不会关闭aisle_card并且控制台显示NPE:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at view.ItemsInAisleGUI$2.CloseFrame(ItemsInAisleGUI.java" referring to this line jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException at view.ItemsInAisleGUI $ 2.CloseFrame(ItemsInAisleGUI.java“指的是这一行jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public class ItemsInAisleGUI {

private static JFrame jFrame;

    public ItemsInAisleGUI() {

    }

    public JPanel createAndShowGUI()
    {
        JPanel content = new JPanel();
        content.setLayout(new GridLayout(2, 1));
        content.setName("aislePanel");

        //panel stuff

        backButton = new JButton("\u25C4 Back to Item Search");
        backButton.setName("BackButton");


        //button for going back to the main screen (Search by Item Name)
        backButton.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                Runner myrunner = new Runner();
                myrunner.createAndShowGUI();
                CloseFrame();
            }
            public void CloseFrame(){
            jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jFrame.setVisible(false);
            }
        });     

        topRowPanel.add(aisleNumberLabel);
        topRowPanel.add(aisleNumberText);
        topRowPanel.add(itemsInAisleLabel);
        topRowPanel.add(itemsInAisleText);
        topRowPanel.add(searchItemButton);
        topRowPanel.add(backButton);    
        content.add(topRowPanel);
        return content;
    }

    public static Container getContainer()
    {
        return jFrame;
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {

    }

}

Any suggestions? 有什么建议么? Thank you. 谢谢。

First, your static variables are not necessary. 首先,您的静态变量不是必需的。 Also, you have some misconceptions about what is happening: 此外,您对发生的事情有一些误解:

it does open the main_card but not close the aisle_card 它确实打开了main_card但没有关闭aisle_card

This is false. 这是错误的。 It actually doesn't up the main_card that you are thinking about. 它实际上并没有你想到的main_card。 It is opening a NEW gui entirely as can be seen in your code here: 它完全打开了一个新的gui,这可以在你的代码中看到:

public void actionPerformed(ActionEvent e)
        {
            Runner myrunner = new Runner();
            myrunner.createAndShowGUI(); // Creates completely new GUI
            CloseFrame();
        }

I don't know exactly the structure of your app, but the following should compile and should at least give you a basis on how CardLayouts work: 我不确切知道你的应用程序的结构,但是下面应该编译,至少应该给你一个关于CardLayouts如何工作的基础:

import javax.smartcardio.Card;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Runner {

    private final JFrame frame;

    private final JPanel home;
    private final JPanel second;

    public static void main(String[] args) {
        Runner runner = new Runner();
        runner.show();
    }

    public Runner() {
        this.frame = new JFrame();
        this.frame.setSize(new Dimension(500, 500));
        this.frame.setLocationRelativeTo(null);

        JPanel contentPanel = new JPanel(new CardLayout());
        frame.setContentPane(contentPanel);

        home = buildMainPanel();
        second = buildSecondPanel();

        contentPanel.add("home", home);
        contentPanel.add("second", second);

    }

    public JPanel buildMainPanel() {
        JPanel something = new JPanel(null);
        something.setBounds(0,0,500,500);
        something.setBackground(Color.black);

        JButton flipButton = new JButton("Second");
        flipButton.setBounds(0,0,100,80);
        flipButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CardLayout layout = (CardLayout) frame.getContentPane().getLayout();
                layout.show(frame.getContentPane(), "second");
            }
        });

        something.add(flipButton);
        return something;
    }

    public JPanel buildSecondPanel() {
        JPanel something = new JPanel(null);
        something.setBounds(0,0,500,500);
        something.setBackground(Color.blue);

        JButton flipButton = new JButton("Second");
        flipButton.setBounds(0,0,100,80);
        flipButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CardLayout layout = (CardLayout) frame.getContentPane().getLayout();
                layout.show(frame.getContentPane(), "home");
            }
        });

        something.add(flipButton);
        return something;
    }

    public void show() {
        frame.setVisible(true);
    }
}

If you compile this and hit the button, you can see that the background flips from black to blue, meaning the different cards are being displayed. 如果您编译并按下按钮,您可以看到背景从黑色翻转为蓝色,这意味着正在显示不同的卡片。 Hope this helps to get you on the right track. 希望这有助于让您走上正轨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java swing中如何在当前窗口(第一帧)中单击按钮时如何打开新窗口(第二帧) - how to open a new window(2nd frame) when a button is clicked in present window(1st frame) in java swing JComboBox仅在从第1到第2时才更改组件(而不是从第3到第2时) - JComboBox changes components only when going from 1st to 2nd (Not from 3rd to 2nd) 当我返回到第一个活动时,第二个活动未调用第二个活动的onCreate()函数 - When I return back to 1st Activity the onCreate() function of 2nd Activity is not called in 2nd time 如何在Java Swing中从第一个面板获取价值并插入第二个面板 - How to get value from 1st panel and insert in 2nd panel in Java Swing 卡加载时的Java Swing卡布局 - Java Swing cardlayout when card loaded Java多线程第二线程等待第一 - Java multithreading 2nd thread waiting for 1st Java继承:第2个实例调用第1个实例方法 - Java Inheritance : 2nd instance calls 1st instance method 在 Java 中的字符串中查找第 1 次和第 2 次出现的正则表达式 - Finding the 1st and 2nd occurrence of a regex in a string in Java 在 java 中将第一个数组值乘以 1,将第二个值乘以 3 - Multiply 1st array value with 1 and 2nd value with 3 in java 关于第一个init()和第二个init() - regarding 1st init() and 2nd init()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM