Hi I'm trying to call the paint method every time in a game loop.At the moment the screen pops up with a label and a button once the button has been pressed the label and button go which i want but i can't get the paint method to start i tried j.repaint() & j.validate() neither accessed paint method.Any help would be appreciated.
package sgame;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SGame extends JPanel
{
public static void main(String[] args)
{
final JFrame window = new JFrame("hello");
final JPanel window1 = new JPanel();
Timer loop = new Timer(1000, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
GameLoop(window1);
}
});
Window(window, loop);
}
public static void Window(final JFrame window, final Timer loop)
{
final JButton b1 = new JButton("GO!");
b1.setLocation(210, 300);
b1.setSize(70, 50);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(500, 500);
window.setLocation(420, 170);
window.setBackground(Color.BLACK);
final JLabel Title = new JLabel("Snake", JLabel.CENTER);
Title.setFont(new Font("Times New Roman", Font.ITALIC, 60));
Title.setVerticalAlignment(JLabel.CENTER);
Title.setForeground(Color.WHITE);
window.add(b1);
window.add(Title);
b1.addActionListener(new ActionListener() // runs when buttons pressed
{
#Override
public void actionPerformed(ActionEvent e) // clears header,button and starts timer
{
b1.invalidate();
b1.setVisible(false);
Title.setVisible(false);
Title.invalidate();
loop.start();
}
});
}
public static void GameLoop(JPanel j)
{
// Call paint method
}
public void paintComponent(Graphics g)
{
g.setColor(Color.yellow);
g.drawRect(30, 30, 30, 30);
}
}
The paintComponent() method in SGame is never called because you didn't instanciate any SGame object. And window1 has not been added to the frame.
Something like this should be better :
public class SGame extends JPanel {
private Timer loop;
public SGame(){
loop = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
gameLoop();
}
});
}
public static void main(String[] args) {
final JFrame window = new JFrame("hello");
final JButton b1 = new JButton("GO!");
b1.setLocation(210, 300);
b1.setSize(70, 50);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(500, 500);
window.setLocation(420, 170);
window.setBackground(Color.BLACK);
final JLabel Title = new JLabel("Snake", JLabel.CENTER);
Title.setFont(new Font("Times New Roman", Font.ITALIC, 60));
Title.setVerticalAlignment(JLabel.CENTER);
Title.setForeground(Color.WHITE);
window.add(b1);
window.add(Title);
b1.addActionListener(new ActionListener() { // runs when buttons pressed
#Override
public void actionPerformed(ActionEvent e) // clears header,button
{
b1.invalidate();
b1.setVisible(false);
Title.setVisible(false);
Title.invalidate();
SGame sg = new SGame();
window.add(sg);
sg.start();
}
});;
}
public void start(){
loop.start();
}
public void gameLoop() {
repaint();
}
#Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.yellow);
g.drawRect(30, 30, 30, 30);
}
}
Related
I want the GUI to show "focus gained" when the user clicks on the button and
"focus lost" when clicking anywhere else. But it always shows "focus gained".
Main Code:
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;
public class focuslistener extends JFrame {
private Container c;
private JButton jb1;
private Font f;
private JTextArea ta1;
focuslistener() {
inticompo();
}
public void inticompo() {
c = this.getContentPane();
c.setBackground(Color.yellow);
c.setLayout(null);
f = new Font("Arial", Font.ITALIC + Font.BOLD, 18);
jb1 = new JButton("Clicked");
jb1.setBounds(50, 10, 250, 80);
jb1.setForeground(Color.red);
jb1.setBackground(Color.blue);
jb1.setFont(f);
c.add(jb1);
ta1 = new JTextArea();
ta1.setFont(f);
ta1.setBounds(10, 110, 400, 300);
ta1.setForeground(Color.black);
ta1.setBackground(Color.red);
c.add(ta1);
jb1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent fe) {
ta1.setText("focus Gained");
}
#Override
public void focusLost(FocusEvent fe) {
ta1.setText("focus Lost");
}
});
}
public static void main(String[] args) {
focuslistener a = new focuslistener();
a.setVisible(true);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setBounds(50, 100, 500, 500);
a.setTitle("hello");
}
}
What I am trying to achieve is that the program would draw a line in the middle of the frame as soon as the user has clicked draw. But sadly nothing is happening other than "frame 3" is disappearing. Any ideas about how I could fix the problem?
Here is the method:
Windowj is my frame. Frame3 is the previous frame please don't worry about it.
public static void graf() {
frame3.setVisible(false);
windowj.setSize(400, 500);
windowj.setLocationRelativeTo(null);
windowj.setResizable(false);
windowj.setLayout(null);
windowj.setVisible(true);
windowj.setTitle("Graphs");
windowj.setDefaultCloseOperation(EXIT_ON_CLOSE);
xinwindow.setBounds(30,40, 90, 40);
yinwindow.setBounds(100,100,90,40);
thefunction.setBounds(200,300,90,40);
draw.setBounds(300,200,90,40 );
windowj.add(xinwindow);
windowj.add(yinwindow);
windowj.add(thefunction);
windowj.add(draw);
c.setPreferredSize(new Dimension(300,200));
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowj.add(c);
c.revalidate();
c.repaint();
}
And here is the paintcomponent method:
private static Component c = new JComponent() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(50, 0, 70 , 100);
}
};
Any help would be appreciated, and please try to keep it simple, I am a beginner. :)
I will assume you use windowj as your JFrame and that what will happen when you click draw button your use windowj.setVisible(false) and that will make your window disappear
so remove it
2nd thing is you need to put your Component in windowj as windowj.add(c); in your draw ActionListener at actionPerformed before c.revalidate();
and here a little code that I wrote to understand what I mean:
public class DrawLine {
private JFrame windowj = new JFrame();
private JButton draw = new JButton();
private static int width = 640, height = 480;
private static JComponent c = new JComponent() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine((width/2) - 1, 0, (width/2) +1 , height);
}
};
public DrawLine() {
windowj.setDefaultCloseOperation(windowj.EXIT_ON_CLOSE);
windowj.setSize(width, height);
windowj.setLayout(new FlowLayout());
windowj.setResizable(false);
windowj.setLocationRelativeTo(null);
windowj.setVisible(true);
draw = new JButton("Draw");
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//i don't know why you set windowj(windowj) false but that will close your window
//windowj.setVisible(false);
//add component to windowj(windowj)
windowj.add(c);
c.revalidate();
c.repaint();
}
});
c.setPreferredSize(new Dimension(width, height-100));
windowj.add(draw);
}
public static void main(String[] args) {
new DrawLine();
}
}
Here is the modified code:
private JFrame frame3, windowj;
private JPanel xinwindow, yinwindow,thefunction;
private JButton draw;
private static Component c = new JComponent() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(50, 0, 70 , 100);
}
};
public DrawLine() {
xinwindow = new JPanel();
yinwindow = new JPanel();
thefunction = new JPanel();
draw = new JButton("Draw");
//i ignored frame3 as you said so just ignore my implementation here
frame3 = new JFrame();
frame3.setVisible(false);
windowj = new JFrame();
windowj.setSize(400, 500);
windowj.setLocationRelativeTo(null);
windowj.setResizable(false);
windowj.setLayout(null);
windowj.setVisible(true);
windowj.setTitle("Graphs");
windowj.setDefaultCloseOperation(EXIT_ON_CLOSE);
/*i used setBackground(Color.anycolor); to make it easier for me to know where
your window is in your frame*/
xinwindow.setBackground(Color.RED);
xinwindow.setBounds(30,40, 90, 40);
yinwindow.setBackground(Color.yellow);
yinwindow.setBounds(100,100,90,40);
thefunction.setBounds(200,300,90,40);
thefunction.setBackground(Color.green);
draw.setBounds(300,200,90,40 );
windowj.add(xinwindow);
windowj.add(yinwindow);
windowj.add(thefunction);
windowj.add(draw);
//here use setBonds instead of setPreferredSize
c.setBounds(100, 200, 200, 200);
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowj.add(c);
c.revalidate();
c.repaint();
}
});
}
public static void main(String[] args) {
new DrawLine();
}
hope that solve your problem.
I made the Card Layout Working completely fine but what happened now is I added a keylistener to the object character which is a JLabel so whenever the person presses up the character should move up but it does absolutely nothing!
I also tried replacing it with a button which moves it when clicked and it worked completely fine. Also I tried changing the event meaning I changed that if they press up then the image of the town map would change but still no effect so it seems there is something wrong with my KeyListener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.*;
import javax.swing.*;
#SuppressWarnings({ "unused", "serial" })
public class FinalBlowzXC extends JFrame implements KeyListener{
public static JPanel game=new JPanel();
public static JPanel mainmenu=new JPanel(null);
public static JPanel loginpanel=new JPanel(null);
public static JPanel tutorial=new JPanel(null);
public static JPanel registration=new JPanel(null);
public static JPanel town_map=new JPanel(null);
public JTextField username= new JTextField("Username");
public JTextField password=new JTextField("Password");
public JLabel bglogin=new JLabel();
public JLabel character=new JLabel();
public JButton log_in=new JButton();
public JButton register=new JButton();
CardLayout page= new CardLayout();
public String level="";
public int charx=350;
public int chary=435;
public static void main(String []args)
{
new FinalBlowzXC().setVisible(true);
}
public FinalBlowzXC()
{
super("Final Blowz Xchanged");
setSize(640,510);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
game.setLayout(page);
game.add(mainmenu, "1");
game.add(loginpanel, "2");
game.add(tutorial, "3");
game.add(registration, "4");
game.add(town_map, "5");
add(game);
opening();
}
public void opening()
{
page.show(game, "1");
JLabel bgmainmenu;
JButton start;
JButton exit;
bgmainmenu = new JLabel();
start = new JButton();
exit = new JButton();
bgmainmenu.setIcon(new ImageIcon(getClass().getResource("/FF-XV.jpg")));
bgmainmenu.setBounds(0,0,640,480);
mainmenu.add(bgmainmenu);
mainmenu.add(start);
start.setBounds(280, 360, 70, 20);
start.setBorder(null);
start.setBorderPainted(false);
start.setContentAreaFilled(false);
start.setOpaque(false);
start.addActionListener(new Start());
exit.setBounds(280, 385, 70, 20);
mainmenu.add(exit);
exit.setBorder(null);
exit.setBorderPainted(false);
exit.setContentAreaFilled(false);
exit.setOpaque(false);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
class Start implements ActionListener{
public void actionPerformed(ActionEvent e) {
login();
}
}
public void login()
{
page.show(game, "2");
bglogin.setIcon(new ImageIcon(getClass().getResource("/FF-XV Login.jpg")));
bglogin.setBounds(0, 0, 640, 480);
username.setBounds(300, 285, 85, 15);
username.setBorder(null);
username.setForeground(Color.WHITE);
username.setOpaque(false);
password.setBounds(300, 310, 85, 20);
password.setBorder(null);
password.setForeground(Color.WHITE);
password.setOpaque(false);
log_in.setBounds(280, 335, 50, 45);
log_in.setBorder(null);
log_in.setBorderPainted(false);
log_in.setContentAreaFilled(false);
log_in.setOpaque(false);
log_in.addActionListener(new Log_in());
register.setBounds(335, 335, 55, 45);
register.setBorder(null);
register.setBorderPainted(false);
register.setContentAreaFilled(false);
register.setOpaque(false);
register.addActionListener(new Register());
loginpanel.add(username);
loginpanel.add(password);
loginpanel.add(bglogin);
loginpanel.add(log_in);
loginpanel.add(register);
}
class Log_in implements ActionListener{
public void actionPerformed(ActionEvent e)
{
Tutorial();
}
}
class Register implements ActionListener{
public void actionPerformed(ActionEvent e)
{
page.show(game, "4");
}
}
public void Tutorial()
{
page.show(game, "3");
JLabel bgtutorial=new JLabel();
JLabel animeforward=new JLabel();
JLabel animeright=new JLabel();
JLabel animeleft=new JLabel();
JButton next=new JButton();
JLabel animebackward=new JLabel();
bgtutorial.setIcon(new ImageIcon(getClass().getResource("/FF-XV Tutorial.jpg")));
bgtutorial.setBounds(0, 0, 640, 480);
animeforward.setIcon(new ImageIcon(getClass().getResource("walkanimofficialfront.gif")));
animeforward.setBounds(115, 230, 30, 30);
animeright.setIcon(new ImageIcon(getClass().getResource("walkanimofficialright.gif")));
animeright.setBounds(190, 315, 30, 30);
animeleft.setIcon(new ImageIcon(getClass().getResource("walkanimofficialleft.gif")));
animeleft.setBounds(45, 315, 30, 30);
animebackward.setIcon(new ImageIcon(getClass().getResource("walkanimofficialback.gif")));
animebackward.setBounds(115, 405, 30, 30);
next.setBounds(530, 430, 100, 30);
next.setBorder(null);
next.setBorderPainted(false);
next.setContentAreaFilled(false);
next.setOpaque(false);
next.addActionListener(new Next());
tutorial.add(next);
tutorial.add(animeright);
tutorial.add(animeleft);
tutorial.add(animebackward);
tutorial.add(animeforward);
tutorial.add(bgtutorial);
}
class Next implements ActionListener{
public void actionPerformed(ActionEvent e)
{
town();
}
}
public void town()
{
page.show(game, "5");
JLabel map=new JLabel();
map.setIcon(new ImageIcon(getClass().getResource("/FF-XV Town.jpg")));
map.setBounds(0, 0, 640, 480);
character.setIcon(new ImageIcon(getClass().getResource("standfront.png")));
character.setBounds(charx, chary, 30, 35);
town_map.add(character);
town_map.add(map);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_UP)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialfront.gif")));
character.setLocation(character.getX(), character.getY()+5);
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialright.gif")));
character.setLocation(character.getX()+5, character.getY());
}
if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialleft.gif")));
character.setLocation(character.getX()-5, character.getY()+5);
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialback.gif")));
character.setLocation(character.getX(), character.getY()-5);
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
it seems there is something wrong with my KeyListener
A KeyEvent is only generated for the component with focus. A JLabel is not focusable by default so it will never receive any events.
Don't use a KeyListener.
Instead you should be using Key Bindings.
See Motion Using the Keyboard for working examples of using Key Bindings that does exactly what you want.
how can i use a Jbutton in a class to trigger a panelSlider effect which is in a button actionPerformed in another class
Find the code here
public class programDisplay extends javax.swing.JPanel { /** * Creates new form programDisplay */
public programDisplay() {
initComponents();
}
here is an example for sliding effect of panel. you can take it as a reference and implement your requirement.
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SlidingPanel {
JPanel panel;
public void makeUI() {
panel = new JPanel();
panel.setBackground(Color.RED);
panel.setBounds(0, 0, 400, 400);
JButton button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((JButton) e.getSource()).setEnabled(false);
new Timer(1, new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.setLocation(panel.getX() - 1, 0);
if (panel.getX() + panel.getWidth() == 0) {
((Timer) e.getSource()).stop();
System.out.println("Timer stopped");
}
}
}).start();
}
});
panel.add(button);
JFrame frame = new JFrame("Sliding Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SlidingPanel().makeUI();
}
});
}
}
UPDATE :
in HomePane.java
rightPane rPane = new rightPane();
JPanel lPane = new leftPane(rPane);
in leftPane.java
private rightPane rPane;
public leftPane(final rightPane rPane)
{
pane = new JPanel();
this.rPane = rPane;
staffLogin = new JButton("STAFF LOGIN");
adminLogin = new JButton("ADMIN LOGIN");
guestLogin = new JButton("GUEST LOGIN");
staffLogin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
rPane.trigerEvent();
}
});
this.setLayout(null);
this.add(staffLogin);
this.add(adminLogin);
this.add(guestLogin);
staffLogin.setFont(new Font("Serif", Font.BOLD, 20));
adminLogin.setFont(new Font("Serif", Font.BOLD, 20));
guestLogin.setFont(new Font("Serif", Font.BOLD, 20));
staffLogin.setBounds(20, 10, 200, 50);
adminLogin.setBounds(20, 75, 200, 50);
guestLogin.setBounds(20, 140, 200, 50);
this.setBorder(BorderFactory.createLineBorder(Color.BLUE));
pane.setBorder(BorderFactory.createLineBorder(Color.red));
}
Like the one we add into the corner of presentation slides.
I already have SwingX library added and working, in case that could help with something.
Basically, you want to use a JLabel for displaying the date/time, a javax.swing.Timer set to a regular interval to update the label and a DateFormat instance to format the date value...
public class PlaySchoolClock {
public static void main(String[] args) {
new PlaySchoolClock();
}
public PlaySchoolClock() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ClockPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ClockPane extends JPanel {
private JLabel clock;
public ClockPane() {
setLayout(new BorderLayout());
clock = new JLabel();
clock.setHorizontalAlignment(JLabel.CENTER);
clock.setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 48f));
tickTock();
add(clock);
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tickTock();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(0);
timer.start();
}
public void tickTock() {
clock.setText(DateFormat.getDateTimeInstance().format(new Date()));
}
}
}
This example uses a time interval of half a second. The main reason for this is I don't go to the trouble of trying to calculate how far we are away from the next second when we set up the initial delay. This ensures that we are always up-to-date
The next question is to ask "why?" This kind of setup is relatively expensive, with the timer firing every half second (to catch any edge cases) and updating the screen, when most OS's actually have a date/time already on the screen...IMHO
I created a JStatusBar from many nested JPanels. I was surprised at how many JPanels it took to create a status bar.
JPanels. JPanels everywhere.
Here's the test GUI.
And here's the JStatusBar class. The status bar has a leftmost status update area. On the right, you can add as many status areas as you want, with a separator bar. The only limit is the width of the status bar.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class JStatusBar extends JPanel {
private static final long serialVersionUID = 1L;
protected JPanel leftPanel;
protected JPanel rightPanel;
public JStatusBar() {
createPartControl();
}
protected void createPartControl() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(getWidth(), 23));
leftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 3));
leftPanel.setOpaque(false);
add(leftPanel, BorderLayout.WEST);
rightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 5, 3));
rightPanel.setOpaque(false);
add(rightPanel, BorderLayout.EAST);
}
public void setLeftComponent(JComponent component) {
leftPanel.add(component);
}
public void addRightComponent(JComponent component) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 0));
panel.add(new SeparatorPanel(Color.GRAY, Color.WHITE));
panel.add(component);
rightPanel.add(panel);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int y = 0;
g.setColor(new Color(156, 154, 140));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(196, 194, 183));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(218, 215, 201));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(233, 231, 217));
g.drawLine(0, y, getWidth(), y);
y = getHeight() - 3;
g.setColor(new Color(233, 232, 218));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(233, 231, 216));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(221, 221, 220));
g.drawLine(0, y, getWidth(), y);
}
}
The separator bar is yet another JPanel.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class SeparatorPanel extends JPanel {
private static final long serialVersionUID = 1L;
protected Color leftColor;
protected Color rightColor;
public SeparatorPanel(Color leftColor, Color rightColor) {
this.leftColor = leftColor;
this.rightColor = rightColor;
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(leftColor);
g.drawLine(0, 0, 0, getHeight());
g.setColor(rightColor);
g.drawLine(1, 0, 1, getHeight());
}
}
And finally, the simulator class that shows you how to use the JStatusBar.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class StatusBarSimulator implements Runnable {
protected TimerThread timerThread;
#Override
public void run() {
JFrame frame = new JFrame();
frame.setBounds(100, 200, 400, 200);
frame.setTitle("Status Bar Simulator");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
JStatusBar statusBar = new JStatusBar();
JLabel leftLabel = new JLabel("Your application is running.");
statusBar.setLeftComponent(leftLabel);
final JLabel dateLabel = new JLabel();
dateLabel.setHorizontalAlignment(JLabel.CENTER);
statusBar.addRightComponent(dateLabel);
final JLabel timeLabel = new JLabel();
timeLabel.setHorizontalAlignment(JLabel.CENTER);
statusBar.addRightComponent(timeLabel);
contentPane.add(statusBar, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent event) {
exitProcedure();
}
});
timerThread = new TimerThread(dateLabel, timeLabel);
timerThread.start();
frame.setVisible(true);
}
public void exitProcedure() {
timerThread.setRunning(false);
System.exit(0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new StatusBarSimulator());
}
public class TimerThread extends Thread {
protected boolean isRunning;
protected JLabel dateLabel;
protected JLabel timeLabel;
protected SimpleDateFormat dateFormat =
new SimpleDateFormat("EEE, d MMM yyyy");
protected SimpleDateFormat timeFormat =
new SimpleDateFormat("h:mm a");
public TimerThread(JLabel dateLabel, JLabel timeLabel) {
this.dateLabel = dateLabel;
this.timeLabel = timeLabel;
this.isRunning = true;
}
#Override
public void run() {
while (isRunning) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Calendar currentCalendar = Calendar.getInstance();
Date currentTime = currentCalendar.getTime();
dateLabel.setText(dateFormat.format(currentTime));
timeLabel.setText(timeFormat.format(currentTime));
}
});
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
}
}
}
public void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
}
}
Add a label component at the appropriate place in your JFrame's component hirerarchy (maybe a JToolBar?).
Then create a timer that fires once per second, and add an ActionListener to it that updates the text of the label with the current time.
See the accepted answer at Using SwingWorker and Timer to display time on a label?
Create a SimpleDateFormat object that will help you format the current date. Add a JLabel to your JFrame. In a separate thread, create a loop that keeps reading the current date, format it to a String and pass it to the JLabel in the EDT. Make the separate thread sleep for one second or less before updating the label again.