如何在用户点击JButton时关闭JFrame窗口?

时间:2013-06-30 14:40:42

标签: java swing jbutton multiple-instances billing

我的节目是关于一家超市。我在delivery()方法中创建了一个名为b1的JButton。我希望当用户按下按钮b1时关闭JFrame窗口。但不幸的是我不知道该怎么做。请帮忙。以下是我的程序的delivery()方法:

public static void delivery()
{
    JFrame f = new JFrame("Name");
    f.setVisible(true);
    f.setSize(600,200);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.setLocation(700,450);

    JPanel p = new JPanel();

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

    final JTextField jt = new JTextField(20);

    JButton b1 = new JButton("Ok");
    b1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            input = jt.getText();
        }
    });

    p.add(b1);
    p.add(l);
    p.add(jt);
    f.add(p);

    String b = JOptionPane.showInputDialog(null, "Please enter your address in one single line:");
    JOptionPane.showMessageDialog(null, "The ordered stuff will be delivered to " +input+ " who lives in: " +b , "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);
}

3 个答案:

答案 0 :(得分:7)

答案 1 :(得分:2)

setVisible()应该为你做的伎俩

    public static void delivery()
{
    JFrame f = new JFrame("Name");
    f.setVisible(true);
    f.setSize(600,200);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.setLocation(700,450);
    JPanel p = new JPanel();
    final JLabel l = new JLabel("Enter your name: ");
    final JTextField jt = new JTextField(20);
    JButton b1 = new JButton("Ok");
    b1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            input = jt.getText();
            f.setVisible(false);
        }
    });
    p.add(b1);
    p.add(l);
    p.add(jt);
    f.add(p);
    String b = JOptionPane.showInputDialog(null, "Please enter your address in one single line:");
    JOptionPane.showMessageDialog(null, "The ordered stuff will be delivered to " +input+ " who lives in: " +b , "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);
}

答案 2 :(得分:1)

只需致电f.dispose()即可关闭JFrame