I have a code which is done coded but I realized its hard to see in the code so what I want do is to add four classes which one will be for Viewer, UserInput, Player and Controller.
The viewer is to see the game information (Which is the JPanel most of all)
UserInput is to let the user choose options with buttons.
Player is where the computer information will be (Functions for the CPU)
Controller is where all the mathematics will be, New game (Restart when pressing New game Button), Make points and so on.
So I made a class where it should start all the classes with by run that class
SSPPlayer player = new SSPPlayer();
SSPViewer viewer = new SSPViewer();
SSPController controller = new SSPController();
SSPUserInput userInput = new SSPUserInput();
JFrame frame1 = new JFrame( "SSPViewer" );
frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame1.add( viewer );
frame1.pack();
frame1.setVisible( true );
JFrame frame2 = new JFrame( "SSPUserInput" );
frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame2.add( userInput );
frame2.pack(); frame2.setVisible( true );
}
}
However, The problem is now that I have made so far two classes which should be in each window for Viewer and UserInput but I could only get viewer to work.
Viewer class
public class SSPViewer extends JFrame{
private JPanel resultatPanel;
private JLabel infoLabel, resultatLabel;
private JTextField UserResult, CompResult;
SSPViewer() {
super("SSPViewer");
setSize(600, 400);
UI();
}
public void UI() {
Container container = getContentPane();
resultatPanel = new JPanel(new GridLayout(2,2));
resultatPanel.setBackground(Color.WHITE);
UserResult = new JTextField(" Dina vinster: ");
resultatPanel.add(användarResultat);
CompResult= new JTextField(" Datorns vinster: ");
resultatPanel.add(datorResultat);
infoLabel = new JLabel("Börja spela genom att ", JLabel.RIGHT);
resultatPanel.add(infoLabel);
resultatLabel = new JLabel("använda knapparna längst ner!", JLabel.LEFT);
resultatPanel.add(resultatLabel);
container.add("Center",resultatPanel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
UserInPut Class
public class SSPUserInput extends JFrame implements ActionListener {
final int ROCK = 0, Sciss = 1, Paper= 2;
private JButton Rock;
private JButton Scoss;
private JButton Paper;
private JButton newgame, exit;
private JPanel UserPanel, UserPanel1;
SSPUserInput() {
super("SSPUserInput");
setSize(800 , 600);
UI1();
}
public void UI1() {
Container container = getContentPane();
UserPanel= new JPanel();
UserPanel.setLayout(new GridLayout(0,4));
UserPanel.add(new JLabel("Du väljer här:", JLabel.CENTER));
Rock = new JButton("Rock");
Sciss = new JButton("Sciss");
PAper = new JButton("Paper");
Rock.addActionListener(this);
Sciss.addActionListener(this);
Paper.addActionListener(this);
UserPanel.add(rock);
UserPanel.add(Sciss);
UserPanel.add(Paper);
container.add("South", userpanel);
UserPanel1= new JPanel();
newgame= new JButton("New Game");
exit= new JButton("Exit");
exit.addActionListener(this);
UserPanel1.add(exit);
newgame.addActionListener(this);
UserPanel1.add(newgame);
container.add("North", UserPanel1);
}
public void actionPerformed(ActionEvent e) {
int val = 0;
if(e.getSource() == exit) {
System.exit(0);
}
else if(e.getSource() == newgame) {
}
else if (e.getSource() == Rock) {
val = Rock;
}
else if (e.getSource() == Sciss) {
val = Sciss;
}
else {
val = Paper;
}
}
}
So I was wondering now why it doesn't work. It seems like I have done it right but...
It would be easier too me and you if anyone is available teamviewer or skype.
EDIT: If there is something you don't understand in the code. Just comment!
ERRORS IM GETTING IS FOLLWING:
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Unknown Source)
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Redovisning3.Test.main(Test.java:15)
SLOVED THIS PROBLEM. To solve this problem which I had before was to just let row 15 and 22 be as a comment for a while until you have done your all classes.
I have done and wrote how to solved the problem I had before (Incase someone is having same trouble as me in the future). However there is another problem which now contain a if-else statements.
So I have a class which allows you to pick SCiss, paper and rock. Which of these has they own number.
Rock = 0, Sciss = 1, Paper = 2.
I have following using this in one of the class because it is needed to know what button you are pressing.
public void actionPerformed(ActionEvent e) {
int val = 0 ;
if(e.getSource() == exit) {
System.exit(0);
}
else if(e.getSource() == Newgame) {
//Nothing here yet.
}
else if (e.getSource() == Rock) {
choice = Rock;
}
else if (e.getSource() == Sciss) {
choice = Sciss;
}
else {
choice = Paper;
}
Sum(choice );
and what I trying to do is when you are pressing one of these three buttons it should save the Number in sum(choice) and then go to another class to make other functions, by that I mean this:
public void berakna(int val){
Userchoice = choice ;
Compchoice = (int)(Math.random() * 3);
resultatLabel.setHorizontalAlignment(0);
infoLabel.setHorizontalAlignment(0);
infoLabel.setText("Result round" + ++round +":");
if (Userchoice == Compchoice )
resultatLabel.setText("Tie!!");
else if (Userchoice == Rock && Compchoice == Sciss||
Userchoice == Sciss && Compchoice == Paper ||
Userchoice == Paper && Compchoice == Rock ) {
resultLabel.setText("You win! One more time?");
UserResult.setText(" You won: " + ++UserWin + "pcs");
}
else {
result.setText(" You lose, Try one more time!");
CompResult.setText(" Comp won: " + ++CompWin+ "st");
}
}
}
I was thinking using return, so I tried but it didn't got me any forward. So ideas would be greatful. There is also no errors.
Related
I am making a GUI Console with Java and Swing. It calls on the scanner to input text, then puts that text into a variable to give to the JFrame. The bolded code is the code in question.
The code works, but when you type in "change text", after putting in the required input, it does not add the JLabel to the JFrame.
Please Help! Thanks!
//prepare all imports
Random rand = new Random();
Scanner input = new Scanner(System.in);
JFrame myframe = new JFrame();
myframe.setSize(300, 300);
myframe.setTitle("Blank Window");
myframe.setResizable(false);
myframe.setLocation(300,300);
//*******************************************
boolean done = false;
boolean winopen = false;
System.out.println("Type commands here. Type 'help' for list of commands.");
while (done == false) {
System.out.print("Console > > > ");
String coninput = input.nextLine();
if (coninput.equals("window open")) {
System.out.println("Opening Window...");
System.out.println("Done!");
winopen = true;
myframe.setVisible(true);
}
if (coninput.equals("window close")) {
System.out.println("Closing Window...");
winopen = false;
myframe.setVisible(false);
System.out.println("Done!");
}
if (coninput.equals("exit")) {
System.out.println("Exiting...");
myframe.dispose();
done = true;
System.out.println("Done!");
}
if (coninput.equals("help")) {
System.out.println("Commands: ");
System.out.println("window open: opens a window");
System.out.println("window close: closes the open window");
System.out.println("exit: shuts down the program");
System.out.println("help: lists commands");
//System.out.println("");
//System.out.println("");
//System.out.println("");
}
**if (coninput.equals("change text") && winopen == true) {
System.out.print("What do you want the text to say > > > ");
JLabel text1 = new JLabel(input.nextLine());
System.out.println("Adding...");
myframe.add(text1);
}**
if (coninput.equals("change text") && winopen == false) {
System.out.print("You have to have a window open.");
}
}
}
}
First of, you need to structure your code in a better way. Secondly, it is better to use a swing container where the text (JLabel) will be added. Below Box is used, which is a container that uses BoxLayout as its layout manager, allowing multiple components (JLabels in your case) to be laid out either vertically (Y_AXIS) or horizontally (X_AXIS). You can then use JScrollPane to provide a scrollable view of the Box component, and add that JScrollPane instance to your frame. Every time you add a new text, you add it to the Box instance, and then you call repaint(); and revalidate(); on your frame for the text to be shown. If you need only the last text to be shown on the window (and not every text you have added), then uncomment box.removeAll(); as a quick fix. Otherwise, do not use the Box with the JScrollPane, but simply add the label to your frame e.g., myframe.getContentPane().add(lbl, BorderLayout.CENTER);. Again, remember to call myframe.getContentPane().removeAll(); before adding a new JLabel, as well as repaint(); and revalidate(); afterwards. Working example below:
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
public class App {
Scanner input;
JFrame myframe;
Box box;
JScrollPane scrollPane;
public App() {
input = new Scanner(System.in);
box = new Box(BoxLayout.Y_AXIS);
scrollPane = new JScrollPane(box);
myframe = new JFrame();
myframe.getContentPane().add(scrollPane, BorderLayout.CENTER);
myframe.setSize(300, 300);
myframe.setTitle("Blank Window");
myframe.setResizable(false);
myframe.setLocation(300, 300);
}
public void go() {
boolean done = false;
boolean winopen = false;
System.out.println("Type commands here. Type 'help' for list of commands.");
while (done == false) {
System.out.print("Console > > > ");
String coninput = input.nextLine();
if (coninput.equals("window open")) {
System.out.println("Opening Window...");
System.out.println("Done!");
winopen = true;
myframe.setVisible(true);
}
if (coninput.equals("window close")) {
System.out.println("Closing Window...");
winopen = false;
myframe.setVisible(false);
System.out.println("Done!");
}
if (coninput.equals("exit")) {
System.out.println("Exiting...");
myframe.dispose();
done = true;
System.out.println("Done!");
}
if (coninput.equals("help")) {
System.out.println("Commands: ");
System.out.println("window open: opens a window");
System.out.println("window close: closes the open window");
System.out.println("exit: shuts down the program");
System.out.println("help: lists commands");
}
if (coninput.equals("change text") && winopen == true) {
System.out.print("What do you want the text to say > > > ");
JLabel lbl = new JLabel(input.nextLine());
System.out.println("Adding...");
// box.removeAll();
box.add(lbl);
myframe.repaint();
myframe.revalidate();
Rectangle bounds = lbl.getBounds();
scrollPane.getViewport().scrollRectToVisible(bounds);// scroll to the new text
}
if (coninput.equals("change text") && winopen == false) {
System.out.print("You have to have a window open.");
}
}
}
public static void main(String[] args) {
new App().go();
}
}
I've developed a working chess engine with minimax and alpha-beta, however I want to test my algorithm by playing itself, computer vs computer. I have tried everything to no avail. Just wondering how I would go about this?
public class Main {
static JTextArea textField;
public static void main(String[] args) {
while ( 'K' != ABChess.board[ABChess.kingLocationUU/8][ABChess.kingLocationUU%8]) {ABChess.kingLocationUU++;}
while ( 'k' != ABChess.board[ABChess.kingLocationLL/8][ABChess.kingLocationLL%8]) {ABChess.kingLocationLL++;}
Asset.init("/images/ChessPiecess.png");
ABChess.updateKingLocations();
//print();
JPanel depthPanel = depthPanel();
JPanel optionPanel = optionPanel();
JPanel logPanel = logPanel();
JPanel menuPanel = new JPanel();
menuPanel.setPreferredSize(new Dimension(140, 100));
menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));
menuPanel.add(depthPanel);
menuPanel.add(optionPanel);
menuPanel.add(logPanel);
GUInterface gui = new GUInterface();
JPanel panel = new JPanel(new BorderLayout());
panel.add(gui);
panel.add(menuPanel, BorderLayout.EAST);
JFrame frame = new JFrame(ABChess.title);
frame.setSize(ABChess.width, ABChess.height);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
System.out.println(ABChess.possibleMoves());
ABChess.playerChoice = JOptionPane.showOptionDialog(null, "Who wants to make the first move?", "Who moves first?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, ABChess.options, ABChess.options[0]);
if (ABChess.playerChoice == 0){
ABChess.flipBoard();
long startTime=System.currentTimeMillis();
Move autoMove = AlphaBeta.alphaBeta(ABChess.gameDepth, 1000000, -1000000, new Move(), 0);
long endTime=System.currentTimeMillis();
ABChess.makeMove(autoMove);
ABChess.flipBoard();
System.out.println("COMPUTER'S MOVE TOOK "+((endTime-startTime)/1000.0)+" SECONDS");
ABChess.printBoard();
frame.repaint();
displayMessage("Took "+((endTime-startTime)/1000.0)+" seconds");
}
}
This is the initial call to the algorithm when the file is ran.
public void mousePressed(MouseEvent event) {
if ( event.getX() < 8*sizeOfSquare && event.getY() < 8*sizeOfSquare) {
mouseX = event.getX();
mouseY = event.getY();
repaint();
}
}
public void mouseReleased(MouseEvent event) {
if (event.getX() < 8*sizeOfSquare && event.getY() < 8*sizeOfSquare) {
newMouseX = event.getX();
newMouseY = event.getY();
if (event.getButton() == MouseEvent.BUTTON1) {
// Regular move
Move legalMovesMove = new Move(mouseY/sizeOfSquare, mouseX/sizeOfSquare, newMouseY/sizeOfSquare, newMouseX/sizeOfSquare, Test6.board[newMouseY/sizeOfSquare][newMouseX/sizeOfSquare]);
java.util.List<Move> legalMoves = ABChess.possibleMoves();
for(Move m : legalMoves) {
if (m.equals(legalMovesMove)) {
ABChess.makeMove(legalMovesMove);
ABChess.flipBoard();
long startTime=System.currentTimeMillis();
Move autoMove = AlphaBeta.alphaBeta(ABChess.gameDepth, 1000000, -1000000, new Move(), 0);
long endTime=System.currentTimeMillis();
ABChess.makeMove(autoMove);
ABChess.flipBoard();
System.out.println("COMPUTER'S MOVE TOOK "+((endTime-startTime)/1000.0)+" SECONDS");
ABChess.printBoard();
repaint();
}
}
checkMate = ABChess.kingSafe();
if(checkMate == false){
int yes = JOptionPane.showOptionDialog(null, "Do you want to make the first move?", "Who moves first?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.YES_OPTION);
if (yes == JOptionPane.YES_OPTION){
ABChess.resetGame();
repaint();
} else if (yes == JOptionPane.NO_OPTION){
System.exit(0);
}
}
legalMoves = ABChess.possibleMoves();
if (legalMoves.size() == 0) {
ABChess.playAgain = JOptionPane.showOptionDialog(null, "Stalemate! Wanna play again?", "Draw!", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, ABChess.choice, ABChess.choice[1]);
if (ABChess.playAgain == 0) {
System.out.println("Yes I will");
ABChess.resetGame();
repaint();
} else {
System.exit(0);
}
}
}
}
}
This is where the algorithm is called every time the mouse is released. Not sure how to code to where it plays itself with the white pieces instead of me.
I would normally seperate the Player from the Game, and the Game would request the interaction from the Player object. The Player object would either be a Human (so the needed input is delegated to some UI) or an AI so it would be delegated to some implementation which decides which move is best.
I would recommend using an object for the ABChess Game instead of static methods.
So with a bit of refactoring and seperating the UI from the logic as well, it could look like this:
interface Player {
Move decide(List<Move> legalMoves);
}
class ChessGame {
ABChess game;
Player player1;
Player player2;
UIInterface ui;
ChessGame(Player player1, Player player2, UIInterface ui) {
this.player1 = player1;
this.player2 = player2;
this.ui = ui;
game = ...
}
public void simulate() {
// ... initial ui ...
boolean player1Turn = true;
do {
Move move = null;
if (player1Turn) {
move = player1.decide(game.possibleMoves());
} else {
move = player2.decide(game.possibleMoves());
}
game.makeMove(move);
// ... update ui ...
player1Turn = !player1Turn;
// check if somebody has won ...
} while (game.isRunning());
// ... update ui with the game result ...
}
}
Once that is done simulating games becomes easy. You just need to initiate the ChessGame with the proper players and call the simulate method. At that point you could also decide to skip the UI presentation completly (so the learning will be much faster).
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 :)
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)) {
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...