Hello I have created a application with several buttons in it. but when I press a button I get the NullPointerException. The strange thing here is that nothing is empty ( null )
here a code example
public class MuseumPanel extends JPanel implements ActionListener {
private JTextField kaartnummer;
private JTextField uur, minuut;
private JButton aankomst, vertrek, overzicht, sluiting;
private int hour;
private int minute;
private final int REFRESH = 1000;
MuseumRegistratie museum;
public MuseumPanel(MuseumRegistratie museum) {
// zorg ervoor dat de huidige tijd wordt opgehaald.
javax.swing.Timer timer = new javax.swing.Timer(REFRESH, this);
timer.start();
kaartnummer = new JTextField(15);
uur = new JTextField(2);
minuut = new JTextField(2);
aankomst = new JButton("Komt binnen");
aankomst.addActionListener(this);
vertrek = new JButton("Vertrekt");
vertrek.addActionListener(this);
overzicht = new JButton("aantal aanwezig");
overzicht.addActionListener(this);
sluiting = new JButton("sluiting");
sluiting.addActionListener(this);
add(new JLabel("Kaartnummer"));
add(kaartnummer);
add(new JLabel("tijdstip van aankomst of vertrek "));
add(uur);
add(new JLabel(" uur en "));
add(minuut);
add(new JLabel(" minuten"));
add(aankomst);
add(vertrek);
add(overzicht);
add(sluiting);
}
#Override
public void actionPerformed(ActionEvent e) {
Calendar now = Calendar.getInstance();
hour = now.get(Calendar.HOUR_OF_DAY);
minute = now.get(Calendar.MINUTE);
uur.setText("" + hour);
minuut.setText("" + minute);
// aankomst
if(e.getSource() == aankomst) {
try {
museum.checkIn(kaartnummer.getText(), hour, minute);
} catch (NullPointerException ex) {
System.out.println("cardnumber: " + kaartnummer.getText() + " hour " + hour + " minute " + minute);
}
}
// vertrek
if(e.getSource() == vertrek) {
museum.checkOut(kaartnummer.getText(), hour, minute);
}
// overzicht
if(e.getSource() == overzicht) {
museum.getAantalAanwezig();
}
// sluiting
if(e.getSource() == sluiting) {
museum.sluitRegistratie();
}
}
}
When pressing this button for example I get the exception with every variable correctly.. Does anyone know how this appears and how to solve it?
Without further information I would assume that the museum object is null which would trigger the nullpointerexception when you try to call museum.checkIn.
Looking at the Code museum is definitely null. in the constructor you should include:
this.museum = museum;
Assuming the museum object you pass in is NOT null then everything else should work.
You don't seem to be assigning a value to museum in your constructor, yet you dereference it in a lot of places. You'd want to do this:
this.museum = museum;
somewhere in your constructor. Alternatively, rename the variable so you don't accidentally do museum = museum, which would have no effect.
Related
I am currently having another problem, this time with JSpinners. I want to add dynamically JSpinners on the screen by right click, via the add button. After I add them, I want them to be inserted in an array of JSpinners and then the data from the JSpinners to be stored into a Date ArrayList. So far I am facing this problem:
If I add a new JSpinner the Date Array does not get automatically the Date from the second JSpinner or third or so on. It only gets the data from the first JSpinner.
I am really lost here. Appreciate any help here. Thanks and best regards
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.text.SimpleDateFormat;
public class TestingGround
{
Toolkit toolkit;
JFrame frame;
JPopupMenu menu;
Calendar calendar1, calendar2;
Date startDate, saveThisDate;
String stringStoredInitialRequestDate;
ArrayList <Date> dateArray; // array to store the dates from the request date
JSpinner spinner;
ArrayList <JSpinner> spinnerArray;
SpinnerModel model1;
int countAddClicks;
int val1;
public TestingGround()
{
frame = new JFrame("Testing ground area");
centerToScreen();
menu = new JPopupMenu();
JMenuItem addRow = new JMenuItem("Add ComboBox");
JMenuItem removeRow = new JMenuItem("Remove ComboBox");
JPanel panel = new JPanel();
JPanel mainGridPanel = new JPanel();
mainGridPanel.setLayout(new GridLayout(0,2));
mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(mainGridPanel);
// -------------------------------------------
dateArray = new <Date> ArrayList(); // array used to store the initial request dates
spinnerArray = new <JSpinner> ArrayList();
JButton saveDataButton = new JButton("save state");
countAddClicks =0;
val1 = -1;
panel.add(saveDataButton);
// ACTION LISTENERS
addRow.addActionListener(new ActionListener(){ // Right click to add JComboBoxes to the screen
public void actionPerformed(ActionEvent event) {
System.out.println("Starting click is: " + countAddClicks);
// JSPINNER 1
calendar1 = Calendar.getInstance();
Date now = calendar1.getTime();
calendar1.add(Calendar.YEAR, -10);
Date startDate = calendar1.getTime();
calendar1.add(Calendar.YEAR, 20);
Date endDate = calendar1.getTime();
model1 = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);
spinner = new JSpinner(model1); // creating Visual Spinner
String format = "dd MMM yy"; // formatting Visual Spinner 1
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, format);
spinner.setEditor(editor); // applying the formatting to the visual spinner
spinnerArray.add(countAddClicks,spinner); // adds the spinner to the array of spinners
/*
model1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
changedDate = ((SpinnerDateModel) e.getSource()).getDate();
}
});
*/
saveThisDate = now;
dateArray.add(countAddClicks, saveThisDate); // add to the DATE array the new date (in the correct slot, going side by side with the other array);
countAddClicks++;
System.out.println("After click is: " + countAddClicks);
mainGridPanel.add(spinner); // add the JTextField to the JPanel
mainGridPanel.repaint();
mainGridPanel.revalidate();
}
});
removeRow.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent event) {
countAddClicks--;
if (countAddClicks <0) {
countAddClicks = 0;
}
if (spinnerArray.size() > 0 & dateArray.size() >0 ) {
spinner = spinnerArray.remove(spinnerArray.size()-1);
mainGridPanel.remove(spinner);
}
System.out.println("After removal click is: " + countAddClicks);
mainGridPanel.revalidate();
mainGridPanel.repaint();
}
});
saveDataButton.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i=0; i< spinnerArray.size(); i++) {
JSpinner tempSpinner = spinnerArray.get(i); // creating a temporary spinner
calendar2 = Calendar.getInstance(); // creating a temporary calendar
Date now2 = calendar2.getTime();
calendar1.add(Calendar.YEAR, -50);
Date startDate2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, 50);
Date endDate2 = calendar2.getTime();
SpinnerModel model2 = new SpinnerDateModel(now2, startDate2, endDate2, Calendar.YEAR);
tempSpinner.setModel(model2); // setting up a temporary spinnerModel and adding it to this instance of JSpinner
model2.addChangeListener(new ChangeListener() { // adding a listener to this model2
public void stateChanged(ChangeEvent e) {
saveThisDate = ((SpinnerDateModel) e.getSource()).getDate(); // checking for user input
System.out.println(saveThisDate); // for testing purpose it is showing that it detects the change
}
});
dateArray.add(saveThisDate); // add to the DATE array the new date (in the correct slot, going side by side with the other array);
}
// Only for checking purpose if the arrays are the correct sizes
System.out.println();
System.out.println("The size of the JSpinner Array is: " + spinnerArray.size() ); // showing correct
System.out.println("The content of the Date Array is: " + dateArray ); // checking the Date array. This is where data is not added, it is not working!
System.out.println("The size of the Date Array is: " + dateArray.size()); // showing correct
System.out.println();
}
});
// Cand dau click din butonul cel mai din dreapta (3) se deschide menium popup
frame.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event) {
if (event.getButton() == event.BUTTON3) {
menu.show(event.getComponent(), event.getX(),event.getY());
}
}
});
menu.add(addRow);
menu.add(removeRow);
frame.add(panel);
frame.setVisible(true);
}
public void centerToScreen()
{
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("A Popup Menu");
toolkit = frame.getToolkit();
Dimension size = toolkit.getScreenSize();
frame.setLocation((size.width-frame.getWidth())/2, (size.height-frame.getHeight())/2);
}
public static void main(String[]args){
new TestingGround();
}
}
The source of the nulls in one of the ArrayLists: You're adding null values to the dateArray ArrayList
Date changedDate; // null
addRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// .....
dateArray.add(countAddClicks, changedDate); // changedDate is null
and you never change these values. Yes you assign a new Date instance to the changedDate variable, but the ArrayList is not holding variables, it's holding objects.
Note that here:
saveDataButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i = 0; i < spinnerArray.size(); i++) {
//.....
model2.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
changedDate = ((SpinnerDateModel) e.getSource()).getDate(); // **** (A) ****
System.out.println(changedDate);
}
});
// ...
}
}
});
again you change the Date instance held by the dateArray variable, but again, this has no effect on the nulls held by the ArrayList.
I suggest that you get rid of the dateArray ArrayList and instead extract the data from the JSpinners when needed (in a listener).
#Hovercraft Full Of Eels I have solved this problem!! I am so proud, now everything works. So it adds dynamically JSpinners and stores the dates in individual Array Slots. I will paste the code if anyone will search for something similar so they can use it as a reference. Thanks again
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.text.SimpleDateFormat;
public class TestingGround {
Toolkit toolkit;
JFrame frame;
JPopupMenu menu;
Calendar calendar1, calendar2;
Date startDate, saveThisDate;
ArrayList<Date> dateArray; // array to store the dates from the request date
JSpinner spinner;
ArrayList<JSpinner> spinnerArray;
SpinnerModel model1;
JPanel mainGridPanel;
int countAddClicks;
public TestingGround() {
frame = new JFrame("Testing ground area");
centerToScreen();
menu = new JPopupMenu();
JMenuItem addRow = new JMenuItem("Add ComboBox");
JMenuItem removeRow = new JMenuItem("Remove ComboBox");
JPanel panel = new JPanel();
mainGridPanel = new JPanel();
mainGridPanel.setLayout(new GridLayout(0, 2));
mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(mainGridPanel);
// -------------------------------------------
dateArray = new <Date>ArrayList(); // array used to store the initial
// request dates
spinnerArray = new <JSpinner>ArrayList();
JButton saveDataButton = new JButton("save state");
countAddClicks = 0;
panel.add(saveDataButton);
// ACTION LISTENERS
addRow.addActionListener(new ActionListener() { // Right click to add
// JComboBoxes to the
// screen
public void actionPerformed(ActionEvent event) {
System.out.println("Starting click is: " + countAddClicks);
// JSPINNER 1
calendar1 = Calendar.getInstance();
Date now = calendar1.getTime();
calendar1.add(Calendar.YEAR, -10);
Date startDate = calendar1.getTime();
calendar1.add(Calendar.YEAR, 20);
Date endDate = calendar1.getTime();
model1 = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);
spinner = new JSpinner(model1); // creating Visual Spinner
String format = "dd MMM yy"; // formatting Visual Spinner 1
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, format);
spinner.setEditor(editor); // applying the formatting to the
// visual spinner
spinnerArray.add(countAddClicks, spinner); // adds the spinner
// to the array of
// spinners
saveThisDate = now;
dateArray.add(countAddClicks, saveThisDate); // add to the DATE
// array the new
// date (in the
// correct slot,
// going side by
// side with the
// other array);
countAddClicks++;
System.out.println("After click is: " + countAddClicks);
mainGridPanel.add(spinner); // add the JTextField to the JPanel
mainGridPanel.repaint();
mainGridPanel.revalidate();
}
});
removeRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
countAddClicks--;
if (countAddClicks < 0) {
countAddClicks = 0;
}
if (spinnerArray.size() > 0 & dateArray.size() > 0) {
spinner = spinnerArray.remove(spinnerArray.size() - 1);
dateArray.remove(dateArray.size() - 1);
mainGridPanel.remove(spinner);
}
System.out.println("After removal click is: " + countAddClicks);
mainGridPanel.revalidate();
mainGridPanel.repaint();
}
});
saveDataButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i = 0; i < spinnerArray.size(); i++) {
JSpinner tempSpinner = new JSpinner(); // creating a
// temporary spinner
calendar2 = Calendar.getInstance(); // creating a temporary
// calendar
Date now2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, -50);
Date startDate2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, 50);
Date endDate2 = calendar2.getTime();
SpinnerModel model2 = new SpinnerDateModel(now2, startDate2, endDate2, Calendar.YEAR);
tempSpinner.setModel(model2); // setting up a temporary
// spinnerModel and adding
// it to this instance of
// JSpinner
model2.addChangeListener(new ChangeListener() { // adding a
// listener
// to this
// model2
public void stateChanged(ChangeEvent e) {
saveThisDate = ((SpinnerDateModel) e.getSource()).getDate(); // checking
// for
// user
// input
System.out.println(saveThisDate); // for testing
// purpose it is
// showing that
// it detects
// the change
}
});
saveThisDate = (Date) spinnerArray.get(i).getValue();
System.out.println("Content of the Spinner Array is: " + spinnerArray.get(i).getValue());
dateArray.add(saveThisDate); // add to the DATE array the
// new date (in the correct
// slot, going side by side
// with the other array);
}
// Only for checking purpose if the arrays are the correct sizes
System.out.println();
System.out.println("The size of the JSpinner Array is: " + spinnerArray.size()); // showing
// correct
System.out.println("The content of the Date Array is: " + dateArray); // checking
// the
// Date
// array.
// This
// is
// where
// data
// is
// not
// added,
// it
// is
// not
// working!
System.out.println("The size of the Date Array is: " + dateArray.size()); // showing
// correct
System.out.println();
}
});
// Cand dau click din butonul cel mai din dreapta (3) se deschide menium
// popup
frame.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event) {
if (event.getButton() == event.BUTTON3) {
menu.show(event.getComponent(), event.getX(), event.getY());
}
}
});
menu.add(addRow);
menu.add(removeRow);
frame.add(panel);
frame.setVisible(true);
}
public void centerToScreen() {
frame.setSize(700, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("A Popup Menu");
toolkit = frame.getToolkit();
Dimension size = toolkit.getScreenSize();
frame.setLocation((size.width - frame.getWidth()) / 2, (size.height - frame.getHeight()) / 2);
}
public static void main(String[] args) {
new TestingGround();
}
}
I'm doing a programming exercise.
Miles and kilometer converter.(both case)
However, If I input number and press "Enter", nothing happened.
I don't know what part I need to modify... :(
Help me please..
public class Grid1 extends JFrame{
private JLabel label1,label2;
private JTextField textField1,textField2;
private Container container;
private GridLayout grid1;
// set up GUI
public Grid1(){
super( "Miles to Km / Km to Mile" );
grid1 = new GridLayout( 2, 2 );
container = getContentPane();
container.setLayout( grid1 );
label1 = new JLabel("Mile");
container.add(label1);
textField1 = new JTextField("");
container.add( textField1 );
label2 = new JLabel("Kilometer");
container.add(label2);
textField2 = new JTextField( "" );
container.add( textField2 );
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener(handler);
JButton submit = new JButton("Submit");
submit.addActionListener(handler);
setSize(300, 100);
setVisible(true);
}
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
float miles = 0, km = 0;
String string = "";
if(event.getSource() == textField1){
string = "textField1: " + event.getActionCommand();
km = miles * 1.609344f;
}else if(event.getSource() == textField2){
string = "textField2: " + event.getActionCommand();
miles = km / 1.609344f;
}
}
}
public static void main( String args[]){
Grid1 application = new Grid1();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} // end class GridLayoutDemo
You should remove handler from variable textField1 if you need to update data from button click. And in handler class you shold store data into result field/label.
In your case it looks like:
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
// In both cases you should get value from textField,
// parse it and store computed values in another field
float miles = 0, km = 0;
try {
if(event.getSource() == textField1){
// Value form field stored in String, you should parse Integer from it
miles = Integer.parseInt(textField1.getText());
km = miles * 1.609344f;
textField2.setText(String.format("%f", km));
}else if(event.getSource() == textField2){
// Value form field stored in String, you should parse Integer from it
km = Integer.parseInt(textField2.getText());
miles = km / 1.609344f;
textField1.setText(String.format("%f", km));
}
} catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Wrong value", "Input error");
}
}
}
Since you are working with a single frame and a single button, I would suggest to set the following line:
frame.getRootPane().setDefaultButton(submitButton);
You can set a default button on each frame you control, the button you set in this method, will automatically listen to enter and invoke your actionPerformed.
You can also use a KeyListener and extend the functionality for your button in this case or in future exercises or projects.
Hope it helps.
All the best... and happy coding :)
My first post, so forgive any incorrect etiquette. I'm currently doing my year end project for school and I need a bit of help. I am making a GUI java app in Netbeans. I have two classes. One is a class that controls a timer, the other is a class that is a scoreboard screen. I need to update the scoreboard timerLabel with the time that is being counted down in the timerClass. Its quite messy as there is another timer label in the Timer class which does update. My problem is that I cannot get timerLabel in MatchScreen() to update. Here is my code :
Timer Class
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class TimerClass extends JFrame {
Timer timer;
JLabel promptLabel, timerLabel;
int counter;
JTextField tf;
JButton button;
MatchScreen call = null;
public TimerClass() {
call = new MatchScreen();
setLayout(new GridLayout(4, 4, 7, 7));
promptLabel = new JLabel(""
+ "Enter number of seconds for the timer",
SwingConstants.CENTER);
add(promptLabel);
tf = new JTextField(5);
add(tf);
button = new JButton("Start");
add(button);
timerLabel = new JLabel("waiting...",
SwingConstants.CENTER);
add(timerLabel);
event e = new event();
button.addActionListener(e);
System.out.println("Button pressed");
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Action performed");
int count = (int) (Double.parseDouble(tf.getText()));
timerLabel.setText("Time left: " + count);
call.setTimerLabel(count);
System.out.println("Passed count to tc");
TimeClass tc = new TimeClass(count);
timer = new Timer(1000, tc);
System.out.println("Timer.start");
timer.start();
//throw new UnsupportedOperationException("Not supported yet.");
}
/*public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}*/
}
public class TimeClass implements ActionListener {
int counter;
public TimeClass(int counter) {
this.counter = counter;
}
public void actionPerformed(ActionEvent e) {
counter--;
if (counter >= 1) {
call.setTimerLabel(counter);
} else {
timerLabel.setText("END");
timer.stop();
Toolkit.getDefaultToolkit().beep();
}
}
}
public static void main(String args[]) {
TimerClass gui = new TimerClass();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(250, 150);
gui.setTitle("Time Setup");
gui.setVisible(true);
}
}
And now the ScoreBoard Screen
public class MatchScreen extends javax.swing.JFrame {
int redScore = 0, blueScore = 0, blueCat1 = 0,
blueCat2 = 0, redCat1 = 0, redCat2 = 0, winner = 0;
public MatchScreen() {
initComponents();
}
//Determine Winner of the match
public int getWinner() {
if (redScore > blueScore) {
winner = 1;
} else {
winner = 2;
}
return winner;
}
public void setTimerLabel(int a) {
int time = a;
while (time >= 1) {
timerLabel.setText("" + time);
}
if (time < 1) {
timerLabel.setText("End");
}
}
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {
//Creates an object of the timerClass
TimerClass gui = new TimerClass();
gui.setSize(300, 175);
gui.setTitle("Time Setup");
gui.setVisible(true);
}
}
Some code that I felt is irrelevant was left out from the MatchScreen().
Many thanks
Managed to solve the general problem. I put all the code into one class. Not ideal, but it works :/ Anyway, deadlines are looming.
Sincere thanks.
You have a while loop in the setTimerLabel method, which I don't think you intended to put there. Also, you take the parameter a and assign it to time and then never use a again, why not just rename your parameter to time and bypass that additional variable?
EDIT
Sorry, I forgot to explain what I'm seeing :P If you say call.setTimerLabel(10) then you hit that while loop (while(time >= 1) which is essentially running while(10 >= 1) which is an infinite loop. Your program is never leaving the method setTimerLabel the first time you call it with a value >= 1.
I have an assignment from my university to continue a JAVA card project from the students from last semester, which happens to be sucked. Because we have to carry on with someones work instead ours..
So my first step is to make an window image icon and tray icon for the application`s window.
The thing is, this code below is based on extended FrameView instead of JWindow.
My idea is to wrap the extended FrameView up into a Window.
Can someone help me with that?
Thanks much I would appreciate that.
CODE:
public class DesktopApplication1View extends FrameView implements IProgressDialogObserver
{
//============================================================
// Fields
// ===========================================================
private Connection connection = new Connection();
private ProgressDialogUpdater pbu = ProgressDialogUpdater.getInstance();
private Vector<CourseFromCard> courseListFromCard = new Vector<CourseFromCard>();
private Vector<School> schoolList = new Vector<School>();
private Vector<CourseFromFile> courseList = new Vector<CourseFromFile>();
private int cardReaderRefreshHelper = 0;
private Student student = null;
JLabel jLabelBilkaImage = null;
final String ICON = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_32.png";
final String PIC = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_128.png";
private JLabel getJLabelBilkaImage() {
if (jLabelBilkaImage == null) {
Icon image = new ImageIcon(PIC);
jLabelBilkaImage = new JLabel(image);
jLabelBilkaImage.setName("jLabelBilkaImage");
}
return jLabelBilkaImage;
}
//============================================================
// Constructors
// ===========================================================
public DesktopApplication1View(SingleFrameApplication app)
{
super(app);
pbu.registriere(this);
app.getMainFrame().setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));
initComponents();
refreshConnectionState();
readFilesFromLocalHDD();
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++)
{
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
{
public void propertyChange(java.beans.PropertyChangeEvent evt)
{
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName))
{
if (!busyIconTimer.isRunning())
{
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
}
else if ("done".equals(propertyName))
{
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
}
else if ("message".equals(propertyName))
{
String text = (String) (evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
}
else if ("progress".equals(propertyName))
{
int value = (Integer) (evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}
.........
SingleFrameApplication provides the method getMainFrame(), which returns the JFrame used to display a particular view. The code you listed in your question is one such view. If you need to operate on the frame, it's probably better to do it in code subclassing SingleFrameApplication than the code you posted.
There's a tutorial on using the Swing Application Framework, which might provide more help.
I created a game and in my swing GUI interface I want to put a timer. The way I do this at the moment is have a field with the current time , gotten with System.currentTimeMillis() which gets it's value when the game starts .In the method of my game i put the System.currentTimeMillis()- field; and it tells you the current time passed since the game started.
Nevertheless, how do get this to update itself every second lets say, so the JLabel will have : timePassed: 0s , timePassed: 1s and so on. Have in mind that i don't use threads in my game at any point.
EDIT: thank you all for your kind suggestions. I used a combination of your answers please give me some feedback.
I have the JLabel as a field called time. (else i cant handle it).
time = new JLabel("Time Passed: " + timePassed() + " sec");
panel_4.add(time);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
time.setText("Time Passed: " + timePassed() + " sec");
}
};
Timer timer = new Timer(1000, actionListener);
timer.start();
Have a look at the swing timer class. It allows to setup recurring tasks quite easily.
This is how I would set my JLabel to update with time & date.
Timer SimpleTimer = new Timer(1000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
jLabel1.setText(SimpleDay.format(new Date()));
jLabel2.setText(SimpleDate.format(new Date()));
jLabel3.setText(SimpleTime.format(new Date()));
}
});
SimpleTimer.start();
This is then added to your main class and the jlabel1/2/3 get updated with the timer.
new Thread(new Runnable
{
public void run()
{
long start = System.currentTimeMillis();
while (true)
{
long time = System.currentTimeMillis() - start;
int seconds = time / 1000;
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
label.setText("Time Passed: " + seconds);
}
});
try { Thread.sleep(100); } catch(Exception e) {}
}
}
}).start();
wirite this in Constructor
ActionListener taskPerformer = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
jMenu11.setText(CurrentTime());
}
};
Timer t = new Timer(1000, taskPerformer);
t.start();
And this Write out Constructor
public String CurrentTime(){
Calendar cal = new GregorianCalendar();
int second = cal.get(Calendar.SECOND);
int min = cal.get(Calendar.MINUTE);
int hour = cal.get(Calendar.HOUR);
String s=(checkTime(hour)+":"+checkTime(min)+":"+checkTime(second));
jMenu11.setText(s);
return s;
}
public String checkTime(int t){
String time1;
if (t < 10){
time1 = ("0"+t);
}
else{
time1 = (""+t);
}
return time1;
}