我已经用Java创建了一个GUI程序,你可以在选择10秒,5分钟或1分钟后启动和停止计时器。这些数字会倒计时,但它们会在2中递增。所以它会变为10,8,6,4,2,0
其他一切工作正常,但我似乎无法弄清楚柜台有什么问题。这是我的代码。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class countdownPanel extends JPanel
{
private ImageIcon banner;
private JComboBox selectCombo;
private JButton stopButton, startButton;
private JLabel picture, theCount;
private Timer timer;
public countdownPanel()
{
setLayout(new BorderLayout());
setBackground(Color.black);
//Banner Image
banner = new ImageIcon ("banner.jpg");
picture = new JLabel(banner);
//Count Down selecter
JComboBox selectCombo = new JComboBox();
selectCombo.addItem("10 Seconds");
selectCombo.addItem("1 Minute");
selectCombo.addItem("5 Minutes");
//countdown components
theCount = new JLabel(" 0");
theCount.setFont(new Font("Helvetica", Font.BOLD, 200));
timer = new Timer(1000, new TimerListener());
//Stop Start Buttons
startButton = new JButton("Start");
stopButton = new JButton("Stop");
ButtonListener listener = new ButtonListener();
startButton.addActionListener(new ButtonListener());
stopButton.addActionListener(new ButtonListener());
selectCombo.addActionListener(new ComboListener());
timer.addActionListener(new TimerListener());
//GUI set up
add(picture, BorderLayout.NORTH);
add(startButton, BorderLayout.WEST);
add(selectCombo, BorderLayout.CENTER);
add(stopButton, BorderLayout.EAST);
add(theCount, BorderLayout.SOUTH);
}
//combo box listener
private class ComboListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JComboBox levelCombo = (JComboBox) event.getSource();
Object selected = levelCombo.getSelectedItem();
if(selected.toString().equals("10 Seconds"))
theCount.setText("10");
if(selected.toString().equals("1 Minute"))
theCount.setText("60");
if(selected.toString().equals("5 Minutes"))
theCount.setText("300");
}
}
//Start and stop button listeners
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
//starts timer
if (event.getSource()== startButton)
timer.start();
//stops timer
if (event.getSource()== stopButton)
timer.stop();
}
}
private class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String A = theCount.getText();
int count = Integer.parseInt(A);
while(count < 0)
{
count--;
theCount.setText(""+ count);
}
if(count == 0)
theCount.setText(" GO!");
}
}
}