2016-01-12 78 views
0

我在eclipse中的windowbuilder創建的run()方法中有計時器。如何停止該線程內的線程/定時器?

我不知道如何從另一種方法停止該計時器。例如,通過添加

if(MenuWindow.gameStarted == false) gameTimer.stop(); 

即是這裏,但是當我將其更改爲false時,它不會改變。它變爲false並返回true(我認爲)。

我改變變量從類MenuWindow

package krystofee.niggatycoon; 

public class MenuWindow { 

private static JFrame frame; 
static boolean gameStarted; 
static GameWindow game; 

/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       MenuWindow window = new MenuWindow(); 
       window.frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the application. 
*/ 
public MenuWindow() { 
    initialize(); 
} 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 
    frame = new JFrame(); 
    frame.setBounds(100, 100, 450, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 

    JButton btnNewButton = new JButton("Start"); 
    btnNewButton.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent arg0) { 
      GameWindow game = new GameWindow(); 
      game.StartGame(); 
      gameStarted = true; 
      frame.setVisible(false); 
     } 
    }); 
    btnNewButton.setBounds(144, 154, 146, 43); 
    frame.getContentPane().add(btnNewButton); 
} 

public static void open() { 
    frame.setVisible(true); 
    game = null; 
    gameStarted = false; 
} 
} 

而且有GameWindow

public class GameWindow<E> { 

private JFrame frame; 
static JProgressBar progressBar1; 
static JButton upGardenerButton; 
private Timer gameTimer; 

public static Player player; 
public static Worker worker; 
private static JLabel labelMoney; 
private JTable table; 
private JLabel lblMultiplier; 
boolean timerStop; 

/** 
* Create the application. 
*/ 
public GameWindow() { 
    worker = new Worker(50, 75, 5000); 
    player = new Player(); 

    initialize(); 
} 

protected void endGame() { 
    frame.dispose(); 
    timerStop = true; 
} 

public void StartGame() { 
    EventQueue.invokeLater(new Runnable() { 

     int gardenerTime = 0; 

     public void run() { 
      try { 
       GameWindow<Object> window = new GameWindow<Object>(); 
       window.frame.setVisible(true); 
       ActionListener taskPerformer = new ActionListener() { 

        @Override 
        public void actionPerformed(ActionEvent arg0) { 
         gardenerTime += 10; 
         progressBar1.setValue(gardenerTime);   
         if(gardenerTime >= worker.time) { 
          player.money.add(worker.getProfit()); 
          gardenerTime = 0; 
         } 

         labelMoney.setText(player.money.getMoney()+"$");  

         if(gardenerTime % 100 == 0) System.out.println("Timer bezi. " + MenuWindow.gameStarted); 

         if(MenuWindow.gameStarted == false) gameTimer.stop(); 
        } 
       }; 

       int delay = 10; 
       gameTimer = new Timer(delay, taskPerformer); 
       gameTimer.start(); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 
    frame = new JFrame(); 
    frame.getContentPane().setBackground(UIManager.getColor("Panel.background")); 
    frame.setBounds(100, 100, 571, 287); 

    WindowListener exitListener = new WindowAdapter() { 

     @Override 
     public void windowClosing(WindowEvent e) { 
      int confirm = JOptionPane.showOptionDialog(
       null, "Opravdu chceš ukončit hru?", 
       "Konec?!", JOptionPane.YES_NO_OPTION, 
       JOptionPane.QUESTION_MESSAGE, null, null, null); 
      if (confirm == 0) { 
       frame.setVisible(false); 
       endGame(); 
       System.out.println("timerstop: "+timerStop); 
       //MenuWindow.open(); 
      } 
     } 
    }; 

    frame.addWindowListener(exitListener); 
    frame.getContentPane().setLayout(null); 

    progressBar1 = new JProgressBar(); 
    progressBar1.setBounds(6, 89, 146, 27); 
    progressBar1.setStringPainted(true); 
    progressBar1.setMaximum(worker.time); 
    progressBar1.setMinimum(0); 
    progressBar1.setString(worker.getProfit()+"$"); 
    frame.getContentPane().add(progressBar1); 

    upGardenerButton = new JButton(worker.getUpgradeCost()+" $ "+"level "+worker.level); 
    upGardenerButton.setBounds(159, 89, 165, 27); 
    upGardenerButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      if(player.money.getMoney() >= worker.getUpgradeCost()) { 
       worker.upgrade(); 
      } 
     } 
    }); 
    frame.getContentPane().add(upGardenerButton); 

    JPanel panel = new JPanel(); 
    panel.setBounds(6, 37, 175, 32); 
    panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); 
    panel.setBackground(Color.LIGHT_GRAY); 
    frame.getContentPane().add(panel); 
    panel.setLayout(new MigLayout("", "[149px]", "[23px]")); 

    labelMoney = new JLabel(""); 
    labelMoney.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); 
    panel.add(labelMoney, "cell 0 0,alignx trailing,aligny baseline"); 

    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); 
    tabbedPane.setBounds(357, 6, 192, 236); 
    frame.getContentPane().add(tabbedPane); 

    JScrollPane scrollPane = new JScrollPane(); 
    tabbedPane.addTab("Upgrades", null, scrollPane, null); 

    String[] columnNames = {"Upgrades", ""}; 
    Object[][] data = 
    { 
     {"Vozík +2", "2000$"}, 
     {"Kalhoty +3", "15000$"}, 
     {"Šperháky +4", "50000$"}, 
     {"Auto *2",  "200000$"}, 
    }; 

    DefaultTableModel model = new DefaultTableModel(data, columnNames){ 
     @Override 
     public boolean isCellEditable(int row, int column) { 
       if(column != 1) return false; 
       else return true; 
      } 
    }; 
    JTable table = new JTable(model); 

    Action upgradeMultiplier = new AbstractAction() 
    { 
     int count = 0; 
     public void actionPerformed(ActionEvent e) 
     { 
      JTable table = (JTable)e.getSource(); 
      int modelRow = Integer.valueOf(e.getActionCommand());     
      String sPrice = (String) table.getModel().getValueAt(modelRow, 1); 
      int price = Integer.parseInt(sPrice.substring(0,sPrice.length()-1));  
      String sMultip = (String) table.getModel().getValueAt(modelRow, 0); 
      if(sMultip.lastIndexOf("*") != -1) { 
       int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("*")+1,sMultip.length())); 
       if(player.money.getMoney() >= price) { 
        player.money.deduct(price); 
        worker.multiplyMultiplier(multip); 
        ((DefaultTableModel)table.getModel()).removeRow(modelRow); 
       } 
      } else if(sMultip.lastIndexOf("+") != -1) { 
       int multip = Integer.parseInt(sMultip.substring(sMultip.lastIndexOf("+")+1,sMultip.length())); 
       if(player.money.getMoney() >= price) { 
        player.money.deduct(price); 
        worker.plusMultiplier(multip); 
        ((DefaultTableModel)table.getModel()).removeRow(modelRow); 
       } 
      } 
      progressBar1.setString(worker.getProfit()+"$"); 
      lblMultiplier.setText(worker.multiplier+"x"); 
     } 
    }; 

    ButtonColumn buttonColumn = new ButtonColumn(table, upgradeMultiplier, 1); 
    buttonColumn.setMnemonic(KeyEvent.VK_D); 

    scrollPane.setViewportView(table); 

    JLabel lblMultiplierStatic = new JLabel("Multiplier:"); 
    lblMultiplierStatic.setBounds(17, 9, 55, 16); 
    frame.getContentPane().add(lblMultiplierStatic); 

    lblMultiplier = new JLabel("1x"); 
    lblMultiplier.setBounds(83, 9, 43, 16); 
    frame.getContentPane().add(lblMultiplier); 

    JButton btnNewButton = new JButton("New button"); 
    btnNewButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      timerStop = true; 
     } 
    }); 
    btnNewButton.setBounds(65, 185, 98, 26); 
    frame.getContentPane().add(btnNewButton); 


} 
} 

看待問題GameWindow頂部,我改變gameStarted的價值封閉框架GameWindow後,它改變它爲false,所以它應該停止計時器...但是...不是。

回答

1

您是否注意到您在GameWindow.StartGame()中創建的Runnable內創建了另一個GameWindow實例?

+0

你是對的!但它沒有解決這個問題。 +1 thx – Krystofee

1

您是否嘗試過製作gameStarted volatile?您正在另一個線程中檢查狀態,儘管我不知道invokeLater的細節,但可能是您看到了gameStarted的陳舊值。如果這不起作用,你可能會錯過代碼中的某些東西,你可能是最有資格發現的代碼!

+0

Thanx的答案!我會嘗試。 – Krystofee