Java swing计时器在Jpanel中不起作用

时间:2016-06-29 21:03:39

标签: java swing timer

我正在尝试在包含2个JPanel的边框布局中构建一个带有swing计时器的JFrame,这两个JPanel都具有假定可以协同工作的Timer,但只有其中一个可以工作。工具栏面板中的计时器不起作用。

public class trygame extends JFrame implements ActionListener {

private JPanel _toolbar = new JPanel(); 
private Play game;
private Timer _timer;
private int _count = 0;

public trygame(Level lvl) {
    super("Elemental Brick Breaker");
    _timer = new Timer(1000,this);
    _timer.start();
    File jarPath=new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
    String levelsPath=jarPath.getParentFile().getAbsolutePath();    
    String path = levelsPath + "\\src\\pics\\gameIcon.png";
    ImageIcon icon = new ImageIcon(path);
    this.setIconImage(icon.getImage());
    setLayout(new BorderLayout());
    JButton returnButton = new JButton("Return");
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(5,5,5,5);
    Dimension d = new Dimension(150,50);
    returnButton.setPreferredSize(d);
    returnButton.setMinimumSize(d);
    _toolbar.add(returnButton,c);
    _toolbar.setBackground(Color.black);
    add(_toolbar, BorderLayout.SOUTH);
    game  = new Play(lvl.getBoard());
    add(game, BorderLayout.CENTER);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(615,750);
    setVisible(true);
    setResizable(false);
    game.setFocusable(true);
}

@Override
public void actionPerformed(ActionEvent e) {

    if (e.getSource() == _timer) {
        _count++;
        JLabel jlabel = new JLabel("     Timer: " + Integer.toString(_count));
        int Destroyed = game.getDestroyed();
        JLabel jlabel2 = new JLabel("    Destroyed: " + Integer.toString(Destroyed));
        jlabel.setFont(new Font("Verdana",1,20));
        jlabel2.setFont(new Font("Verdana",1,20));
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        Dimension d = new Dimension(150,50);
        jlabel.setPreferredSize(d);
        jlabel2.setMinimumSize(d);
        _toolbar.add(jlabel,c);
        _toolbar.add(jlabel2,c);
        _toolbar.setBorder(new LineBorder(Color.BLACK));
    }   
}

}

0 个答案:

没有答案