さて、基本的には、私は上下にカウントするタイマーを作成しようとしています。一度に1つのタイマーだけを起動するプログラムが必要です。タイマーは2つあり、1つは変数の増分、もう1つは減分します。私はそれを正しくすることはできません、私が増分を押すと、変数が増加しますが、決して停止しません、私は減量ボタンを押しても。これをどうやって行うのですか?また、別の簡単な質問:どのように私はキーを押す方法内の値を返すのですか? Keypressはデフォルトで無効になっているので、私は困惑しました。場合2タイマーの交換方法は? Java GUIで
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class TimerTutorial extends JFrame {
JLabel timerLabel;
JButton buttonAdd, buttonMin, buttonReset;
Timer timer;
Timer timer2;
public TimerTutorial() {
setLayout(new GridLayout(2, 2, 5, 5));
buttonReset = new JButton("Press to reset");
add(buttonReset);
buttonAdd = new JButton("Press to Add");
add(buttonAdd);
buttonMin = new JButton("Press to Minus");
add(buttonMin);
timerLabel = new JLabel("Waiting...");
add(timerLabel);
event e = new event();
buttonAdd.addActionListener(e);
buttonMin.addActionListener(e);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonAdd) {
TimeClassAdd tcAdd = new TimeClassAdd();
timer = new Timer(1000, tcAdd);
timer.start();
} else if (e.getSource() == buttonMin) {
TimeClassMin tcMin = new TimeClassMin();
timer2 = new Timer(1000, tcMin);
timer2.start();
} else if (e.getSource() == buttonReset) {
timer.stop();
timer2.stop();
// This code does not work
// Need to revert counter to 0.
}
}
}
public class TimeClassAdd implements ActionListener {
int counter = 0;
public void actionPerformed(ActionEvent f) {
String status_symbol[] = new String[4];
status_symbol[0] = "Unused";
status_symbol[1] = "Green";
status_symbol[2] = "Yellow";
status_symbol[3] = "Red";
if (counter < 3) {
counter++;
timerLabel.setText("Time left: " + status_symbol[counter]);
} else {
timerLabel.setText("Time left: " + status_symbol[counter]);
}
}
}
public class TimeClassMin implements ActionListener {
int counter = 4;
public void actionPerformed(ActionEvent d) {
String status_symbol[] = new String[4];
status_symbol[0] = "Unused";
status_symbol[1] = "Green";
status_symbol[2] = "Yellow";
status_symbol[3] = "Red";
if (counter >= 3) {
counter = 3;
timerLabel.setText("Time left: " + status_symbol[counter]);
counter--;
} else if (counter == 2) {
timerLabel.setText("Time left: " + status_symbol[counter]);
counter--;
} else if (counter == 1) {
timerLabel.setText("Time left: " + status_symbol[counter]);
}
}
}
public static void main(String args[]) {
TimerTutorial gui = new TimerTutorial();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(500, 250);
gui.setTitle("Timer Tutorial");
gui.setVisible(true);
}
}
1つのファイルに複数のパブリッククラスがあるようです。これはコンパイルされますか? –
@Hovercraft:これらは内部クラスであり、すべて 'TimerTutorial'クラスに含まれています。はい、それはコンパイルされます。 – Howard
+1 [sscce](http://sscce.org/)。 – trashgod