Java Timers and TextFields - java

I have a panel where I have an uneditable Textfield. I want to be able to add a textField.setText(timer); sort of thing in the panel. I basically just want the JTextArea to display it like this: 0:0:0.
I've tried making Timers, TimerTasks, ActionListeners and the sort. I can't get the hang of this. Maybe it's because where I'm adding the timer? At the moment I tried adding it in a public void guiComponents() throws Exception{...}. This method holds all the properties for the panel, the frame it's in and other components.
Maybe I'm not understating the whole concept of timers. Origanlly I tried using a double-nested for loop to achieve this task, but because this has to go on while the rest of the program is running, I couldn't do that.

Don't use a JTextField for this. Use a JLabel to display text. Something like:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class TimerTime extends JFrame implements ActionListener
{
JLabel timeLabel;
public TimerTime()
{
timeLabel = new JLabel( new Date().toString() );
getContentPane().add(timeLabel, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e)
{
timeLabel.setText( new Date().toString() );
}
public static void main(String[] args)
{
TimerTime frame = new TimerTime();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
int time = 1000;
javax.swing.Timer timer = new javax.swing.Timer(time, frame);
timer.setInitialDelay(1);
timer.start();
}
}

Related

How would I refresh this panel

I want to make a kind of digital clock which you can activate by using enter to kind of refresh the clock display, for that I use this method:
private static void GUI(String time, int action){
JLabel textLabel = new JLabel(time);
JPanel panel = new JPanel();
JFrame enterMessage = new JFrame("Tester");
if (action == 1){
enterMessage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
enterMessage.setSize(190, 80);
enterMessage.setVisible(true);
panel.setBackground(Color.WHITE);
panel.add(textLabel);
enterMessage.add(panel);
}else {
System.out.printf("Refresh");
panel.revalidate();
enterMessage.revalidate();
panel.repaint();
enterMessage.repaint();
}
}
}
This method gets called twice in the program code: one time to make the GUI upon opening the program and everytime an enterpress is detected to refresh it. I searched on internet how to refresh a JPanel and I found that you needed to use revalidate(); and then repaint(); but it does not refresh the time displayed by the panel. How would I refresh it?
ps:the time is passed from the main as a string and everytime an enterpress is detected gets overwritten and passed
Follow Java naming conventions. Variable names should NOT start with an upper case character.
Don't keep adding the label to the panel. Just use the setText(...) method of JLabel to change the text being displayed.
Edit:
An example of a SSCCE that shows you how to use the setText(...) method:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class TimerTime extends JPanel implements ActionListener
{
private JLabel timeLabel;
public TimerTime()
{
timeLabel = new JLabel( new Date().toString() );
add( timeLabel );
Timer timer = new Timer(1000, this);
timer.setInitialDelay(1);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e)
{
//System.out.println(e.getSource());
timeLabel.setText( new Date().toString() );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("TimerTime");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TimerTime() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

I created my GUI in a GUI class' constructor. How would I access its Frames, Panels etc. from another class?

First of all, this is a more specific question than it seems to be. To start off: I am currently doing a small application with a rather small GUI, so I decided to make a GUI class, and initialize my whole GUI in this constructor.
This would look like this:
public class GUI extends JFrame{
public GUI{
//Initialize GUI here, including its Frames, Panels, Buttons etc.
}
}
How can I now access the GUIs frame etc. from an external class? If I would create an object of the GUI class, I would simply duplicate my GUI window. I did not come across any other ideas than making the frame, panel and so on static.
I'm somewhat lost right now. Also I'm pretty sure that I am not thinking the right way into this case, but I need someone to point me to the right direction. If someone could help me out, I would be very thankful.
First of all, using static is the worst solution possible, even if your GUI class is a singleton (buf if it is, at least it will work fine).
Why don't you simply create getters and/or setters ? And finally, it is usually not normal that external classes need to access the components of another graphic class. You should wonder if your design is the most fitted for your needs.
Here's a simple GUI to change the background color of a JPanel with a JButton. Generally, this is how you construct a Swing GUI.
package com.ggl.testing;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ChangeDemo implements Runnable {
private boolean isYellow;
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
#Override
public void run() {
frame = new JFrame("Change Background Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
JPanel namePanel = new JPanel();
JLabel nameLabel = new JLabel(
"Click the button to change the background color");
nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
namePanel.add(nameLabel);
mainPanel.add(namePanel);
final JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.YELLOW);
isYellow = true;
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
buttonPanel.add(changeButton);
mainPanel.add(buttonPanel);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
You don't access the Swing components of the GUI from other classes. You create other classes to hold the values of the GUI.
Generally, you use the model / view / controller pattern to construct a Swing GUI. That way, you can focus on one part of the GUI at a time.
Take a look at my article, Java Swing File Browser, to see how the MVC pattern works with a typical Swing GUI.
You don't need to make it static or to create a new JFrame object every time.
Have a look at this simple code :
class UseJFrame {
public static void main(String...args) {
Scanner sc = new Scanner(System.in);
JFrame frame = new GUI();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
System.out.println("Press E to exit");
String ip;
while(true) {
System.out.println("Show GUI (Y/N/E)? : ");
ip = sc.nextLine();
if(ip.equalsIgnoreCase("y") {
frame.setVisible(true);
} else if(ip.equalsIgnoreCase("n") {
frame.setVisible(false);
} else { // E or any other input
frame.dispose();
}
}
}
}
Note : Don't make GUI visible through constructor or it will show window at the very starting of creation of JFrame object.
If you want to use the same JFrame object at other places too then pool architecture would be better approach.

Java GUI Help (JFrame, JButton, etc)

Ok so im new to programming GUIs in Java and I need some help on how to add buttons and Labels. I went around looking at an example and I figured it this was how it worked to basically add a button:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GUI_Tests extends JFrame{
public static void main(String[] args){
private JButton button;
button = new JButton("pls work");
add(button);
}
}
Well that didnt work at all... Can someone show me how its done and give me some pointers?
You should note that a JFrame has a default BorderLayout which, if not specified, will add a component to a BorderLayout.CENTER position.
When adding components to JFrame, if a different Layout is not specified, then you want to set a component's position, like add(button, BorderLayout.SOUTH);
Also you should use a constructor. Something like this
public class GUI_Tests extends JFrame {
public GUI_Tests(){
JButton button = new JButton("Pls work");
JLabel label = new JLabel("Pls work");
add(button, BorderLayout.CENTER);
add(label, BorderLayout.SOUTH);
}
}
Also you need to remember to set the frame visible.
A simple running program would be something like this
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class GUI_Tests extends JFrame {
public GUI_Tests() {
JButton button = new JButton("Pls work");
JLabel label = new JLabel("Pls work");
add(button, BorderLayout.CENTER);
add(label, BorderLayout.WEST);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new GUI_Tests();
}
});
}
}
The main method may look somewhat crazy to you, but all it is doing is causing the program to run on the Event Dispatch Thread (EDT). I won't go into this too much as you are still a beginner.
What is going on in the run is that all I do is create an instance of me program, which extends JFrame. If I didn't extend JFrame, I would have to explicitly create a JFrame to run the program. All GUI programs need some top-level container to run.
Also you can see in the constructor, that when I added the button and label I set a layout position
add(button, BorderLayout.CENTER);
add(label, BorderLayout.SOUTH);
as I stated earlier, when using a JFrame without specifying a different layout, you should use position with the default `BorderLayout. Other possible positions are
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.CENTER
BorderLayout.NORTH
BorderLayout.SOUTH
Take a look at [Laying Out Components Within a Container]Laying Out Components Within a Container)
Also, noticed I used pack(). What this does is make the frame the perfect with for the preferrsed sizes of the components. It is preferred to pack() rather then setSize() of a frame.
setDefaultCloseOperation(EXIT_ON_CLOSE); makes it so that when x out the frame, the program shuts down.
setLocationRelativeTo(null); set the frame's location in the center of the screen
setVisible(true); makes the frame visible. This should always be called to make the frame visible on start of the program.
Please have a look at the Swing tutorials
You are supposed to add your JButton to a JFrame, but it seems to me that you haven't even created a JFrame yet. You should first create an instance of GUI_Tests, then use the JFrame#add method with your JButton. For example:
public class GUI_Tests extends JFrame {
public GUI_Tests() {
super("My first Swing frame!");
this.setPreferredSize(new Dimension(640, 480));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create your GUI here
this.add(new JButton("Click on me :)"));
this.setVisible(true);
}
}
Actually, I wouldn't be mean to you, but I think you tried to go too fast: in my opinion, you should start by following some tutorial on how to deal with Swing :)
public class GUI_Tests extends JFrame {
private JButton button;
public GUI_Tests() {
setTitle("Title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // so that the application properly closes when you click close
button = new JButton("pls work");
add(button);
pack(); // resize the frame to its contents
setLocationRelativeTo(null); // center the frame on the screen
}
public static void main(String args[]) {
// properly start a swing application
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI_Tests gui = new GUI_Tests();
gui.setVisible(true); // set the frame visible
}
});
}
}
hope this helps you understand it a bit more. i didn't use any layouts in this code as its just a simple example, however, i highly recommend you to read on built-in layouts in swing and how to use them.
Here's one good start
You need to add your button to a JFrame The basic flow should look something like this:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class GUITests extends JFrame{
public GUITests() {
setTitle("Simple example");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button = new JButton("pls work");
add(button);
pack();
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUITests ex = new GUITests();
ex.setVisible(true);
}
});
}
}
The GUITests class extends the JFrame class so you can call all the methods that are visible on the JFrame class. In the main method It's just some boiler plate code that calls your constructor for you so that you can see your basic example.
Check out the tutorials here: http://zetcode.com/tutorials/javaswingtutorial/firstprograms/
type
setVisible( true );
setSize( 500 , 500 );
and I think you'll see something. Also get rid of private in the statement private JButton button But you should really put your code in the constructor of the GUI_Tests:
import javax.swing.*;
public class GUI_Tests extends JFrame {
public GUI_Tests() {
JButton button = new JButton( "Hello World" );
add( button );
setVisible( true );
setSize( 500 , 500 );
}
final public static void main( String[] args ) {
GUI_Tests tests = new GUI_Tests();
}
}
Check out the Java tutorial for more help, possibly here: http://docs.oracle.com/javase/tutorial/uiswing/start/index.html

Closing a JFrame using the keyboard

I am creating a basic screensaver for a small project for college and I am having trouble closing the JFrame after I open it. I have removed the outer panel so as to make it look a proper screensaver but I now have to open the Task Manager to close down the program, I want the window to close when I press a button on the keyboard how can I do that?
Thanks in advance.
-------EDIT--------
I have tried the first two methods given but I can't seem to get them to work properly. Here is my code for the frame so far:
import java.awt.Color;
import javax.swing.JFrame;
public class ScreensaverTest
{
public static void main( String[] args )
{
JFrame frame = new JFrame( "Screen Saver" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setUndecorated(true);
ScreenSaverJPanel screensaverTestJPanel = new ScreenSaverJPanel();
frame.add( screensaverTestJPanel );
frame.setBackground( Color.BLACK );
frame.setVisible( true );
frame.setLocation( 0, 0 );
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
--------EDIT---------
Also I am using the repaint method to move objects around the screen and I want some of them to move at different speed. I am using a random number generator for the positioning so adjusting the numbers isn't really an option, please help.
There are a lot of examples on how to do this.
You need to add an eventListener to the frame that listens for keyboard-inputs and then closes the frame.
Try looking at this: http://www.java2s.com/Code/Java/Swing-JFC/Reacttoframecloseaction.htm
You will have to replace the event with something keyboard-related, but that is the best way to go I would think..
Edit:
To respond to the edit in the post you could do something like this:
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Test {
public Test() {
final JFrame frame = new JFrame("Screen Saver");
frame.validate();
frame.setVisible(true);
KeyAdapter listener = new KeyAdapter() {
#Override public void keyPressed(KeyEvent e) {
frame.dispose();
}
};
frame.addKeyListener(listener);
}
public static void main(String[] args) {
new Test();
}
}
And voila - that should work. It compiles for me on Java 7.
Here is the code if you have only a single JFrame. You should add it when you initialize your components.
addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(java.awt.event.KeyEvent evt)
{
processWindowEvent(new WindowEvent(getWindows()[0], WindowEvent.WINDOW_CLOSING));
}
});

Java Splash screen

I'm trying to make to make some text appear before my applet loads so I've made a simple SSCCE(.org):
import java.awt.*;
import javax.swing.*;
public class test extends JApplet {
public void init() {
this.add(new JLabel("Button 1"));
System.out.println("Hello world...");
try {
Thread.sleep(3000);
}catch(Exception hapa) { hapa.printStackTrace(); }
}
}
If you run it, the Button 1 will appear AFTER the 3 seconds when it's suppose to appear BEFORE that... what am I doing wrong?
I think the init() method has to return before the items are rendered.
JustinKSU covered the technical part of the question.
A better strategy would be to use the image param to show a 'splash' before the applet appears. See Special Attributes of Applets for further details.
I want one for a fixed amount of time... not just the loading.
In that case, put a CardLayout in the applet. Add the 'splash' to the first card, the rest of the GUI to another. At the end of the init() create a non-repeating Swing Timer that will flip to the card with the main GUI.
E.G.
// <applet code='SplashApplet' width='400' height='400'></applet>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SplashApplet extends JApplet {
public void init() {
final CardLayout cardLayout = new CardLayout();
final JPanel gui = new JPanel(cardLayout);
JPanel splash = new JPanel();
splash.setBackground(Color.RED);
gui.add(splash, "splash");
JPanel mainGui = new JPanel();
mainGui.setBackground(Color.GREEN);
gui.add(mainGui, "main");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cardLayout.show(gui, "main");
}
};
Timer timer = new Timer(3000, listener);
// only needs to be done once
timer.setRepeats(false);
setContentPane(gui);
validate();
timer.start();
}
}

Categories

Resources