Related
I created a shop cart login JFrame and I added a "shopkeeperToggle" so that when it's pressed the user logs in to the shopkeeper's JFrame and otherwise to a shopper's jframe. the problem is I don't know how to implement it, I tried to set a boolean "pressed" to false whenever the key is released in the "shopkeeperToggle" key listener, and apparently I'm unable to use the value of pressed inside the sign-in button.
Here's the code for the toggle:
shopkeeperToggle = new JToggleButton("Shopkeeper");
shopkeeperToggle.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
pressed = false;
}
});
and this is what I'm trying to do in the sign in button:
signinButton = new JButton("Sign in ");
signinButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/shoppingCart","root","");
// select the users that have the inputted credentials from the database
String sql = "SELECT * FROM users WHERE userUsername = ? AND userEmail =?AND userPassword = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernamelogin.getText());
ps.setString(2, emaillogin.getText());
ps.setString(3,passwordlogin.getText());
ResultSet rs = ps.executeQuery();
// if query executed and
if (rs.next()) {
// if login succ show window log succ, and go to home shopping page
JOptionPane.showMessageDialog(null,"Login successful! :)");
/////////////////this is where I fail////////////////////
if (pressed) {
OwnerHomePage ownerhome = new OwnerHomePage();
ownerhome.setVisible(true);
setVisible(false);
} else {
UserHomePage home = new UserHomePage();
home.setVisible(true);
setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null,"Wrong Username or Email or Password :(");
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,e1);
}
}
}
This may offer some help in fixing your issue. It is a fully compilable demo. The following changes were made.
Used Actions in lieu of KeyListener. A little more involved to setup but they can be configured to monitor only certain keys.
Used a JButton in lieu of a JToggleButton. No specific reason and can be changed.
Created separate inner classes for the listeners. Tends to reduce clutter and is usually more readable.
Changed the name of the button depending on the mode.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class ActionMapAndButtons {
JFrame frame = new JFrame("Demo");
public static void main(String[] args) {
SwingUtilities
.invokeLater(() -> new ActionMapAndButtons().start());
}
public void start() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyClass cls = new MyClass();
frame.add(cls);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyClass extends JPanel {
JButton button = new JButton("Shopper Sign in");
boolean pause = false;
public MyClass() {
setPreferredSize(new Dimension(300, 300));
button.addActionListener(new ButtonListener());
add(button);
InputMap map = getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
for (int i = 0; i < 256; i++) {
map.put(KeyStroke.getKeyStroke((char)i), "anyKey");
}
getActionMap().put("anyKey", new MyAction());
setFocusable(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj instanceof JButton) {
JButton b = (JButton) obj;
pause = !pause;
if (pause) {
b.setText("Shopkeeper Sign in");
} else {
b.setText("Shopper Sign in");
}
}
}
}
private class MyAction extends AbstractAction {
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if (pause) {
System.out.println("Shopkeeper - " + cmd);
} else {
System.out.println("Shopper - " + cmd);
}
}
}
}
Inner (or nested) classes and action maps are covered in The Java Tutorials
You can define pressed as a static value;
class c {
static boolean pressed = true;
...
}
and you can access anywhere;
c.pressed; //will return true if you don't change
I am trying to make a java simulation of a train moving from station to station. I have the main code working but having trouble with the GUI. I have the basic layout with a start and stop button but as soon as the start button is selected, the main loop runs for the simulation and the GUI doesn't respond. I've been having trouble finding how to work around this. And help wpuld be much appreciated!
Here is the main simulation class:
/**
* Here is the main simulation class that runs the main loop.
* It uses instances of two classes : train and station.
* #author Ollie Jones
*
*/
public class SimEngine
{
/**
* Station object array and train object initialised.
* The line has 16 station so an array of 16 is needed.
*/
Station[] station = new Station[16];
Train train = new Train();
int forwardTimeArray[];
int backwardTimeArray[];
/**
* Constructor for objects of class SimEngine
*/
public SimEngine()
{
/**
* Here that values are initialised.
*/
train = new Train();
forwardTimeArray = new int[]{1,4,2,4,6,3,3,5,3,2,5,5,1,4,2};
backwardTimeArray = new int[]{3,2,4,5,2,2,4,3,4,2,5,2,1,4,5};
// A for loop is used to initialse the station number
for(int i=0; i<station.length; i++){
station[i] = new Station();
station[i].setStationNumber(i+1);
}
/**
* Each station name is initialised separately as
* they all have different names.
*/
station[0].setStationName("Name of 1st station");
station[1].setStationName("Name of 2nd station");
station[2].setStationName("Name of 3rd station");
station[3].setStationName("Name of 4th station");
station[4].setStationName("Name of 5ht station");
station[5].setStationName("Name of 6th station");
station[6].setStationName("Name of 7th station");
station[7].setStationName("Name of 8th station");
station[8].setStationName("Name of 9th station");
station[9].setStationName("Name of 10th station");
station[10].setStationName("Name of 11th station");
station[11].setStationName("Name of 12th station");
station[12].setStationName("Name of 13th station");
station[13].setStationName("Name of 14th station");
station[14].setStationName("Name of 15th station");
station[15].setStationName("Name of 16th station");
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
/**
* This method stats the train simulation.
*
*/
public void start()
{
int x = 0;
System.out.println("Station Number:1"); //Print the first staion number.
while(x == 0){
int stationNumber = 0;
int time = 0;
Boolean forwards;
stationNumber = train.getStationNumber();
forwards = train.getDirection();
if (forwards == true){
time = forwardTimeArray[stationNumber-1];
sleep(time);
stationNumber = stationNumber + 1;
System.out.println("Station Nubmer:" + stationNumber);
train.setStationNumber(stationNumber);
}
else{
time = backwardTimeArray[stationNumber-2];
sleep(time);
stationNumber = stationNumber - 1;
System.out.println("Station Number:" + stationNumber);
train.setStationNumber(stationNumber);
}
if (stationNumber == 1){
forwards = true;
}
else if (stationNumber == 16){
forwards = false;
//train.setStationNumber(stationNumber-1);
}
train.setDirection(forwards);
}
}
public static void sleep(int time)
{
try{
time = time * 100;
Thread.sleep(time);
}
catch(Exception e) {}
}
public void stop()
{
System.exit(0);
}
}
Here is the sim class where the simulation is started.
public class Sim
{
private GUI gui;
private SimEngine engine;
/**
* Constructor for objects of class sim
*
*/
public Sim()
{
engine = new SimEngine();
gui = new GUI(engine);
}
/**
* Opens window if it has been closed.
*/
public void show()
{
gui.setVisable(true);
}
}
Here is the GUI, where the main issue is (i think).
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class GUI extends JFrame
{
// instance variables - replace the example below with your own
private JFrame frame;
private JTextField display;
private final SimEngine sim;
private JLabel infoLabel;
/**
* Constructor for objects of class GUI
*/
public GUI(SimEngine engine)
{
// initialise instance variables
makeFrame();
frame.setVisible(true);
sim = engine;
}
/**
* Creates GUI frame!
*/
public void makeFrame()
{
frame = new JFrame("Train Simulation");
JPanel contentPane = (JPanel)frame.getContentPane();
contentPane.setLayout(new BorderLayout(8,8));
contentPane.setBorder(new EmptyBorder(10,10,10,10));
display = new JTextField();
contentPane.add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(1,2));
addButton(buttonPanel, "Start", () -> sim.start());
addButton(buttonPanel, "Stop", () -> sim.stop());
contentPane.add(buttonPanel, BorderLayout.CENTER);
frame.pack();
}
private void addButton(Container panel, String buttonText, ButtonAction
action)
{
JButton button = new JButton(buttonText);
button.addActionListener(e -> {action.act(); redisplay(); });
panel.add(button);
}
private interface ButtonAction
{
/**
* act on button press.
*/
void act();
}
private void redisplay()
{
}
/**
* Makes frame visable.
*/
public void setVisable(boolean visable){
frame.setVisible(visable);
}
}
You're running your simulation on the event dispatch thread. While your calculations are happening, they are monopolizing the thread that handles UI events, so it can't process anything and the UI freezes.
Use worker threads.
It looks like you have this usecase (from the linked tutorial):
The background task can provide intermediate results by invoking SwingWorker.publish, causing SwingWorker.process to be invoked from the event dispatch thread.
As explained in the comments and in this answer, running long processes on the The Event Dispatch Thread blocks it, so it does not respond to changes.
One alternative is to use a SwingWorker which does the background processing in its doInBackground() method, publishes interim values (publish method) and is capable of updating gui (process method).
The following is a basic implementation of a SwingWorker, based on your code.
It can be copy-pasted into one file (GUI.java) and run.
Note the comments in the code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
public class GUI extends JFrame
{
// instance variables - replace the example below with your own
private JFrame frame;
private JTextField display;
private final SimEngine sim;
private JLabel infoLabel;
/**
* Constructor for objects of class GUI
*/
public GUI(SimEngine engine)
{
// initialize instance variables
makeFrame();
frame.setVisible(true);
sim = engine;
}
/**
* Creates GUI frame!
*/
public void makeFrame()
{
frame = new JFrame("Train Simulation");
JPanel contentPane = (JPanel)frame.getContentPane();
contentPane.setLayout(new BorderLayout(8,8));
contentPane.setBorder(new EmptyBorder(10,10,10,10));
display = new JTextField();
contentPane.add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(1,2));
addButton(buttonPanel, "Start", () -> sim.start());
addButton(buttonPanel, "Stop", () -> sim.stop());
contentPane.add(buttonPanel, BorderLayout.CENTER);
frame.pack();
}
private void addButton(Container panel, String buttonText, ButtonAction action)
{
JButton button = new JButton(buttonText);
button.addActionListener(e -> {action.act(); redisplay(); });
panel.add(button);
}
void updateDisplay(String newValue){
display.setText(newValue);
}
private interface ButtonAction
{
/**
* act on button press.
*/
void act();
}
private void redisplay() { }
/**
* Makes frame visible.
*/
public void setVisable(boolean visable){
frame.setVisible(visable);
}
public static void main(String[] args) {
Sim sim = new Sim();
sim.show();
}
}
//implements Listener so it can listen to SimEngine value changes
class Sim implements Listener
{
private final GUI gui;
private final SimEngine engine;
public Sim()
{
engine = new SimEngine(this);
gui = new GUI(engine);
}
/**
* make gui visible
*/
public void show()
{
gui.setVisable(true);
}
#Override
public void valueChanged(String newValue){
gui.updateDisplay(newValue);
}
}
class SimEngine {
/**
* Station object array and train object initialized.
* The line has 16 station so an array of 16 is needed.
*/
private final Station[] station = new Station[16];
private Train train = new Train();
private final int forwardTimeArray[], backwardTimeArray[];
private final Listener listener;
//accept a listener
public SimEngine(Listener listener)
{
this.listener = listener;
train = new Train();
forwardTimeArray = new int[] {1,4,2,4,6,3,3,5,3,2,5,5,1,4,2,3}; //needs 16 values, had only 16
backwardTimeArray = new int[]{3,2,4,5,2,2,4,3,4,2,5,2,1,4,5,4};
// A for loop is used to initialize the station number and name
for(int i=0; i<station.length; i++){
station[i] = new Station();
station[i].setStationNumber(i+1);
station[0].setStationName("Station #"+(i+1));
}
}
/**
* This method starts the train simulation.
*
*/
public void start()
{
//have all background processing done by a SwingWorker so GUI does not freeze
new SimulationWorker().execute();
}
public static void sleep(int time)
{
try{
Thread.sleep(time * 300);
}
catch(Exception e) {}
}
public void stop()
{
System.exit(0);
}
class SimulationWorker extends SwingWorker<Void,Integer>{
boolean stop = false; //use if you wish to stop
//do background processing
#Override
protected Void doInBackground() throws Exception {
while(! stop){
int stationNumber = 0;
int time = 0;
boolean forwards;
stationNumber = train.getStationNumber();
forwards = train.getDirection();
if (stationNumber == 1){
forwards = true;
train.setDirection(forwards);
}
else if (stationNumber == 15){
forwards = false;
train.setDirection(forwards);
}
if (forwards == true){
time = forwardTimeArray[stationNumber+1];//time = forwardTimeArray[stationNumber-1];
sleep(time);
stationNumber = stationNumber + 1;
//System.out.println("Station Number:" + stationNumber);
train.setStationNumber(stationNumber);
}
else{
time = backwardTimeArray[stationNumber-2];
sleep(time);
stationNumber = stationNumber - 1;
//System.out.println("Station Number:" + stationNumber);
train.setStationNumber(stationNumber);
}
publish(train.getStationNumber()); //publish result (station number)
}
return null;
}
//process published information
#Override
protected void process(List<Integer> stationsList) {
for(int stationNumber : stationsList){
listener.valueChanged("Train is at "+ stationNumber); //notify listener
}
}
}
}
class Train {
private int stationNumber = 0;
private boolean forwards = true ;
public int getStationNumber() {
return stationNumber;
}
public void setDirection(boolean forwards) {
this.forwards = forwards;
}
public void setStationNumber(int stationNumber) {
this.stationNumber = stationNumber;
}
public boolean getDirection() {
return forwards;
}
}
class Station {
private int stationNumber;
private String stationName;
public void setStationNumber(int stationNumber) {
this.stationNumber = stationNumber;
}
public void setStationName(String stationName) {
this.stationName = stationName;
}
}
//an interface use by Sim to listen to SimEngine changes
interface Listener {
void valueChanged(String newValue);
}
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'm having an issue with Item Listeners.It's the first time I'm using it, so far all I've used is the Item Event. I was wondering if you could clear up what the difference between those two, as well point me out what I'm doing wrong.
My issue is on line 46 the line starting with: Object source = toppingList.getSource(); and the error I get is 'Cannot find symbol'.
I'm thinking I'm using the wrong item before the getSource();, I thought that the toppingList was the correct item, I can't see which other item I could put in it's place.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Pizza extends JFrame{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public Pizza()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
pizzaBox.addItemListener((ItemListener) this);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent[] list)
{
Object source = toppingList.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
Gui elements do not have any getSource, it is a method of the event - telling you which gui element generated the event. But you know what the source of the event is, since in your constructor you wrote:
pizzaBox.addItemListener((ItemListener) this);
and you did not add this to any other gui element. So you cannot get events from any other gui element. So do not test for it.
But there are other issues:
Your PizzaBox should implement ItemListener:
public class Pizza extends JFrame implement ItemListener
and then just write
pizzaBox.addItemListener(this);
If you want to listen to multiple elements, add separate anonymous listener for each (and Pizza does not implement ItemListener)
// in your constructor:
pizzaBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
pizzaNum = pizzaBox.getSelectedIndex(); // in your code you have int pizzaNum but at the same time, pizzaNum is a class variable, probably an error
// and so on
}
}
});
or you can move the code to a separate method
public class Pizza extends JFrame {
public Pizza() {
:
pizzaBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pizzaBox_itemStateChanged(e);
}
});
:
}
private void pizzaBox_itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
pizzaNum = pizzaBox.getSelectedIndex();
// and so on
}
}
:
}
You need to implement ItemListener with class. For details go through this tutorial
public class Pizza extends JFrame implements ItemListener{
.....
public Pizza(){
pizzaBox.addItemListener(this);// Here this is enough
....
}
// itemStateChanged should write as follows
public void itemStateChanged(ItemEvent e) {
//It will be enable if checkbox is selected
if (e.getStateChange() == ItemEvent.SELECTED) {
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
What is the best way to handle key presses in Java? I was trying to set up my KeyListener code but then I saw online KeyBinding is what should be used but after reading
http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
and not being able to find any tutorials online I am even more confused.
Here is what i have been trying:
frame = new JFrame("Jay's Game Title");
Container panel = (JPanel)frame.getContentPane();
...
panel.setFocusable(true);
panel.requestFocus();
panel.addKeyListener(this);//TODO:fix me please, this is not working
frame.setSize(1024, 768);
frame.setVisible(true);
frame.setFocusable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
but to no avail. Any help is much appreciated and in the meantime I will continue to look over others' posts and pull more of my hair out.
note: my code for my buttons work just great, and I would love to have my keypresses handled in another keypresses.java file or something to keep it organized
package com.jayavon.game.client;
/****************************************************************
* Author : ***REMOVED***
* Start Date : 09/04/2011
* Last Update : 10/04/2011
*
* Description
* This is the video game application
* This application is used to sending and receiving the messages
* and all of the game data(soon, hopefully :p).
*
* Remarks
* Before running the client application make sure the server is
* running.
******************************************************************/
import javax.swing.*;
import java.awt.Container;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
public class MyClient extends JFrame implements ActionListener, KeyListener{
JFrame frame;
JTextField chatBoxTxt;
JButton sendButton, exitButton, onlineButton, backpackButton, characterButton, helpButton, optionsButton, questsButton, skillsButton;
JInternalFrame skillsFrame, onlineFrame;
DefaultListModel modelChatList;
JList listForChat;
JScrollPane chatScrollPane;
DefaultListModel modelUserList;
JList listForUsers;
JScrollPane userListScrollPane;
String name, password;
Socket s, s1, s2;
DataInputStream messageIn;
DataOutputStream messageOut;
DataInputStream userNameIn;
DataOutputStream userNameOut;
DataOutputStream userLogOut;
MyClient(String name, String password) throws IOException{
this.name = name;
initGUI();
s = new Socket("localhost",1004); //creates a socket object
s1 = new Socket("localhost",1004);
s2 = new Socket("localhost",1004);
//create input-stream for a particular socket
messageIn = new DataInputStream(s.getInputStream());
//create output-stream
messageOut = new DataOutputStream(s.getOutputStream());
//sending a message for login
messageOut.writeUTF(name + " has joined the game.");
userLogOut = new DataOutputStream(s1.getOutputStream());
userNameOut = new DataOutputStream(s2.getOutputStream());
userNameIn = new DataInputStream(s2.getInputStream());
//creating a thread for maintaining the list of user name
MyUserNameReciever userNameReciever = new MyUserNameReciever(userNameOut, modelUserList, name, userNameIn);
Thread userNameRecieverThread = new Thread(userNameReciever);
userNameRecieverThread.start();
//creating a thread for receiving a messages
MyMessageReciever messageReciever = new MyMessageReciever(messageIn, modelChatList);
Thread messageRecieverThread = new Thread(messageReciever);
messageRecieverThread.start();
}
public void initGUI(){
frame = new JFrame("Jay's Game Title");
Container panel = (JPanel)frame.getContentPane();
chatBoxTxt = new JTextField();
panel.add(chatBoxTxt);
chatBoxTxt.setBounds(5,605,650,30);
chatBoxTxt.setVisible(false);
sendButton = new JButton("Send");
sendButton.addActionListener(this);
panel.add(sendButton);
sendButton.setBounds(260,180,90,30);
modelChatList = new DefaultListModel();
listForChat = new JList(modelChatList);
chatScrollPane = new JScrollPane(listForChat);
panel.add(chatScrollPane);
chatScrollPane.setBounds(5,640,650,80);
modelUserList = new DefaultListModel();
listForUsers = new JList(modelUserList);
userListScrollPane = new JScrollPane(listForUsers);
userListScrollPane.setSize(100,250);
userListScrollPane.setVisible(false);
backpackButton = new JButton(new ImageIcon("images/gui/button_backpack.png"));
backpackButton.addActionListener(this);
backpackButton.setBounds(660,686,33,33);
backpackButton.setBorderPainted(false);backpackButton.setFocusPainted(false);
backpackButton.setToolTipText("Backpack[B]");
panel.add(backpackButton);
characterButton = new JButton(new ImageIcon("images/gui/button_character.png"));
characterButton.addActionListener(this);
characterButton.setBounds(695,686,33,33);
characterButton.setBorderPainted(false);characterButton.setFocusPainted(false);
characterButton.setToolTipText("Character[C]");
panel.add(characterButton);
skillsButton = new JButton(new ImageIcon("images/gui/button_skills.png"));
skillsButton.addActionListener(this);
skillsButton.setBounds(730,686,33,33);
skillsButton.setBorderPainted(false);skillsButton.setFocusPainted(false);
skillsButton.setToolTipText("Skills[V]");
panel.add(skillsButton);
questsButton = new JButton(new ImageIcon("images/gui/button_quests.png"));
questsButton.addActionListener(this);
questsButton.setBounds(765,686,33,33);
questsButton.setBorderPainted(false);questsButton.setFocusPainted(false);
questsButton.setToolTipText("Quests[N]");
panel.add(questsButton);
onlineButton = new JButton(new ImageIcon("images/gui/button_online.png"));
onlineButton.addActionListener(this);
onlineButton.setBounds(800,686,33,33);
onlineButton.setBorderPainted(false);onlineButton.setFocusPainted(false);
onlineButton.setToolTipText("Online List[U]");
panel.add(onlineButton);
helpButton = new JButton(new ImageIcon("images/gui/button_help.png"));
helpButton.addActionListener(this);
helpButton.setBounds(835,686,33,33);
helpButton.setBorderPainted(false);helpButton.setFocusPainted(false);
helpButton.setToolTipText("Help[I]");
panel.add(helpButton);
optionsButton = new JButton(new ImageIcon("images/gui/button_options.png"));
optionsButton.addActionListener(this);
optionsButton.setBounds(870,686,33,33);
optionsButton.setBorderPainted(false);optionsButton.setFocusPainted(false);
optionsButton.setToolTipText("Options[O]");
panel.add(optionsButton);
exitButton = new JButton(new ImageIcon("images/gui/button_exit.png"));
exitButton.addActionListener(this);
exitButton.setBounds(905,686,33,33);
exitButton.setBorderPainted(false);exitButton.setFocusPainted(false);
exitButton.setToolTipText("Exit[none]");
panel.add(exitButton);
skillsFrame = new JInternalFrame("Skills", true, true, false, false);
skillsFrame.setBounds(600, 10, 400, 500);
skillsFrame.setVisible(false);
panel.add(skillsFrame);
onlineFrame = new JInternalFrame("Users", true, true, false, false);
onlineFrame.setContentPane(userListScrollPane);
onlineFrame.setBounds(850, 10, 150, 300);
onlineFrame.setVisible(false);
panel.add(onlineFrame);
panel.setLayout(null);
panel.setFocusable(true);
panel.requestFocus();
panel.addKeyListener(this);//TODO:fix me please, this is not working
frame.setSize(1024, 768);
frame.setVisible(true);
frame.setFocusable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
// sending the messages
if(e.getSource() == sendButton && chatBoxTxt.isVisible() == false){
chatBoxTxt.setVisible(true);
chatBoxTxt.requestFocus(true);
} else if (e.getSource() == sendButton && chatBoxTxt.isVisible() == true){
String str = "";
str = chatBoxTxt.getText();
if (str != ""){
str = name + ": > " + str;
try{
messageOut.writeUTF(str);
System.out.println(str);
messageOut.flush();
}catch(IOException ae)
{System.out.println(ae);}
}
//and hide chatBoxTxt
chatBoxTxt.setText("");
chatBoxTxt.setVisible(false);
}
// show user list
if (e.getSource() == onlineButton){
if (userListScrollPane.isVisible()){
userListScrollPane.setVisible(false);
} else {
userListScrollPane.setVisible(true);
}
if (onlineFrame.isVisible()){
onlineFrame.setVisible(false);
} else {
onlineFrame.setVisible(true);
}
}
// show skill list
if (e.getSource() == skillsButton){
if (skillsFrame.isVisible()){
skillsFrame.setVisible(false);
} else {
skillsFrame.setVisible(true);
}
}
// client logout
if (e.getSource() == exitButton){
int exit = JOptionPane.showConfirmDialog(this, "Are you sure you want to exit?");
if (exit == JOptionPane.YES_OPTION){
frame.dispose();
try{
//sending the message for logout
messageOut.writeUTF(name + " has logged out.");
userLogOut.writeUTF(name);
userLogOut.flush();
Thread.currentThread().sleep(1000);
System.exit(1);
}catch(Exception oe){}
}
}
}
public void windowClosing(WindowEvent w){
try{
userLogOut.writeUTF(name + " has logged out.");
userLogOut.flush();
Thread.currentThread().sleep(1000);
System.exit(1);
}catch(Exception oe){}
}
#Override
public void keyPressed(KeyEvent e) {
int id = e.getID();
//open up chatBoxTxt for typing
if (id == KeyEvent.VK_ENTER && !chatBoxTxt.isVisible()){
chatBoxTxt.setVisible(true);
chatBoxTxt.requestFocus(true);
} //it is open so want to send text
else if (id == KeyEvent.VK_ENTER && chatBoxTxt.isVisible()) {
//send message
String str = "";
str = chatBoxTxt.getText();
//make sure there is a message
if (str.length() > 0){
chatBoxTxt.setText("");
str = name + ": > " + str;
try{
messageOut.writeUTF(str);
System.out.println(str);
messageOut.flush();
}catch(IOException ae)
{System.out.println(ae);}
}
//and hide chatBoxTxt
chatBoxTxt.setVisible(false);
} //press (Map) key without chatBoxTxt being open
else if (id == KeyEvent.VK_M && !chatBoxTxt.isVisible()){
} //press (Character) key without chatBoxTxt being open
else if (id == KeyEvent.VK_C && !chatBoxTxt.isVisible()){
} //press (Backpack) key without chatBoxTxt being open
else if (id == KeyEvent.VK_B && !chatBoxTxt.isVisible()){
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
// class is used to maintain the list of user name
class MyUserNameReciever implements Runnable{
DataOutputStream userNameOut;
DefaultListModel modelUserList;
DataInputStream userNameIn;
String name, lname;
ArrayList alname = new ArrayList(); //stores the list of user names
ObjectInputStream obj; // read the list of user names
int i = 0;
MyUserNameReciever(DataOutputStream userNameOut, DefaultListModel modelUserList, String name, DataInputStream userNameIn){
this.userNameOut = userNameOut;
this.modelUserList = modelUserList;
this.name = name;
this.userNameIn = userNameIn;
}
public void run(){
try{
userNameOut.writeUTF(name); // write the user name in output stream
while(true){
obj = new ObjectInputStream(userNameIn);
//read the list of user names
alname = (ArrayList)obj.readObject();
if(i>0)
modelUserList.clear();
Iterator i1 = alname.iterator();
System.out.println(alname);
while(i1.hasNext()){
lname = (String)i1.next();
i++;
//add the user names in list box
modelUserList.addElement(lname);
}
}
}catch(Exception oe){}
}
}
//class is used to received the messages
class MyMessageReciever implements Runnable{
DataInputStream messageIn;
DefaultListModel modelChatList;
MyMessageReciever(DataInputStream messageIn, DefaultListModel modelChatList){
this.messageIn = messageIn;
this.modelChatList = modelChatList;
}
public void run(){
String incommingMessage = "";
while(true){
try{
incommingMessage = messageIn.readUTF(); // receive the message from server
// add the message in list box
modelChatList.addElement(incommingMessage);
/* forces chat to bottom of screen :TODO but doesn't allow scrolling up
chatScrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}});*/
}catch(Exception e){}
}
}
}
}
and not being able to find any tutorials online I am even more confused.
That link is a tutorial. Unless you ask a specific question we don't know what you don't understand.
my code for my buttons work just great
It looks like you want the Enter key to do the same processing as clicking on a button. In this case the simple solution is to add an ActionListener to the text field instead of using Key Bindings. You should NOT even consider using a KeyListener for this.
Of course this means you need to redesign your program to use a different ActionListener for each button. So you need "Send", "Online", "Skills", and "Exit" ActionListeners. Then the "Send" ActionListener can be used by both the send button and the text field.
Edit:
for example: the user can hit (VK_V) or click the skills button to show the skills internal frame
You would use Key Bindings for this. You can do the bindings manually as described in the tutorial.
Or, an easier solution is to use a JMenu with menu items to invoke your Actions. Then you can just set an Accelerator for the menu item. Read the section from the Swing tutorial on How to Use Menus for more information.
Any further help will require you to post your SSCCE,