I've created a simple JApplet with three components, but the final added component always overlays the other two so that they are not visible. I believe this is because they are being added to the same area in the default BorderLayout (correct me if I'm wrong!). However, I keep getting an error message when I try to change the LayoutManager. I commented on the line causing the problem below.
import javax.swing.*;
import java.awt.event.*;
public class Vote extends JApplet {
int candidate1 = 50; // this int holds the votes for candidate 1
int candidate2 = 50; // this int holds the votes for candidate 2
public void init() {
JButton vote1 = new JButton("Vote for candidate 1");
JButton vote2 = new JButton("Vote for candidate 2");
JButton results = new JButton("See Results");
vote1.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
++candidate1;
String message = "You voted for candidate 1. \n\nThe current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
vote2.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
++candidate2;
String message = "You voted for candidate 2. \n\nThe current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
results.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String message = "The current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
getContentPane().setLayout(new GridLayout(3, 1)); // this line is the one I can't get to work
getContentPane().add(vote1);
getContentPane().add(vote2);
getContentPane().add(results);
}
}
Related
Got this program for a candy machine GUI finished, but I can't figure out where to put in the InputMismatchException code. I've tried putting it in under the input for entering the payments, but I can't find a way to put it in the right area, I don't know what I'm doing wrong.
Main Candy Machine Class
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import java.util.InputMismatchException;
public class candyMachine extends JFrame {
//window size setup
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
//setup for the store items and register
private CashRegister cashRegister = new CashRegister();
private Dispenser candy = new Dispenser(100, 50);
private Dispenser chips = new Dispenser(100, 65);
private Dispenser gum = new Dispenser(75, 45);
private Dispenser cookies = new Dispenser(100, 85);
//heading and button setups
private JLabel headingMainL;
private JLabel selectionL;
private JButton exitB, candyB, chipsB, gumB, cookiesB;
private ButtonHandler pbHandler;
//the main machine constructor
public candyMachine() {
setTitle("Candy Machine"); // window title
setSize(WIDTH, HEIGHT); // window size
Container pane = getContentPane(); //container get
pane.setLayout(new GridLayout(7,1)); //pane layout setup
pbHandler = new ButtonHandler(); //instantiate listener object
//Store sign setup
headingMainL = new JLabel("WELCOME TO SHELLY'S CANDY SHOP", SwingConstants.CENTER);
//instructions setup
selectionL = new JLabel("To Make a Selection, " + "Click on the Product Button", SwingConstants.CENTER);
//adding the labels to the panes
pane.add(headingMainL);
pane.add(selectionL);
//candy button setup
candyB = new JButton("Candy");
//registering the listener for the candy button
candyB.addActionListener(pbHandler);
//chip button setup
chipsB = new JButton("Chips");
//Registering listener for chips button
chipsB.addActionListener(pbHandler);
//gum button setup
gumB = new JButton("Gum");
//registering the listener for the gum button
gumB.addActionListener(pbHandler);
//cookie button setup
cookiesB = new JButton("Cookies");
//registering the listener for the cookie button
cookiesB.addActionListener(pbHandler);
//exit button setup
exitB = new JButton("Exit");
//registering the listener for the exit button
exitB.addActionListener(pbHandler);
pane.add(candyB); //adds the candy button to the pane
pane.add(chipsB); //adds the chips button to the pane
pane.add(gumB); //adds the gum button to the pane
pane.add(cookiesB); //adds the cookies button to the pane
pane.add(exitB); //adds the exit button to the pane
setVisible(true); //show the window and its contents
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//class to handle button events
private class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getActionCommand().equals("Exit"))
System.exit(0);
else if (e.getActionCommand().equals("Candy"))
sellProduct(candy, "Candy");
else if (e.getActionCommand().equals("Chips"))
sellProduct(chips, "Chips");
else if (e.getActionCommand().equals("Gum"))
sellProduct(gum, "Gum");
else if (e.getActionCommand().equals("Cookies"))
sellProduct(cookies, "Cookies");
}
}
//Method to sell machine items
private void sellProduct(Dispenser product, String productName) {
//int variables for the amount of money entered, prices, and money needed
int coinsInserted = 0;
int price;
int coinsRequired;
String str;
// if statement for buying the products
if (product.getCount() > 0) {
price = product.getProductCost();
coinsRequired = price - coinsInserted;
while (coinsRequired > 0) {
str = JOptionPane.showInputDialog("To buy " + productName + " please insert " + coinsRequired + " cents");
coinsInserted = coinsInserted
+ Integer.parseInt(str);
coinsRequired = price - coinsInserted;
}
cashRegister.acceptAmount(coinsInserted);
product.makeSale();
JOptionPane.showMessageDialog(null, "Please pick up " + "your " + productName + " and enjoy",
"Thank you, Come again!", JOptionPane.PLAIN_MESSAGE);
} else //if that item is sold out
JOptionPane.showMessageDialog(null, "Sorry " + productName + " is sold out\n" + "Please make another selection",
"Thank you, Come again!", JOptionPane.PLAIN_MESSAGE);
}
public static void main(String[] args) {
candyMachine candyShop = new candyMachine();
}
}
Cash Register Class
public class CashRegister {
private int regiCash; //int variable for storing cash in the "register"
public CashRegister()
{ // default amount of cash on hand is 500
regiCash = 500;
}
//Method that receives the cash entered by the user and updates the register
public void acceptAmount(int amountIn) {
regiCash = regiCash + amountIn;
}
//Constructer for setting the amount of money in the register to a specific amount (500)
public CashRegister(int cashIn)
{
if (cashIn >= 0)
regiCash = cashIn;
else
regiCash = 500;
}
//Method to show the current amount of money in the cash register
public int currentBalance()
{
return regiCash;
}
}
Dispenser Class
public class Dispenser {
private int itemNumber; //int variable for storing the number of items in the dispenser
private int price; //int variable for storing item prices
//item constructor
public Dispenser(int i, int j)
{ //default number of items is 5 and default price is 50
itemNumber = 5;
price = 50;
}
public int getCount()
{
return itemNumber;
}
public void makeSale()
{
itemNumber--;
}
public int getProductCost()
{
return price;
}
}
Button Handler Class
package lab9Final;
public class ButtonHandler {
//Handles the buttons
}
I am trying to write this
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
onto my scores.txt file.
This is what I want the output in the scores.txt file to look like:
Write save here and then skip line
Write save here and then skip line (repeat again and again)
My Problem
Every time I press the save score button, it runs this code
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
which is good. But whenever I press the save score button again, the original line gets overwritten which I don't want to happen.
What I've Tried
I have tried \r\n and BufferedWriter and it doesn't match what I want the outcome to be.
My Code
HackerGUI.java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class HackerGUI extends JFrame
{
//jframe components
private JPanel rootPanel;
private JButton hack;
private JLabel time;
private JButton reset;
private JLabel description;
private JLabel title;
private JLabel gif;
private JTextField textField1;
private JButton saveScoresButton;
private JButton settingsButton;
private JButton placeholder;
//timer stuff
private final Timer timer; //create timer
private final long duration = 10000; //duration of time
private long startTime = -1; //start of the time
private int delay = 300; //delay of when the time starts
//hacker levels
private int count = 0;
public HackerGUI()
{
add(rootPanel); //add intellij windows builder form
setTitle("Hacker UI v8.4"); //set the title of the frame
try {
File myObj = new File("scores.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("Scores file already exists.");
}
} catch (IOException a) {
System.out.println("An error occurred.");
a.printStackTrace();
}
try {
File myObj = new File("settings.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("Settings file already exists.");
}
} catch (IOException a) {
System.out.println("An error occurred.");
a.printStackTrace();
}
timer = new Timer(20, new ActionListener() { //timer module
#Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) { //if time reaches 0, stop time so it doesn't go to negative int
startTime = System.currentTimeMillis(); //use system time
}
long now = System.currentTimeMillis(); //use system time
long clockTime = now - startTime;
if (clockTime >= duration) { //whenever clock reaches 0, run command under:
clockTime = duration;
timer.stop(); //stop the timer from going to the negatives
hack.setEnabled(false); //disables hack button as timer went to 0
reset.setEnabled(true); //enable reset button to play again
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss.SSS"); //format of time shown
time.setText(df.format(duration - clockTime)); //set time component to destination
}
});
timer.setInitialDelay(delay); //set the delay
hack.addActionListener(new ActionListener() { //play action listener, triggers when button is pressed
#Override
public void actionPerformed(ActionEvent e) {
count++; //count in positives and add
hack.setText("Hacker Level: " + count); //change int and label
if (!timer.isRunning()) { //when button pressed, start timer
startTime = -1; //int to when start
timer.start(); //start
}
}
});
reset.addActionListener(new ActionListener() { //reset action listener, triggers when button is pressed
#Override
public void actionPerformed(ActionEvent e) {
hack.setEnabled(true); //enable hack button to start a new game
reset.setEnabled(false); //disable reset button as it has been used
//old command line save score
String name = textField1.getText(); //get name string
System.out.println(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds."); //print other info
System.out.println(""); //print spacer
//old command line save score
count = count + -count; //count in positive integers
hack.setText("Hacker Level: " + -count); //reset level score
time.setText("00:10.000"); //reset time label
}
});
saveScoresButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
FileWriter myWriter = new FileWriter("scores.txt");
String name = textField1.getText(); //get name string
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.");
myWriter.close();
System.out.println("Successfully wrote to the score file.");
} catch (IOException b) {
System.out.println("An error occurred.");
b.printStackTrace();
}
}
});
settingsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO: put stuff here
}
});
//please don't delete! as this shows credits and help info
JOptionPane.showMessageDialog(rootPanel,
"Hacker UI v8.4 is created by _._#3324, thank you for downloading! What is Hacker UI v8.4? It is a clicker game! To know more, read the documentation! https://github.com/udu3324/Hacker-UI-v8.4");
System.out.println("Hacker UI v8.4: has successfully loaded.");
System.out.println("=====================================================");
System.out.println("");
}
private void createUIComponents() {
// TODO: place custom component creation code here
}
public void setData(HackerGUI data) {
}
public void getData(HackerGUI data) {
}
public boolean isModified(HackerGUI data) {
return false;
}
}
Main.java
import javax.swing.*;
import java.net.URL;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, javax.swing.UnsupportedLookAndFeelException
{
System.out.println("Hello, World!"); //Hello, World!
}
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println("Hacker UI v8.4: is loading..."); //print status of loading
URL iconURL = getClass().getResource("/images/Hacker UI.png"); //load icon resource
ImageIcon icon = new ImageIcon(iconURL); //set icon to icon
HackerGUI hackergui = new HackerGUI(); //make a hacker gui
hackergui.setIconImage(icon.getImage()); //get icon resource and set as
hackergui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //terminate when asked on close
hackergui.setResizable(false); //no resizing
hackergui.pack(); //wrap it into a pack and set jframe size depending on jframe component size
hackergui.setLocationRelativeTo(null); //set location to middle of screen
hackergui.setVisible(true); //set the frame visible
}
});
}
}
If you do not want to overwrite the text each time you need to append. You can do this by initializing your FileEriter as follows:
FileWriter myWriter = new FileWriter("scores.txt", true);
This constructor takes 2 parameters, one is the file you are writing to and the second is a boolean expression that determines will you append to the file or overwrite it.
If you want to know more about it you can check it out here:
https://www.geeksforgeeks.org/java-program-to-append-a-string-in-an-existing-file/
Please help me with this. I have been stuck for hours!
I have addActionListener to my JTextField, and inside the actionPerformed(), I am trying to modify one class String variable choice. BUT IT IS NOT CHANGING! The value of choice after the actionPerformed() method is always null. I remove the actionListener after it one action has been performed, so I can do some selection later.
The code is below:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package assignment;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.*;
public class GUI_V2 extends JFrame {
//Typing Area;
private JTextField txtEnter = new JTextField();
//Chat area;
private JTextArea txtChat = new JTextArea();
//Scroll
private final JScrollPane scroll = new JScrollPane(txtChat);
private String choice;
public GUI_V2(){
//Frame Attributes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(2000,2000);
this.setVisible(true);
this.setResizable(false);
this.setLayout(null);
this.setTitle("Menu ChatBot");
//textEnter Attributes
txtEnter.setLocation(20,1825);
txtEnter.setSize(1950,100);
txtEnter.setFont(new Font("Arial",Font.PLAIN,45));
//txtChat Attributes
txtChat.setLocation(22,5);
txtChat.setSize(1950,1800);
txtChat.setFont(new Font("Arial",Font.BOLD,45));
txtChat.setBackground(java.awt.Color.getHSBColor(0.4957f,0.0902f,1.0f));
txtChat.setLineWrap(true);
txtChat.setWrapStyleWord(true);
txtChat.setEditable(false);
//scroll Attributes
scroll.setLocation(22,5);
scroll.setSize(1950,1800);
//Add Items To Frame
this.add(txtEnter);
this.add(scroll);
final String name = greetings();
txtChat.append(botSays("Hi " + name + "! Please enter the mode of operation:"
+ "\n(1) Add keywords and response"
+ "\n(2) Start chatting"
+ "\n(3) Exit the chatbot\n"));
txtEnter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
//add userInput into the txtChat
choice = txtChat.getText();
txtChat.append(name + ": " + choice + "\n");
//auto scroll down
txtChat.setCaretPosition(txtChat.getDocument().getLength());
//set the txtEnter field to be empty
txtEnter.setText("");
txtEnter.removeActionListener(this);
}
});
System.out.println(choice);
//display main menu and ask for user choice
public static void main(String[] args) {
new GUI_V2();
}
private String greetings(){
long currentHour = getCurrentHour();
String time;
if (currentHour < 12)
time = "morning";
else if (currentHour < 18)
time = "afternoon";
else
time = "evening";
txtChat.append(botSays("Good " + time + ", my name is Nova. Welcome to the HOTPOT restaurant!\n"));
pause(1000);
txtChat.append(botSays("First of all, may I know you name? Please.\n"));
pause(1000);
String name = JOptionPane.showInputDialog(null, "Please enter your name:", "My master", JOptionPane.QUESTION_MESSAGE);
return name;
}
public static String botSays(String s){
return "Nova: " + s;
}
public static long getCurrentHour(){
long totalSec = System.currentTimeMillis()/1000;
long totalMin = totalSec / 60;
long totalHour = totalMin / 60;
return (totalHour + 8) % 24; //+8 because SG is GMT+8
}
public static void pause (int millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
private void displayMenu(String name){
txtChat.append(botSays("Hi " + name + "! Please enter the mode of operation:"
+ "\n(1) Add keywords and response"
+ "\n(2) Start chatting"
+ "\n(3) Exit the chatbot\n"));
txtEnter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
//add userInput into the txtChat
choice = txtChat.getText();
txtChat.append(name + ": " + choice + "\n");
//auto scroll down
txtChat.setCaretPosition(txtChat.getDocument().getLength());
//set the txtEnter field to be empty
txtEnter.setText("");
txtEnter.removeActionListener(this);
}
});
}
}
Your action performed is not working on txtEnter. That is why value of choice is not changing.
I have a Gadget, Mobile, MP3 and GadgetShop class. The Gadget is the super class, the Mobile and MP3 are Subclasses of the Superclass and the GadgetShop is the GUI I made.
I just need my GadgetShop to gather the information to place it in the TextFields I've made when I click the button I've made. I have no idea how to pass the information.
I'm using BlueJ by the way.
This is my Mobile Class:
/**Mobile phone class that:
* allows calling credit to be applied that is more than 0
* shows remaining calling credit
* allows a phone number to be added
* shows duration of phone call
*/
public class Mobile extends Gadget
{
private int credit;
private int duration;
private String number = "";
/**
* Constructor for objects of class Mobile.
*/
public Mobile(double ThePrice, int TheWeight, String TheModel, String TheSize)
{
// initialise instance variables
super(ThePrice, TheWeight, TheModel, TheSize);
}
/**
* Insert the duration of the call.
*/
public void insertDuration(int length)
{
System.out.println("A duration of " + length + " minutes for the phone call has been inserted!");
duration = length;
}
/**
* Insert the phone number.
*/
public void insertNumber(String numberAdder)
{
System.out.println("The phone number " + numberAdder + " has been inserted!");
number = numberAdder;
}
/**
* Insert credit for the call.
* A positive amount will need to be added in order for successfull credit to be applied,
* otherwise an error message is displayed.
*/
public void insertCredit(int calls)
{
if(calls > 0) {
System.out.println("Successfully added " + calls + " pounds of credit!");
credit = credit + calls;
}
else {
System.out.println("You need to insert a positive amount more than " + credit + " pounds.");
}
}
/**
* Make the phone call.
* If the credit is equal to or more than the duration, a message displays the phone number and duration of the call.
* If the credit is 0, a message will be displayed to insert more than 0.
* The number of minutes the call lasted is reduced by the amount that was available.
*/
public void makePhoneCall()
{
if(credit == 0)
System.out.println("Insert more than 0 credit to make a phone call!");
else {
if(credit >= duration) {
System.out.println("The phone number " + number + " has been dialed and is being called for " + duration + " minutes");
credit = credit - duration;
duration = 0;
}
else {
if(credit < duration)
System.out.println("You do not have enough credit to make a phone call! Your credit is " + credit + " pounds");
}
}
}
public void mobilePrint()
/**
* Print the details of the mobile.
**/
{
System.out.println("The price of the mobile is " + price + " pounds");
System.out.println("The weight is " + weight + " grams");
System.out.println("The model is " + model);
System.out.println("The size is " + size);
}
}
This is my GadgetShop:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class GadgetShop implements ActionListener
{
private JTextField model, price, weight, size, credit, memory, phoneNo, duration, download, displayNumber;
private JButton addMobile, addMP3, clear, displayAll;
//These JTextField's are for the labels
private JTextField model2, price2, weight2, size2, credit2, memory2, phoneNo2, duration2, download2, displayNumber2;
private JFrame frame;
private ArrayList<Gadget> gadgetDetails;
public GadgetShop()
{
makeFrame();
}
public void addGadget(Gadget newGadget)
{
ArrayList<Gadget> GadgetList = new ArrayList<Gadget>();
Gadget Object = new Gadget(1.00,20,"model","big");
GadgetList.add(Object);
model.setText("hi");
}
public void makeFrame()
{
frame = new JFrame("Gadget Shop");
Container contentPane = frame.getContentPane();
model = new JTextField(10);
price = new JTextField(10);
weight = new JTextField(10);
size = new JTextField(10);
credit = new JTextField(10);
memory = new JTextField(10);
phoneNo = new JTextField(10);
duration = new JTextField(10);
download = new JTextField(10);
displayNumber = new JTextField(10);
//Display Model text box and model info
model2 = new JTextField("Model:");
contentPane.add(model2);
model2.setOpaque(false);
contentPane.add(model);
price2 = new JTextField("Price:");
contentPane.add(price2);
price2.setOpaque(false);
contentPane.add(price);
weight2 = new JTextField("Weight:");
contentPane.add(weight2);
weight2.setOpaque(false);
contentPane.add(weight);
size2 = new JTextField("Size:");
contentPane.add(size2);
size2.setOpaque(false);
contentPane.add(size);
credit2 = new JTextField("Credit:");
contentPane.add(credit2);
credit2.setOpaque(false);
contentPane.add(credit);
memory2 = new JTextField("Memory:");
contentPane.add(memory2);
memory2.setOpaque(false);
contentPane.add(memory);
phoneNo2 = new JTextField("Phone Number:");
contentPane.add(phoneNo2);
phoneNo2.setOpaque(false);
contentPane.add(phoneNo);
duration2 = new JTextField("Duration:");
contentPane.add(duration2);
duration2.setOpaque(false);
contentPane.add(duration);
download2 = new JTextField("Download:");
contentPane.add(download2);
download2.setOpaque(false);
contentPane.add(download);
displayNumber2 = new JTextField("Display Number:");
contentPane.add(displayNumber2);
displayNumber2.setOpaque(false);
contentPane.add(displayNumber);
addMobile = new JButton("Add Mobile Number");
contentPane.add(addMobile);
addMobile.addActionListener(this);
addMP3 = new JButton("Add MP3 Song");
contentPane.add(addMP3);
addMP3.addActionListener(this);
clear = new JButton("Clear");
contentPane.add(clear);
clear.addActionListener(this);
displayAll = new JButton("Display All");
contentPane.add(displayAll);
displayAll.addActionListener(this);
contentPane.setLayout (new GridLayout(4,4));
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (command.equals("Add Mobile Number")) {
addMobile();
}
}
public void addMobile()
{
model.setText("");
}
public void clearText()
{
model.setText("");
price.setText("");
weight.setText("");
size.setText("");
credit.setText("");
memory.setText("");
phoneNo.setText("");
duration.setText("");
download.setText("");
displayNumber.setText("");
}
}
Where I have the:
public void addMobile()
{
model.setText("");
}
I want to add the details of the Mobile Phone
Similarly how you do it in the addGadget method you could add a Mobile parameter to addMobile
public void addMobile(Mobile mobile)
{
// You should add getter methods for attribute
//in the Mobile class to get meaningful values here instead of toString
model.setText(mobile.toString());
}
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)) {