Reputation: 21
I've recently got a project in school.
Create a Java GUI with an image as background and some textbox.
the first textbox is just a text that says: Lunch break at 1pm.
the second textbox is a countdown timer. This timer should appear 5 minutes before the end of the upcoming break, which counts down from 5:00 to 0:00 minutes every second. When reaching 0:00, the timer should respond to a text (e.g. "The Presentation will start shortly ").
Image as a background: done
Text that says: Lunch break at 1pm: done
Countdown: I'm stuck at this point. I program a countdown timer first on the console. But I really don't know how to include this countdown to a Java GUI.
Do you have any suggestions?
This is my code for the background:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Toolkit;
import javax.swing.JPanel;
import javax.swing.*;
public class Bildhintergrund extends JFrame{
//Background
public Bildhintergrund () {
setTitle(" Bildhintergrund");
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("/path/to/bild.jpg")));
setLayout(new FlowLayout());
JLabel background = new JLabel();
add(background);
//Text
JLabel text = new JLabel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
};
;
JPanel panel = new JPanel();
Dimension size = text.getPreferredSize();
getContentPane().add( text );
text.setFont(text.getFont().deriveFont((float) 58));
text.setText("Lunch break at 1pm");
/*text.setAlignmentX(0);
text.setAlignmentY(0);*/
text.setBounds(300, 300, size.width, size.height);
panel.add(text);
panel.setLayout(null);
add(text);
}
public static void main(String[] args) {
new Bildhintergrund();
}
}
This is my code for the countdown:
{
/*int Time = 5;
String time;
int seconds;
int minutes;*/
int timet= Time * 60; // Convert to seconds
long delay = timet * 1000;
do
{
minutes = timet / 60;
seconds = timet % 60;
time = minutes + ":" + seconds;
System.out.println(GetTimer());
Thread.sleep(1000);
timet = timet - 1;
delay = delay - 1000;
}
while (delay != 0);
System.out.println("Another topic will follow");
}
public static String GetTimer()
{
return time;
}
}
Upvotes: 2
Views: 346
Reputation: 813
You can use javax.swing.Timer
like this example:
javax.swing.Timer timer = new javax.swing.Timer(1000/*timer delay between calling ActionListener.actionPerformed(ActionEvent e) (in milliseconds)*/, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Second over!!!");
//put your code here
}
});
timer.setRepeats(true);//makes timer repeats forever (or until call timer.stop() method)
timer.start();
Upvotes: 1