我想在我的主帧中添加一个计时器按钮,但它在另一个类中,我不知道如何在我的主类中使用它。我的框架中需要一个计时器按钮,但没有另一个类我就无法做到。在那堂课上,我不能调用我的主框架。这是我的代码:
class ButtonTimer extends Thread{
private JButton button = new JButton(" ");
private int count = 1;
public ButtonTimer() {
Timer time = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
button.setText(String.valueOf(count));
count++;
}
});
time.start();
JFrame frame1 = new JFrame();
frame1.add(button);
frame1.setBounds(0, 20, 100, 50);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.pack();
frame1.setVisible(true);
}
}
public class game {
public static void main(String[] args) {
JFrame frame2 = new JFrame();
frame2.setBounds(0, 0, 1000, 5000);
frame2.setVisible(true);
JLayeredPane jlp = new JLayeredPane();
jlp.setBounds(0, 0, 1000, 500);
frame2.add(jlp);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonTimer();
}
});
}
}
我该怎么做?
你可以...
创建一个自定义JButton
,将Timer
内部包装到它。
这使您可以将按钮和计时器自行包含在一个单元中,并在您想要的任何位置重复使用它......
你可以...
创建一个自定义Timer
,该接受对JButton
的引用,并在每个触发器上自动更新文本...
你可以...
创建自定义ActionListener
甚至Action
,该甚至,该JButton
引用并更新文本,然后将其传递到您选择的Timer
实例中...
试一试。在这里,我们在您的主框架中创建一个 JButton,然后在另一个类的 actionExecute 上设置文本。
public class game1 {
private static JFrame frame2;
private static JButton button1=new JButton(" ");
public static void main(String[] args) {
frame2 = new JFrame();
frame2.setBounds(0, 0, 1000, 5000);
JLayeredPane jlp = new JLayeredPane();
jlp.setBounds(0, 0, 1000, 500);
jlp.add(button1);
frame2.add(jlp);
frame2.add(button1);
frame2.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonTimer();
}
});
}
private static class ButtonTimer {
private JButton button = new JButton(" ");
private int count = 1;
public ButtonTimer() {
javax.swing.Timer timer = new javax.swing.Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button.setText(String.valueOf(count));
button1.setText(String.valueOf(count));
count++;
}
});
timer.start();
JFrame frame1 = new JFrame();
frame1.add(button);
frame1.setBounds(0, 20, 100, 50);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.pack();
frame1.setVisible(true);
}
}
}