如何安全地退出Swing应用程序

时间:2014-10-02 15:53:05

标签: java swing

我有一个处理某些文件的程序。有时,我需要在处理过程中停止它,但是我很难完成它。我已经看到了几种可能性,但我不确定应该追求什么。它是多线程的,就像在游戏中一样吗?我找到了一些有关取消的信息,但它似乎只适用于输入数据时?我在下面包含了我的gui的代码,因为我可能只是做错了什么?

要明确,目标是无论处理的位置如何都要停止程序......

private JRadioButton blockButton, unblockButton;
private JButton btnCancel;
private ButtonGroup group;
private JLabel text;
private JButton enter;

public Gui(){
    super("Download CORS files");
    setLayout(null);

    text = new JLabel("Would you like to download data in a block of days or intermittently over time?");
    add(text);

    blockButton = new JRadioButton("Block of Days", true);
    unblockButton = new JRadioButton("Intermittent Days", false);
    btnCancel = new JButton("Cancel run");
    add(blockButton);
    add(unblockButton);
    add(btnCancel);

    group = new ButtonGroup();
    group.add(blockButton);
    group.add(unblockButton);

    // Get the size of the screen
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    // Determine the new location of the window
    int w = this.getSize().width;
    int h = this.getSize().height;
    int x = ((dim.width-w)/2)-200;
    int y = ((dim.height-h)/2)-200;
    // Move the window
    this.setLocation(x, y);

    enter = new JButton("Enter");
    enter.addActionListener(this);
    add(enter);

    text.setBounds(5,5,700,25);
    blockButton.setBounds(5, 25, 300, 25);
    unblockButton.setBounds(5,50, 300, 25);
    enter.setBounds(75,100,100,20);
    btnCancel.setBounds(300,100,100,20);

    btnCancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }});

1 个答案:

答案 0 :(得分:0)

根据情况停止处理的两种方法

  1. 停止处理I / O:如果您需要打破I / O进程,IMO最好的方法是关闭Stream,特别是对于Reader线程。您可能会抛出IOException,但这就是
  2. 的例外情况
  3. 强烈的计算/处理:如果要停止强烈的处理循环,应该在处理线程上调用Thread.interrupt()。如果您已编写处理代码,则可以在循环/代码中的某处检查Thread.interrupted()状态。另一方面,如果您使用的是第三方代码,则可能会或可能不会起作用
相关问题