2014-10-02 95 views
0

我有一个处理某些文件的程序。有时候,我需要在处理过程中阻止它,但是在如何完成这个过程中遇到困难。我已经看到了几种可能性,但我不确定要追求什么。多线程,就像在游戏中一样吗?我发现了一些关于取消的信息,但它似乎只适用于数据输入过程中?我在下面包括我的GUI的代码,也许我只是做了错误的事情?如何安全地退出Swing应用程序

需要明确的是,我们的目标是停止程序,无论它在哪里处理?

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); 
     }}); 
+5

调用'System.exit(1);'。这将阻止它。 – 2014-10-02 15:54:44

+1

如果您试图从一个Swing窗口终止一个选项,那不是线程安全的。您需要设置一个任务,以允许Swing的功能正常工作。 – Compass 2014-10-02 15:56:16

+2

http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int) – StackFlowed 2014-10-02 15:56:23

回答

0

两种方式停止处理,视情况而定

  1. 停止处理I/O:如果您需要摆脱I/O进程,IMO最好的办法是关闭Stream,特别是Reader线程。您可能会抛出IOException异常,但这是异常情况的例外情况
  2. 激烈的计算/处理:如果您想停止激烈的处理循环,则应该在处理Thread上调用Thread.interrupt()。如果您已经编写了处理代码,则可以检查循环/代码中某处的Thread.interrupted()状态。另一方面,如果您使用的是第三方代码,这可能会也可能不会工作
+0

因此,Thread.interrupt()是否可以按下按钮的形式工作,这会停止程序的处理和关闭?我并不担心I/O,但真正从没有任务管理器的情况下停止处理。也许这是一个完全可以接受的方法,但仅仅依靠这种方法感觉不对。 – Iakona 2014-10-03 16:52:35

+0

是的,你可以通过点击按钮的动作来实现这一点 – ControlAltDel 2014-10-03 17:08:11

+0

我不明白你的评论的最后一句话。你能澄清吗? – ControlAltDel 2014-10-03 17:08:56