このコードを main() に入れようとしています
public class TestPane extends JPanel {
private JTextField field;
private JButton button;
private int tick;
private Timer timer;
public TestPane() {
field = new JTextField(10);
field.setEditable(false);
button = new JButton("Start");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button.setEnabled(false);
tick = 0;
timer.start();
}
});
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Success" + tick);
field.setText(Integer.toString(++tick));
if (tick > 4) {
timer.stop();
button.setEnabled(true);
}
}
});
timer.setInitialDelay(0);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(field, gbc);
add(button, gbc);
}
}
これが行うことは次のとおりです。ウィンドウが開き、そのスタートボタンを押すとスタートボタンが表示され、一定時間後にテキストが表示されます
私がやりたいことは、コードをメイン関数に配置することです.何が起こるべきかというと、スタートボタンがなく、プログラムを実行すると、一定の時間間隔で領域にテキストを設定する必要があります(ボタンを押さずに自動的に)
私は試しましたが失敗しました ここにコードがあります
public static void main(String args[]) {
//int tick;
// Timer timer;
final Timer timer = new Timer(1000, new ActionListener() {
int tick=0;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Success" + ++tick);
if (tick > 4) {
((Timer)e.getSource()).stop();
}
}
});
timer.setInitialDelay(0);
System.out.format("About to schedule task.%n");
new NewJFrame();
System.out.format("Task scheduled.%n");
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
どうすればよいかわかりません。