У меня есть GUI с формой для людей, чтобы заполнить, и я хотел бы поставить таймер обратного отсчета в верхнем правом углу страницы
Heres метод для таймера, чтобы получить оставшееся время. Скажем, мой класс формы - это FillForm, и метод таймера находится в таймере.
Как установить динамический (постоянно обновляющийся) таймер внутри графического интерфейса?
public String getRemainingTime() {
int hours = (int)((this.remainingTime/3600000) % 60);
int minutes = (int)((this.remainingTime/60000) % 60);
int seconds = (int)(((this.remainingTime)/1000) % 60);
return(format.format(hours) + ":" + format.format(minutes)+
":" + format.format(seconds));
}
GUI построен с использованием построителя GUI NetBeans.
Вы должны абстрагировать свой таймер в компоненте пользовательского интерфейса. JLabel
кажется наиболее подходящим, поскольку это текст, который вы хотите отобразить.
public class TimerLabel extends JLabel {
// Add in your code for 'format' and 'remainingTime'.
// Note that the first time that 'getText' is called, it called from the constructor
// if the superclass, so your own class is not fully initialized at this point.
// Hence the 'if (format != null)' check
public TimerLabel() {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}
public String getRemainingTime() {
int hours = (int) ((this.remainingTime / 3600000) % 60);
int minutes = (int) ((this.remainingTime / 60000) % 60);
int seconds = (int) (((this.remainingTime) / 1000) % 60);
return (format.format(hours) + ":" + format.format(minutes) + ":" + format.format(seconds));
}
@Override
public String getText() {
if (format != null) {
return getRemainingTime();
} else {
return "";
}
}
Попробуй это:
import javax.swing.Timer;
Timer timer=new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//code here
}
});
timer.start();
//timer.stop()
Выполняется каждый второй таймер.
Try This Demo :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
class Counter {
private static int cnt;
static JFrame f;
public static void main(String args[]) {
f=new JFrame();
f.setSize(100,100);
f.setVisible(true);
ActionListener actListner = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
cnt += 1;
if(cnt%2==0)
{
f.setVisible(true);
}
else
{
f.setVisible(false);
}
}
};
Timer timer = new Timer(500, actListner);
timer.start();
}
}
"Могу ли я добавить это в Swing.JPanel или что-то в этом роде?"
Просто поместите его в конструктор вашего класса формы. Объявите Timer timer;
как член класса, а не локально, чтобы вы могли использовать метод start()
как в кнопке actionPerformed
. Что-то вроде
import javax.swing.Timer;
public class GUI extends JFrame {
public Timer timer = null;
public GUI() {
timer = new Timer (500, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (timerGetsToZero) {
((Timer)e.getSource()).stop();
} else {
timeLabel.setText(getRemainingTime());
}
}
});
}
private void startButtonActionPerformed(ActionEvent e) {
timer.start();
}
}