簡體   English   中英

如何僅在按下上一個JFrame窗口的JButton后才顯示JFrame窗口?

[英]How to make a JFrame window appear only after I press the JButton of the previous JFrame window?

我的程序是關於一家超級市場的​​。 當我編譯程序時,JFrame窗口“ f1”和“ f2”都出現在屏幕上。 但是我希望首先顯示JFrame窗口'f1',然后單擊'f1'窗口的JButton'b1'之后,我希望JFrame窗口'f2'出現。 下面是我程序的delivery()方法:

public static void delivery()
{
    final JFrame f1 = new JFrame("Name");
    GridLayout grid = new GridLayout(20, 40, 10, 8);
    f1.setLayout(grid);
    f1.setVisible(true);
    f1.setSize(600,200);
    f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f1.setLocation(700,450);

    JPanel p1 = new JPanel();

    final JLabel l1 = new JLabel("Enter your name: ");

    final JTextField jt1 = new JTextField(20);

    JButton b1 = new JButton("Ok");
    b1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            input1 = jt1.getText();
            f1.dispose();
        }
    });

    p1.add(b1);
    p1.add(l1);
    p1.add(jt1);
    f1.add(p1);

    final JFrame f2 = new JFrame("Address");
    f2.setVisible(true);
    f2.setSize(600,200);
    f2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f2.setLocation(700,450);

    JPanel p2 = new JPanel();

    final JLabel l2 = new JLabel("Enter your address: ");

    final JTextField jt2 = new JTextField(20);

    JButton b2 = new JButton("Ok");
    b2.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            input2 = jt2.getText();
            f2.dispose();
        }
    });

    p2.add(b1);
    p2.add(l2);
    p2.add(jt2);
    f2.add(p2);

    JOptionPane.showMessageDialog(null, "The ordered stuff will be delivered to " +input1+ " who lives in: " +input2 , "Delivery" , JOptionPane.PLAIN_MESSAGE);
    JOptionPane.showMessageDialog(null, "Thank you for shopping at Paradise 24/7. Hope to see you again." , "Shopping Done!" , JOptionPane.PLAIN_MESSAGE);
}

使框架出現的代碼行是這個

f1.setVisible(true);

您的投放方式中的兩個框架都具有此功能。

為了使一個在另一個更改之后出現,以便在按鈕的代碼中將一個設置為可見,而另一個設置為未設置(即,盡管您顯然必須在此之前聲明f2)

 b1.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        input1 = jt1.getText();
        f1.dispose();
        //f1.setVisible(false); // or dispose if you no longer need it
        f2.setVisible(true);
    }
});

只是一個建議:更好的方法可能是使用JDialog 這將允許您從用戶等待響應的表單中獲取輸入,然后提示下一個輸入。 單擊此處獲取對話框教程

在為框架/面板添加組件時,您可能還需要查看一些布局。 GridLayoutBorderLayoutFlowLayout

只需添加代碼f2.setVisible(true); 在Button的actionPerformed()中。

例如

f1.setBounds(whatever);
f2.setBounds(whatever);

//add button in JFrame and actionListener
f1.setVisible(true);
f2.setVisible(false);

actionPerformed(ActionEvent e)
{
     f2.setVisible(true);
}

然后,您必須先閱讀JavaDocs並閱讀一些適用於Java初學者的優秀電子書,例如Java 2 Complete Reference,O'Really-Java Swing將對您有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM