我在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的顶部,在关闭框架GameWindow之后,我更改了gameStarted的值,并将其更改为false,因此它应该停止计时器...但是...不。

最佳答案

您是否注意到要在GameWindow中创建的Runnable中创建GameWindow.StartGame()的另一个实例?

08-18 06:08