Как закрыть JFrame в середине программы - PullRequest
0 голосов
/ 16 июня 2010
public class JFrameWithPanel extends JFrame implements ActionListener, ItemListener
{
    int packageIndex;
    double price;
    double[] prices = {49.99, 39.99, 34.99, 99.99};

    DecimalFormat money = new DecimalFormat("$0.00");
    JLabel priceLabel = new JLabel("Total Price: "+price);
    JButton button = new JButton("Check Price");
    JComboBox packageChoice = new JComboBox();
    JPanel pane = new JPanel();
    TextField text = new TextField(5);
    JButton accept = new JButton("Accept");
    JButton decline = new JButton("Decline");
    JCheckBox serviceTerms = new JCheckBox("I Agree to the Terms of Service.", false);
    JTextArea termsOfService = new JTextArea("This is a text area", 5, 10);

    public JFrameWithPanel()
    {
        super("JFrame with Panel");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pane.add(packageChoice);
        setContentPane(pane);
        setSize(250,250);
        setVisible(true);

        packageChoice.addItem("A+ Certification");
        packageChoice.addItem("Network+ Certification ");
        packageChoice.addItem("Security+ Certifictation");
        packageChoice.addItem("CIT Full Test Package");

        pane.add(button);
        button.addActionListener(this);

        pane.add(text);
        text.setEditable(false);
        text.setBackground(Color.WHITE);
        text.addActionListener(this);

        pane.add(termsOfService);
        termsOfService.setEditable(false);
        termsOfService.setBackground(Color.lightGray);

        pane.add(serviceTerms);
        serviceTerms.addItemListener(this);

        pane.add(accept);
        accept.addActionListener(this);

        pane.add(decline);
        decline.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e)
    {
        packageIndex = packageChoice.getSelectedIndex();
        price = prices[packageIndex];
        text.setText("$"+price);

        Object source = e.getSource();

        if(source == accept)
        {
            if(serviceTerms.isSelected() == false)
            {
                JOptionPane.showMessageDialog(null,"Please accept the terms of service.", "Terms of Service", JOptionPane.ERROR_MESSAGE);
            }
            else
            {
                JOptionPane.showMessageDialog(null,"Thank you. We will now move on to registering your product.");
                pane.dispose();
            }
        }
        else if(source == decline)
        {
            System.exit(0);
        }
    }

    public void itemStateChanged(ItemEvent e)
    {
        int select = e.getStateChange();
    }

    public static void main(String[] args)
    {
        String value1;
        int constant = 1, invalidNum = 0, answerParse, packNum, packPrice;

        JOptionPane.showMessageDialog(null,"Hello!"+"\nWelcome to the CIT Test Program.");

        JOptionPane.showMessageDialog(null,"IT WORKS!");
    }



}//class

Как заставить этот кадр закрыться, чтобы мои диалоги сообщений JOptionPane могли продолжаться в программе, не выходя из программы полностью.

РЕДАКТИРОВАТЬ: Я пытался .dispose (), но я получаю это:

cannot find symbol
symbol  : method dispose()
location: class javax.swing.JPanel
                pane.dispose();
                    ^

Ответы [ 2 ]

0 голосов
/ 11 декабря 2011

Я знаю, что это может быть глупым ответом, но иногда самые очевидные вещи вызывают проблемы.Я не видел, как вы импортировали javax.swing в свой код ... Вы это сделали?

0 голосов
/ 16 июня 2010

Попробуйте: this.dispose() вместо.

JPanel не имеет этого метода, но JFrame имеет

edit

Inваш основной, вы не называете свой кадр:

public static void main(String[] args)  {
    String value1;
    int constant = 1, invalidNum = 0, answerParse, packNum, packPrice;

    JOptionPane.showMessageDialog(null,"Hello!"+"\nWelcome to the CIT Test Program.");

    JOptionPane.showMessageDialog(null,"IT WORKS!");
    }

Попробуйте добавить его и увидите разницу:

public static void main(String[] args)  {
    String value1;
    int constant = 1, invalidNum = 0, answerParse, packNum, packPrice;

    JOptionPane.showMessageDialog(null,"Hello!"+"\nWelcome to the CIT Test Program.");

    JOptionPane.showMessageDialog(null,"IT WORKS!");
    new JFrameWithPanel(); //<-- creating a JFrameWithPanel
}

Также в методе «действие выполнено» вы показываете диалоговое окно изатем избавиться, вероятно, вы хотите сделать это наоборот.

if(serviceTerms.isSelected() == false) {
    JOptionPane.showMessageDialog(null,"Please accept the terms of service.", "Terms of Service", JOptionPane.ERROR_MESSAGE);
} else {
    this.dispose();
    JOptionPane.showMessageDialog(null,"Thank you. We will now move on to registering your product.");
}

Результат:

main http://img194.imageshack.us/img194/7038/capturadepantalla201006x.png

Затем следует

результат http://img85.imageshack.us/img85/8513/capturadepantalla201006l.png

edit 2

Попробуйте следующий код, он должен показывать рамку, а когда вы нажимаете кнопку «закрыть», он должен показывать диалоговое окно,это то, что вы ищете?

import javax.swing.*;
import java.awt.event.*;

class FrameDemo {
    public static void main( String [] args ) {
        final JFrame frame = new JFrame("Main frame");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new JPanel(){{
            add( new JLabel("This is the main content"));
            add( new JButton("Close"){{
                addActionListener( new ActionListener(){
                    public void actionPerformed(ActionEvent e ) {
                        frame.dispose();
                        JOptionPane.showMessageDialog(frame,"IT WORKS!");

                    }
                });
            }});
        }});
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );

    }
}
...