Java Swing Timer Not Clear - java

I have been having some problems with using the Timer function of Java swing. I am fairly new to programming with Java, so any help is greatly appreciated. I have looked over many other Timer questions on this site but none of them have answered my question. I have made a GUI that allows you to play rock paper scissors, where you can choose from clicking three buttons. I want my program to sleep for around 1 second after you click the button, and again after it displays a message. After I realized Thread.sleep() wouldn't work for my GUI, I tried to implement a timer.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import java.io.*;
public class rps {
//ROCK PAPER SCISSORS
static JLabel middle = new JLabel();
static JLabel them = new JLabel();
static JLabel yourWins = new JLabel();
static JLabel theirWins = new JLabel();
static JPanel yourPanel = new JPanel();
static JPanel middlePanel = new JPanel();
static JLabel blank1 = new JLabel();
static JLabel blank2 = new JLabel();
static JButton rock = new JButton("Rock");
static JButton paper = new JButton("Paper");
static JButton scissors = new JButton("Scissors");
static int yw = 0;
static int tw = 0;
static ButtonHandler listener = new ButtonHandler();
public static void main(String[] args) {
//Create the frame
JFrame frame = new JFrame("Rock Paper Scissors");
frame.setSize(500, 500); //Setting the size of the frame
middle.setFont(new Font("Serif", Font.PLAIN, 30));
middle.setHorizontalAlignment(SwingConstants.CENTER);
them.setFont(new Font("Serif", Font.PLAIN, 15));
them.setHorizontalAlignment(SwingConstants.CENTER);
yourWins.setHorizontalAlignment(SwingConstants.CENTER);
theirWins.setHorizontalAlignment(SwingConstants.CENTER);
//Creating panels
JPanel bigPanel = new JPanel();
Border border = BorderFactory.createLineBorder(Color.BLACK, 1);
Border wlb = BorderFactory.createLineBorder(Color.RED, 1);
them.setBorder(border);
yourPanel.setBorder(border);
bigPanel.setBorder(border);
yourWins.setBorder(wlb);
theirWins.setBorder(wlb);
middlePanel.setBorder(border);
//Creating grid layouts
GridLayout yourGrid = new GridLayout(1,3,10,10);
GridLayout theirGrid = new GridLayout(1,1); //One row, one column
GridLayout middleGrid = new GridLayout(5,1);
GridLayout bigGrid = new GridLayout(3,1);//Two rows, one column
//Setting the layouts of each panel to the grid layouts created above
yourPanel.setLayout(yourGrid); //Adding layout to buttons panel
them.setLayout(theirGrid); //Adding layout to label panel
middlePanel.setLayout(middleGrid);
bigPanel.setLayout(bigGrid);
//Adding r/p/s to your grid.
yourPanel.add(rock);
yourPanel.add(paper);
yourPanel.add(scissors);
//Adding w/l rations to middlegrid.
middlePanel.add(theirWins);
middlePanel.add(blank1);
middlePanel.add(middle);
middlePanel.add(blank2);
middlePanel.add(yourWins);
//Attaching the listener to all the buttons
rock.addActionListener(listener);
paper.addActionListener(listener);
scissors.addActionListener(listener);
bigPanel.add(them);
bigPanel.add(middlePanel);
bigPanel.add(yourPanel);
//Shows the score at 0-0.
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
frame.getContentPane().add(bigPanel); //panel to frame
frame.setVisible(true); // Shows frame on screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//Class represents what do when a button is pressed
private static class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
Timer timer = new Timer(1000, this);
String tc = random();
them.setText("They chose: " + tc + "!");
if (e.getSource() == rock) {
whoWins("rock", tc);
} else if (e.getSource() == paper) {
whoWins("paper", tc);
} else if (e.getSource() == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
timer.setRepeats(false);
timer.start();
}
}
public static String random() {
int random = (int) (Math.random() * 3);
if (random == 0) {
return "Rock";
} else if (random == 1) {
return "Paper";
} else if (random == 2) {
return "Scissors";
}
return "";
}
public static void whoWins(String yc, String tc) {
if (yc.equals("rock")) {
if (tc.equals("Rock")) {
middle.setText("It's a tie!");
} else if (tc.equals("Paper")) {
middle.setText("You lose!");
tw++;
} else if (tc.equals("Scissors")) {
middle.setText("You win!");
yw++;
}
} else if (yc.equals("paper")) {
if (tc.equals("Rock")) {
middle.setText("You win!");
yw++;
} else if (tc.equals("Paper")) {
middle.setText("It's a tie!");
} else if (tc.equals("Scissors")) {
middle.setText("You lose!");
tw++;
}
} else if (yc.equals("scissors")) {
if (tc.equals("Rock")) {
middle.setText("You lose!");
tw++;
} else if (tc.equals("Paper")) {
middle.setText("You win!");
yw++;
} else if (tc.equals("Scissors")) {
middle.setText("It's a tie!");
}
}
}
}
What is actually happening is there is no delay from when I press the button to a message displaying, because clearly I am not using the timer correctly. I would like the timer to just run once, and after it runs the code will execute. However, when I click a button the timer will run on repeat although setRepeats is false. Therefore, the message I want to display, instead of being delayed, is displayed instantaneously but then goes on a loop and keeps displaying a message (the message is random) until I shut off the program. If I click the button again, it will double the tempo of the timer it seems, and the messages display twice as fast and so on and so forth.
them.setText("They chose: " + tc + "!");
This is the message that is displayed on repeat, with the variable tc changing every time. The timer seems to just be displaying this message every timer interval (1s).
Any help would be greatly appreciated.
EDIT:
So I added this section :
private static class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
// I'd be disabling the buttons here to prevent
// the user from trying to trigger another
// update...
// This is an instance field which is used by your
// listener
Timer timer = new Timer(1000, listenert);
timer.setRepeats(false);
timer.start();
}
}
private static class timer implements ActionListener {
public void actionPerformed (ActionEvent e) {
String tc = random(); //A method that chooses a random word.
them.setText("They chose: " + tc + "!");
if (e.getSource() == rock) {
whoWins("rock", tc); //whoWins is a method that will display a message.
} else if (e.getSource() == paper) {
whoWins("paper", tc);
} else if (e.getSource() == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
// Start another Timer here that waits 1 second
// and re-enables the other buttons...
}
}
so what I believe happens now is when I click a button, the buttonhandler listener starts the timer which is attached to the timer listener (named listenert) which will run the code in the actionPerformed of the timer class. however the sleep function still is not working
EDIT 2.5:
private static class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
final JButton button = (JButton)e.getSource();
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String tc = random();
them.setText("They chose: " + tc + "!");
if (button == rock) {
whoWins("rock", tc);
} else if (button == paper) {
whoWins("paper", tc);
} else if (button == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
}
});
timer.setRepeats(false);
timer.start();
}
}
that is what I have so far, I just need to add antoher sleep after
them.setText("They chose: " + tc + "!");
where would I put a timer.restart() if any? the timer.start() is at the end of the method which I don't quite understand.

So, the ActionListener you supply to the Timer is notified when the timer "ticks", so you ButtonHandler actionPerformed should look more like...
public void actionPerformed (ActionEvent e) {
// I'd be disabling the buttons here to prevent
// the user from trying to trigger another
// update...
// This is an instance field which is used by your
// listener
choice = e.getSource();
Timer timer = new Timer(1000, listener);
timer.setRepeats(false);
timer.start();
}
And your listener should look more like
public void actionPerformed (ActionEvent e) {
String tc = random(); //A method that chooses a random word.
them.setText("They chose: " + tc + "!");
if (choice == rock) {
whoWins("rock", tc); //whoWins is a method that will display a message.
} else if (choice == paper) {
whoWins("paper", tc);
} else if (choice == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
// Start another Timer here that waits 1 second
// and re-enables the other buttons...
}
For example...
You may consider taking a look at How to use Swing Timers for more details
Updated
Start with a simple example...
public class TestPane extends JPanel {
private JLabel label;
private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public TestPane() {
setLayout(new GridBagLayout());
label = new JLabel();
add(label);
tick();
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tick();
}
});
timer.start();
}
protected void tick() {
label.setText(sdf.format(new Date()));
}
}
This just calls the tick method every half second to update the time on the JLabel...

firstly import the following ;
import java.awt.event.ActionEvent ;
import java.awt.event.ActionListener ;
import javax.swing.Timer ;
then initialize the timer at the end of the form like this ;
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new mainprogramme().setVisible(true);
}
});
}
private Timer timer ;
then after initializing the timer add a public class like following;
public class progress implements ActionListener {
public void actionPerformed(ActionEvent evt){
int n = 0 ;
if (n<100){
n++ ;
System.out.println(n) ;
}else{
timer.stop() ;
}
}
}
after you do this go to the j Frame>right click and select>Events>window>window Opened and type the following ;
private void formWindowOpened(java.awt.event.WindowEvent evt) {
timer = new Timer(100,new progress()) ;
and after you do all this take a button name it as anything and type the following in its void like following ;
timer.start();
AND THAT'S IT CODE IT AND THEN REPLY ME...

Related

Display not Changing [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I am working on this program that calculates the Beats per Minute (BPM) when you click the button. When you click two times, it is supposed to display the current BPM, and display the new one with every click after that. What the problem is, though, is that the display isn't changing. What do I need to do?
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class BPM extends JPanel implements ActionListener {
JLabel label;
public String display;
public int bpm;
public int buttonPressed;
public int time1;
public int time2;
public int time3;
public int counter[];
public void addComponents(Container pane) {
JPanel buttons = new JPanel();
JButton bpmButton = new JButton("Click");
bpmButton.setSize(new Dimension(100, 50));
bpmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed++;
counter = new int[2];
if (buttonPressed == 1) {
counter[0] = (int)(System.currentTimeMillis());
} else if (buttonPressed == 2) {
counter[1] = (int)(System.currentTimeMillis());
calculateTimeBetweenClicks();
setTime();
} else {
counter[0] = counter[1];
counter[1] = (int)(System.currentTimeMillis());
calculateTimeBetweenClicks();
setTime();
}
}
});
display = "0";
label = new JLabel(display, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(100.0f)); // original 45
pane.add(label, BorderLayout.PAGE_START);
pane.add(bpmButton, BorderLayout.CENTER);
}
// Calculates the difference between the two saved clicks
public void calculateTimeBetweenClicks() {
if (buttonPressed == 1) {
time1 = counter[0];
} else {
time1 = counter[0];
time2 = counter[1];
}
time3 = time2 - time1;
}
// Calculates the BPM and changes the display accordingly
public void setTime() {
bpm = 60000 / time3;
display = "" + bpm + "";
label.setText(display);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public static void createAndShowGUI() {
// Creates the window
JFrame frame = new JFrame("BPM Calculator");
frame.setPreferredSize(new Dimension(300, 200)); // original (250, 130)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Adds the components to the content pane
BPM window = new BPM();
window.addComponents(frame.getContentPane());
//Displays the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Turns off bold text
UIManager.put("swing.boldMetal", Boolean.FALSE);
// Allows the components to be used and interacted with
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The problem is in your addComponents method, you are creating a new array on each and every button click (so you end up with a new and empty array). This is throwing off your calculation. Simply move the instantiation of your array to somewhere outside of the ActionListener like this...
public void addComponents(Container pane) {
JPanel buttons = new JPanel();
counter = new int[2]; //Move this line to here...
JButton bpmButton = new JButton("Click");
bpmButton.setSize(new Dimension(100, 50));
bpmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed++;
if (buttonPressed == 1) {
counter[0] = (int)(System.currentTimeMillis());
} else if (buttonPressed == 2) {
counter[1] = (int)(System.currentTimeMillis());
calculateTimeBetweenClicks();
setTime();
} //Removed the else - see edit below :-)
}
});
Additional
Your code as-is seems to get a litle confused after the 2nd click (the first BPM calculation) as it seems to take that 2nd click as the first click of the next set of 2 clicks if you get what I mean. I'm not sure if this is intended behaviour, but if not, I would reset everything in the calculateTimeBetweenClicks method after you've calculated the correct bpm ready for a new set of 2 clicks...
// Calculates the difference between the two saved clicks
public void calculateTimeBetweenClicks() {
if (buttonPressed == 1) {
time1 = counter[0];
} else {
time1 = counter[0];
time2 = counter[1];
//Reset here ready for next 2 clicks...
counter[0]=0;
counter[1]=0;
buttonPressed = 0;
}
time3 = time2 - time1;
}

Countdown timer helppp

I made a puzzle game in java Applet, and I need to add a timer that runs for 5 minutes where the player has to solve the puzzle within this time, if not a dialog box will appear asking to retry, so then I need the timer to start again.
Can someone tell me how can I code this.
public void init (){
String MINUTES = getParameter("minutes");
if (MINUTES != null) remaining = Integer.parseInt(MINUTES) * 600000;
else remaining = 600000; // 10 minutes by default
// Create a JLabel to display remaining time, and set some PROPERTIES.
label = new JLabel();
// label.setHorizontalAlignment(SwingConstants.CENTER );
// label.setOpaque(false); // So label draws the background color
// Now add the label to the applet. Like JFrame and JDialog, JApplet
// has a content pane that you add children to
count.add(label);
Puzframe.add(count,BorderLayout.SOUTH);
// Obtain a NumberFormat object to convert NUMBER of minutes and
// seconds to strings. Set it up to produce a leading 0 if necessary
format = NumberFormat.getNumberInstance();
format.setMinimumIntegerDigits(2); // pad with 0 if necessary
// Specify a MouseListener to handle mouse events in the applet.
// Note that the applet implements this interface itself
// Create a timer to call the actionPerformed() method immediately,
// and then every 1000 milliseconds. Note we don't START the timer yet.
timer = new Timer(1000, this);
timer.setInitialDelay(0); //
timer.start(); }
public void start() { resume(); }
//The browser calls this to stop the applet. It may be restarted later.
//The pause() method is defined below
void resume() {
// Restore the time we're counting down from and restart the timer.
lastUpdate = System.currentTimeMillis();
timer.start(); // Start the timer
}`
//Pause the countdown
void updateDisplay() {
long now = System.currentTimeMillis(); // current time in ms
long elapsed = now - lastUpdate; // ms elapsed since last update
remaining -= elapsed; // adjust remaining time
lastUpdate = now; // remember this update time
// Convert remaining milliseconds to mm:ss format and display
if (remaining < 0) remaining = 0;
int minutes = (int)(remaining/60000);
int seconds = (int)((remaining)/1000);
label.setText(format.format(minutes) + ":" + format.format(seconds));
label.setForeground(new Color(251,251,254));
label.setBackground(new Color(0,0,0));
// If we've completed the countdown beep and display new page
if (remaining == 0) {
// Stop updating now.
timer.stop();
}
count.add(label);
Puzframe.add(label,BorderLayout.SOUTH); }
This what I have so far, but my problem is that it doesn't appear in my game. I'm calling the updateDisplay() from actionPerformed
Use Swing Timer it is made for such a scenario
//javax.swing.Timer
timer = new Timer(4000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(mainFrame,
"End Of Game",
"5 minutes has passed",
JOptionPane.ERROR_MESSAGE);
}
});
I prepared a simple example to demonstrate it
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JPanel controlPanel;
private Timer timer;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
//javax.swing.Timer
timer = new Timer(4000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(mainFrame,
"End Of Game",
"5 minutes has passed",
JOptionPane.ERROR_MESSAGE);
}
});
}
private void showEventDemo(){
JButton okButton = new JButton("Start Game");
okButton.setActionCommand("OK");
okButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
timer.start();
String command = e.getActionCommand();
if( command.equals( "OK" )) {
System.out.println("Timer started");
}
}
}
}

Swing JButton , Java programing

program suppose to run "Guess the number" game
after guessing the number correctly , there's an option to start over
Pressing the "playAgainBtn" make the program stuck.
Another issue is after guessing the "guessText" cant be .selectAll
any insight will be welcomed
Tnx.
public class GuessTheNumberGame extends JFrame
{
private int randomNumber;
private boolean correctGuess;
private JLabel startMsg;
private JLabel enterGuessJLabel;
private JButton playAgainBtn;
private JLabel msgToPlayer;
private JTextField guessText;
private int previousGuess; // previous guessed number hot/cold
private int numOfGuess;
private Container container;
public GuessTheNumberGame()
{
container = getContentPane();
startMsg = new JLabel();
enterGuessJLabel = new JLabel();
guessText = new JTextField(10);
guessText.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
int playerGuess = Integer.parseInt(event.getActionCommand());
if ( playerGuess == randomNumber )
{
msgToPlayer.setText("Great ! u guessed in " + numOfGuess + "Guesses");
correctGuess = true;
}
else
{
wrongGuess(playerGuess);
}
}
}
);
msgToPlayer = new JLabel("");
playAgainBtn = new JButton("Play Again");
ButtonHandler buttonHandler = new ButtonHandler();
playAgainBtn.addActionListener(buttonHandler);
setLayout(new FlowLayout());
add(startMsg);
add(enterGuessJLabel);
add(guessText);
add(msgToPlayer);
add(playAgainBtn);
}
protected class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
startGame();
}
}
public void startGame()
{
previousGuess = 1000;
numOfGuess = 1;
correctGuess = false;
Random rand = new Random();
randomNumber = rand.nextInt(1000) + 1;
startMsg.setText( "I have a number between 1 and 1000. can you Guess my Number?" );
playAgainBtn.setVisible( false );
while ( !correctGuess)
{
enterGuessJLabel.setText( "Please enter your " + numOfGuess + " guess: " );
}
playAgainBtn.setVisible(true);
}
private void wrongGuess(int playerGuess)
{
numOfGuess++;
if ( Math.abs(playerGuess - randomNumber) > previousGuess )
container.setBackground( Color.GREEN);
else
container.setBackground( Color.RED);
previousGuess = Math.abs(playerGuess - randomNumber);
if (playerGuess > randomNumber)
msgToPlayer.setText("Too High");
else
msgToPlayer.setText( "Too Low" );
}
}
When you start the application, startGame() runs on the main thread, which is OK. When you press playAgainBtn, it calls startGame() on the AWT Dispatch Thread, thus tying up this thread, prohibiting the AWT from processing events. Try this to free up the AWT Dispatch Thread:
protected class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent event)
{
new Thread() {
#Override
public final void run() {
startGame();
}
}.start();
}
}
The problem is that your startGame method, called when the button is clicked, has an infinite loop in it.
while ( !correctGuess)
{
enterGuessJLabel.setText( "Please enter your " + numOfGuess + " guess: " );
}
The correctGuess variable will never be changed so your program will just execute the setText command endlessly.
The way Swing (and all GUI frameworks) work is that you must always respond to an event such as a button click and then return control.

JButtons, ActionListener, and JOptionPane

I'm trying to give a popup JOptionPane MessageDialog if the required items are ticked or not ticked but I don't get anything. Basically I'm checking which button is pressed using the action listener and then check which user was selected in the previous window. If the user is not allowed then it should show a popup message dialog telling them so, otherwise it should check whether the required items are ticked in the JCheckBox and if the correct items are ticked it should show a message dialog "welcoming" them into the room.
The classes were made quite a while ago and I know that I should be better in naming them as well as my variables. This is quite an old project that I never finished so there are many flaws in the way I programmed, so please don't call me out on that, although tips are welcome.
Even though I say this is an old project I am still not great at Java and I'm still learning so my code is not perfect, obviously.
Some of the names and messages are in Afrikaans so if there's anything you don't understand just ask and I'll change it for you.
I couldn't quite figure out how to use the site's code highlighting, I hope I did it right, sorry.
Main class:
import javax.swing.JFrame;
public class main {
public static void main(String args[]){
window1 w1Ob = new window1();
w1Ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w1Ob.setSize(250,250);
w1Ob.setVisible(true);
w1Ob.setLocationRelativeTo(null);
w1Ob.setResizable(true);
}
}
First window class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
//has to extend JFrame to use content from JFrame, cannot import to here but can to main class, not sure how it
//works
public class window1 extends JFrame{
//creating window2 object to run window2 if inserted password is correct
window2 wO2 = new window2();
//adds needed variables
//adds jlist which is the used list
private JList list;
//names used in the jlist, jlist uses string array
private static String[] usernames = {"Jannie", "Heloise", "Juan", "Chane"};
//font used to make text larger
Font font = new Font("Sans-Serif", Font.BOLD, 24);
//attempt at making a password array that stores all the passwords as strings then is used in an if statement
//to check if correct
private static int[] passwords = {1, 2, 3, 4};
//creating variable to know which user is logged in
public int loggedUser;
//constructor to create the window
public window1(){
//title
super("Project");
//the layout used, FlowLayout, most basic layout as temporary solution until learning new one
setLayout(new FlowLayout());
//tells the jlist to use the usernames string array to display in the list, meaning it will display
//Jannie on list 1, Heloise on line 2, etc.
list = new JList(usernames);
//tells the jlist how many lines to display, if array contains > 4 strings and is told to display only
//4 it will give a scroll bar
list.setVisibleRowCount(4);
//makes sure only 1 item in the list is selected
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//sets the jlist lists' font to preset font in variable at the top of the class
list.setFont(font);
//adds the jlist to the screen
add(new JScrollPane(list));
//adds the listener to wait for the user to select an item in the list, thus "ListSelection"
list.addListSelectionListener(
//anonymous class insides parameters for adding the listener to list
new ListSelectionListener(){
//obligatory overwrite, parameters of "ListSelectionEvent event" obligatory, not sure what
//it does...
public void valueChanged(ListSelectionEvent event){
//creating the OptionPane for the password
String pass = JOptionPane.showInputDialog(null, "Enter Password");
//converts pass to string under variable name i
int i = Integer.parseInt(pass);
//checks if entered value is equal to the value in the array, example, Jannie = list[0]
//because it's the first value in array list and 1 = pass[0] since it's the first value
//in array passwords, thus if 1 is entered it will be correct because it's the
//corresponding value in the arrays
if(i == passwords[list.getSelectedIndex()]){
int selectedValue = list.getSelectedIndex();
if(selectedValue == 0){
loggedUser = 1;
}
else if(selectedValue == 1){
loggedUser = 2;
}
else if(selectedValue == 2){
loggedUser = 3;
}
else if(selectedValue == 3){
loggedUser = 4;
}
wO2.setDefaultCloseOperation(EXIT_ON_CLOSE);
wO2.setSize(500, 500);
wO2.setVisible(true);
wO2.setLocationRelativeTo(null);
wO2.setResizable(true);
}
}
}
);
}
}
Second window class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class window2 extends JFrame{
//adding JButton variables for each button on the screen
private JButton garage;
private JButton kombuis;
private JButton badkamer;
private JButton mancave;
//adding JCheckBox variables for each required item
public JCheckBox sleutel;
public JCheckBox helmet;
public JCheckBox voorskoot;
public JCheckBox beker;
public JCheckBox handdoek;
public JCheckBox seep;
public JCheckBox musiek;
//adding String variable to tell the user what he requires to enter the area he wants
private String youNeed;
private JButton button;
public window2(){
//title
super("Access");
//3 rows (int), 4 columns (int), 15 px horizontal gap (int), 15 px vertical gap (int)
setLayout(new GridLayout(3, 4, 2, 5));
//gives parameters for garage, puts text "Garage" on the button
garage = new JButton("Garage");
//adds garage JButton to the screen
add(garage);
//gives parameters for kombuis, puts text "Kombuis" on the button
kombuis = new JButton("Kombuis");
//adds kombuis JButton to the screen
add(kombuis);
//gives parameters for badkamer, puts text "Badkamer" on the button
badkamer = new JButton("Badkamer");
//adds badkamer JButton to the screen
add(badkamer);
//gives parameters for mancave, puts text "Mancave" on the button
mancave = new JButton("Mancave");
//adds mancave JButton to the screen
add(mancave);
sleutel = new JCheckBox("Sleutel");
add(sleutel);
helmet = new JCheckBox("Helmet");
add(helmet);
voorskoot = new JCheckBox("Voorskoot");
add(voorskoot);
beker = new JCheckBox("Beker");
add(beker);
handdoek = new JCheckBox("Handdoek");
add(handdoek);
seep = new JCheckBox("Seep");
add(seep);
musiek = new JCheckBox("Musiek");
add(musiek);
HandlerClass handler = new HandlerClass();
//adds action listeners for following button to wait for user to select one
garage.addActionListener(handler);
kombuis.addActionListener(handler);
badkamer.addActionListener(handler);
mancave.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
//create window1 object to use loggedUser variable from window1
window1 wo1 = new window1();
//create variable using window1 object to use loggedUser variable in window2 class
int loggedU = wo1.loggedUser;
if(event.getActionCommand().equals(garage)){
if(loggedU == 1){
if(sleutel.isSelected() && helmet.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the garage, Jannie");
}
else{
if(sleutel.isSelected()){
youNeed = "Helmet";
}
else if(helmet.isSelected()){
youNeed = "Sleutel";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 3){
if(sleutel.isSelected() && helmet.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the garage, Juan");
}
else{
if(sleutel.isSelected()){
youNeed = "Helmet";
}
else if(helmet.isSelected()){
youNeed = "Sleutel";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else{
JOptionPane.showMessageDialog(null, "You're not allowed in here");
}
}
if(event.getActionCommand().equals(badkamer)){
if(loggedU == 1){
if(handdoek.isSelected() && seep.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the bathroom, Jannie");
}
else{
if(handdoek.isSelected()){
youNeed = "Seep";
}
else if(seep.isSelected()){
youNeed = "Handdoek";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 2){
if(handdoek.isSelected() && seep.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the bathroom, Heloise");
}
else{
if(handdoek.isSelected()){
youNeed = "Seep";
}
else if(seep.isSelected()){
youNeed = "Handdoek";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 3){
if(handdoek.isSelected() && seep.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the bathroom, Juan");
}
else{
if(handdoek.isSelected()){
youNeed = "Seep";
}
else if(seep.isSelected()){
youNeed = "Handdoek";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 4){
if(handdoek.isSelected() && seep.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the bathroom, Chane");
}
else{
if(handdoek.isSelected()){
youNeed = "Seep";
}
else if(seep.isSelected()){
youNeed = "Handdoek";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
}
if(event.getActionCommand().equals(kombuis)){
if(loggedU == 2){
if(voorskoot.isSelected() && beker.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the kombuis, Heloise");
}
else{
if(voorskoot.isSelected()){
youNeed = "beker";
}
else if(beker.isSelected()){
youNeed = "voorskoot";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 4){
if(voorskoot.isSelected() && beker.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the kombuis, Chane");
}
else{
if(voorskoot.isSelected()){
youNeed = "beker";
}
else if(beker.isSelected()){
youNeed = "voorskoot";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else{
JOptionPane.showMessageDialog(null, "You're not allowed in here");
}
}
if(event.getActionCommand().equals(mancave)){
if(loggedU == 1){
if(musiek.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the mancave, Jannie");
}
else{
youNeed = "musiek";
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else{
JOptionPane.showMessageDialog(null, "You're not allowed in here");
}
}
}
}
}
Thanks in advance for any attempts at solving/solutions.
Regarding this code:
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
window1 wo1 = new window1(); // ***** problem is here *****
int loggedU = wo1.loggedUser;
if (event.getActionCommand().equals(garage)) {
which for debugging purposes, I've changed to:
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
window1 wo1 = new window1(); // ***** problem is here *****
int loggedU = wo1.loggedUser;
System.out.println("action command: " + event.getActionCommand()); //!!
System.out.println("loggedU: " + loggedU);
if (event.getActionCommand().equals(garage)) {
You'll see that loggedU always returns 0.
Your problem is a common newbie mistake -- you are creating a new window1 object, w02, and are assuming that its state is the same as a previously created window1 object, and that's not how Java works. To get the state of the original window1 object, you will need to test it, and not a new and different instance.
e.g.,
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.Window;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class MyTest {
private static void createAndShowGui() {
MainGuiPanel mainGuiPanel = new MainGuiPanel();
final JFrame frame = new JFrame("MyTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainGuiPanel);
frame.pack();
frame.setLocationRelativeTo(null);
// frame.setVisible(true);
DialogPanel dialogPanel = new DialogPanel();
JDialog dialog = new JDialog(frame, "Select User", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
// show modal dialog
dialog.setVisible(true);
// here dialog is no longer visible
// extract datat from dialog's dialogPanel
String selectedUser = dialogPanel.getSelectedName();
// put into the main GUI
mainGuiPanel.setSelectedUser(selectedUser);
// now show the main GUI's JFrame
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MainGuiPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JButton doItButton = new JButton(new DoItAction("Do It!", KeyEvent.VK_D));
private String selectedUser;
public MainGuiPanel() {
add(doItButton);
}
public void setSelectedUser(String selectedUser) {
this.selectedUser = selectedUser;
}
private class DoItAction extends AbstractAction {
public DoItAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Selected User: " + selectedUser);
}
}
}
class DialogPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final String[] USER_NAMES = { "Jannie", "Heloise", "Juan", "Chane" };
private JList<String> userList = new JList<>(USER_NAMES);
private String selectedName;
public DialogPanel() {
userList.addListSelectionListener(new UserListListener());
add(new JScrollPane(userList));
}
public String getSelectedName() {
return selectedName;
}
private class UserListListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
selectedName = userList.getSelectedValue();
if (selectedName != null) {
Window win = SwingUtilities.getWindowAncestor(DialogPanel.this);
win.dispose();
}
}
}
}
}
Edit
Your code is not taking String capitalization into account!
Change:
if (event.getActionCommand().equals(garage)) {
to:
if (event.getActionCommand().equalsIgnoreCase(garage)) {

Changing JLabels between classes

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.

Categories