I'm currently working on a Magic8Ball game, very basic, although I did change it to a genie theme, and now I've decided to add sound to the game.
Basically I have prepared the reading of the answers and saved them as an audio file (mp3), and I want to attribute each voice over to the appropriate array string.
So if the voice reading says "as I see it, yes" it should be linked to array[0] which contains that answer. So ultimately, I want the game to say the answers to the player as it displays the answer.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class CompSays02GUI extends JFrame {
public static void main(String[] args) {
//set look and feel for UI as deault operating system look
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//start the program
new CompSays02GUI().setVisible(true);
}
public CompSays02GUI() {
setTitle("Genie Game");
setSize(725, 525);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
addComponents();
}
private void addComponents() {
MainPanel background = new MainPanel();
add(background, BorderLayout.CENTER);
}
private class MainPanel extends JPanel implements ActionListener {
private JTextField question;
private JButton ask;
private JButton exit;
private JLabel result;
/**
* Initialize MainPanel
*/
public MainPanel() {
setLayout(null); // set to free layout
addComponents();
}
/**
* Add components to JPanel
*/
private void addComponents() {
//question text field
question = new JTextField();
question.setForeground(Color.BLUE); //set the foreground color
question.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16)); // set the font
question.setBounds(100, 120, 250, 33); // set location, width and height
add(question);
//ask button
ask = new JButton("Ask");
ask.addActionListener(this); // add action listener to handle button click
ask.setBackground(Color.BLUE); // set background color
ask.setForeground(Color.WHITE); // set text color
ask.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20)); // set font
ask.setBounds(400, 120, 80, 33); // set location, width and height
add(ask);
//exit button
exit = new JButton("Exit");
exit.addActionListener(this);
exit.setBackground(Color.RED);
exit.setForeground(Color.WHITE);
exit.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20));
exit.setBounds(500, 120, 80, 33);
add(exit);
//result label
result = new JLabel();
result.setForeground(Color.BLACK);
result.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 22));
result.setBounds(250, 200, 400, 33);
add(result);
}
/**
* Paint the image in background
*
* #param g Graphics
*/
#Override
public void paintComponent(Graphics g) {
try {
super.paintComponents(g);
//read the image
Image img = ImageIO.read(new File("resources/genie.png"));
//draw in background of panel
g.drawImage(img, 0, 0, null);
} catch (IOException ex) { // else if image not found, print error
System.out.println("Error: Image 'genie.png' not found");
System.out.println(ex.getMessage());
}
}
/**
* Handle the ask and exit buttons clicks
*
* #param e ActionEvent
*/
#Override
public void actionPerformed(ActionEvent e) {
// if ask button clicked
if (e.getSource() == ask) {
//get question
String ques = question.getText();
//if it's empty
if (ques.isEmpty()) {
JOptionPane.showMessageDialog(this, "Error: Your question "
+ "was not stated as a yes or no. Try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
//check the question and continue else if it's valid
if (questionCheck(ques)) {
result.setText(printResult(ques));
}
}
// if exit button clicked
if (e.getSource() == exit) {
//print message
JOptionPane.showMessageDialog(this, "Thanks for playing!\n\n");
}
}
/**
* Check else if the question is valid
*
* #param ques String
* #return boolean
*/
private boolean questionCheck(String ques) {
// They have a valid question
boolean result = true;
//else if it's not yes/no question
if (ques.indexOf("who") != -1 || ques.indexOf("what") != -1
|| ques.indexOf("why") != -1 || ques.indexOf("which") != -1
|| ques.indexOf("how") != -1 || ques.indexOf("When") != -1
|| ques.indexOf("whats") != -1 || ques.indexOf("what's") != -1) {
result = false;
JOptionPane.showMessageDialog(this, "Error: Your question was "
+ "not stated as a yes or no. Try again.", "Error",
JOptionPane.ERROR_MESSAGE);
}
return result;
}
/**
* Generate random number from 1-20 and return the result answer
*
* #return String
*/
private String printResult(String ques) {
String[] answers = new String [20];
answers[0] = "As i see it, yes";
answers[1] = "It is certain";
answers[2] = "It is decidedly so";
answers[3] = "Most Likely";
answers[4] = "Outlook looking good";
answers[5] = "Sign points to yes";
answers[6] = "Without a doubt";
answers[7] = "Yes";
answers[8] = "Yes, definitely";
answers[9] = "You shouldn't rely on it";
answers[10] = "Reply hazy, try again";
answers[11] = "Try again later";
answers[12] = "Better not tell you now";
answers[13] = "Cannor predict now";
answers[14] = "Concentrate and ask again";
answers[15] = "Don't count on it";
answers[16] = "My reply is... NO!";
answers[17] = "My sources say no";
answers[18] = "Outlook not so good";
answers[19] = "Very doubtful";
Random nexGen = new Random();
int nextAnswer = nexGen.nextInt(answers.length);
return answers[nextAnswer];
}
}
Please help.
Thanks.
Simple example for playing a sound:
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.net.URL;
import java.io.*;
class SoundTest {
public static void main(String[] args) throws Exception {
URL urlToSound = new URL("file:c:/java/gun1.wav");
// URL urlToSound = new URL("file:c:/java/flyby1.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(urlToSound);
final Clip clip = AudioSystem.getClip();
clip.open(ais);
JButton button = new JButton("Play Sound");
button.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
clip.setFramePosition(0);
clip.start();
}
} );
JOptionPane.showMessageDialog(null, button);
}
}
Related
When I run my code there is only the empty frame. To see the JButton and the JTextFields I have to search and click on them before they are visible. I searched everywhere on the Internet but I found nothing. I also set the visibility to true and added the JComponents. Here is my Code:
Frame Fenster = new Frame();
And this...
package me.JavaProgramm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Frame extends JFrame {
private JButton bChange;
private JTextField tvonEur;
private JTextField tzuOCur; //andere Währung (other Currency)
private JTextField tzuEur;
private JTextField tvonOCur;
private JComboBox cbCur; //Wärhung wählen
private String curName;
private double faktorUSD;
private double faktorGBP;
private static String[] comboCur = {"USD", "GBP"};
public Frame() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Währungsrechner");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setResizable(false);
Font schrift = new Font("Serif", Font.PLAIN + Font.ITALIC, 30);
tvonEur = new JTextField("Euro");
tvonEur.setSize(80, 25);
tvonEur.setLocation(20, 50);
tvonEur.requestFocusInWindow();
tvonEur.selectAll();
tzuEur = new JTextField("Euro");
tzuEur.setSize(80, 25);
tzuEur.setLocation(20, 150);
tzuEur.requestFocusInWindow();
tzuEur.selectAll();
bChange = new JButton("Euro zu US-Dollar");
bChange.setSize(120, 25);
bChange.setLocation(110, 50);
tzuOCur = new JTextField("US-Dollar");
tzuOCur.setSize(80, 25);
tzuOCur.setLocation(240, 50);
tzuOCur.requestFocusInWindow();
tzuOCur.selectAll();
tvonOCur = new JTextField("US-Dollar");
tvonOCur.setSize(80, 25);
tvonOCur.setLocation(240, 50);
tvonOCur.requestFocusInWindow();
tvonOCur.selectAll();
cbCur = new JComboBox(comboCur);
cbCur.setSize(100, 20);
cbCur.setLocation(100, 100);
tvonEur.setVisible(true);
tzuEur.setVisible(true);
tzuOCur.setVisible(true);
tvonOCur.setVisible(true);
bChange.setVisible(true);
cbCur.setVisible(true);
add(tvonEur);
add(bChange);
add(tzuOCur);
add(cbCur);
Currency currency = new Currency();
String strUSD = currency.convertUSD();
try {
NumberFormat formatUSD = NumberFormat.getInstance(Locale.GERMANY);
Number numberUSD = formatUSD.parse(strUSD);
faktorUSD = numberUSD.doubleValue();
System.out.println(faktorUSD);
} catch (ParseException e) {
System.out.println(e);
}
String strGBP = currency.convertGBP();
try {
NumberFormat formatGBP = NumberFormat.getInstance(Locale.GERMANY);
Number numberGBP = formatGBP.parse(strGBP);
faktorGBP = numberGBP.doubleValue();
System.out.println(faktorGBP);
} catch (ParseException e) {
System.out.println(e);
}
cbCur.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cbCur = (JComboBox) e.getSource();
curName = (String) cbCur.getSelectedItem();
if (curName == "USD") {
tzuOCur.setText("US-Dollar");
} else if (curName == "GBP") {
tzuOCur.setText("British-Pound");
}
}
});
bChange.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (curName == "USD") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleUSD = doubleEUR * faktorUSD;
tzuOCur.setText(Double.toString(roundScale3(doubleUSD)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
} else if (curName == "GBP") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleGBP = doubleEUR * faktorGBP;
tzuOCur.setText(Double.toString(roundScale3(doubleGBP)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
}
}
});
}
public static double roundScale3(double d) {
return Math.rint(d * 1000) / 1000.;
}
}
Try moving setVisible(true) after you add the children to the parent container.
Generally with Swing it's considered good practice to put code that updates visible components in the event dispatching thread, like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame.this.setVisible(true);
}
});
I'm writing a program that has a quiz element, and when the user gets an answer wrong, feedback is given. The question JFrame is made of a JLabel that has the actual question, and 4 JRadioButtons that have the different options (named rad1, rad2, rad3, rad4). What I'm trying to do is if the user gets an asnswer wrong, the radio button with the correct answer's background colour turns green and the radio button with the answer that the user gave's background turns red.
Here's the FOR loop that I'm using to figure out which of the answers is correct:
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("Submit Clicked");
//figures out what choice the user selected
String correctAnswer = questions.get(current).getAnswer();
int numChoice = -1;
String choice = "";
boolean answered = false;
if (rad1.isSelected()) {
numChoice = 0;
answered = true;
choice = rad1.getText();
} else if (rad2.isSelected()) {
numChoice = 1;
answered = true;
choice = rad2.getText();
} else if (rad3.isSelected()) {
numChoice = 2;
answered = true;
choice = rad3.getText();
} else if (rad4.isSelected()) {
numChoice = 3;
answered = true;
choice = rad4.getText();
} else { //user didn't pick a choice
JOptionPane.showMessageDialog(null, "You didn't answer the question, try again!");
}
if (choice.equals(correctAnswer)) {
score++;
System.out.println("score++");
} else {
//figures out which of the answers was correct
rad1.setBackground(Color.RED);
for (int i = 0; i < 4; i++) {
if (questions.get(current).getChoices()[i].equals(correctAnswer)) {
System.out.println(correctAnswer);
System.out.println(i);
//me trying to see if it will change if I put it outside the switch
//confirmed that it will not.
rad1.setBackground(Color.RED);
switch (i) {
case 0:
rad1.setBackground(new Color(51, 204, 51));
break;
case 1:
rad2.setBackground(new Color(51, 204, 51));
break;
case 2:
rad3.setBackground(new Color(51, 204, 51));
break;
case 3:
rad4.setBackground(new Color(51, 204, 51));
break;
}
break;
}
}
switch (numChoice) {
case 0:
rad1.setBackground(new Color(153, 0, 0));
break;
case 1:
rad2.setBackground(new Color(153, 0, 0));
break;
case 2:
rad3.setBackground(new Color(153, 0, 0));
break;
case 3:
rad4.setBackground(new Color(153, 0, 0));
break;
}
}
//loads next question
//loads the next question
if (current < 10) {
updateFrame();
} else {
//ends the quiz
}
}
I've been playing around with the .setBackground() method for a while, and if I put print statements in the case blocks, they execute, but the colouring doesn't happen. Is there something dumb that I'm missing?
Thanks
EDIT: Added more code to see that the FOR loop is within the btnSubmitActionPerformed() method. When the user clicks the button, their answer is to be judged and the colour of the radio button is to be changed.
You look to have code that is overly and unnecessarily complex. Myself, I'd try to "OOP-ify" things to reduce cyclomatic complexity and have
A nonGUI Question class,
with a String field for questionText,
with a String field for correctAnswer,
with a List<String> for incorrectAnswers.
I'd give it a method, say public List<String> getShuffledAnswers() to return a List of Strings with all answers, both correct and incorrect, shuffled in their own list,
A boolean method to testAnswer(String test), and return true of the test equals the correctAnswer.
I'd then create a JPanel called QuestionPanel
that has a Question field
that displays the information of a single Question object, including the questionText in the JLabel and all the shuffled answers in JRadioButtons.
It would have methods for getting the selected JRadioButton and for getting the Question,
And a method for setting making a JRadioButtons background non-opaque when need be, by calling `setOpaque(false)
And a method that allows the calling code to set the background of select JRadioButtons with a correct answer color or incorrect answer color.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class TestQuestions extends JPanel {
private static final Question TEST_QUESTION = new Question("Select the Correct Answer", "This answer is correct",
"Incorrect Answer 1", "Incorrect Answer 2", "Incorrect Answer 3");
private QuestionPanel questionPanel = new QuestionPanel();
public TestQuestions() {
questionPanel.setQuestion(TEST_QUESTION);
JButton testAnswerBtn = new JButton(new AbstractAction("Test Answer") {
#Override
public void actionPerformed(ActionEvent e) {
boolean isCorrect = questionPanel.isCorrectAnswerSelected();
String message = "";
if (isCorrect) {
message = "Correct answer selected!";
} else {
message = "Incorrect answer selected!";
}
JOptionPane.showMessageDialog(TestQuestions.this, message);
questionPanel.displayCorrectWrongAnswers();
}
});
JButton clearAllBtn = new JButton(new AbstractAction("Clear All") {
#Override
public void actionPerformed(ActionEvent e) {
questionPanel.clearAll();
questionPanel.clearSelection();
}
});
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
btnPanel.add(testAnswerBtn);
btnPanel.add(clearAllBtn);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(questionPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TestQuestions");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestQuestions());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class QuestionPanel extends JPanel {
private static final Color CORRECT_ANSWER_SELECTED_COLOR = new Color(151, 255, 151);
private static final Color CORRECT_ANSWER_NOT_SELECTED_COLOR = new Color(151,151, 255);
private static final Color INCORRECT_ANSWER_SELECTED_COLOR = new Color(255, 151, 151);
private Question question;
private JLabel questionTextLabel = new JLabel();
private List<JRadioButton> answerButtonList = new ArrayList<>();
private JPanel answerPanel = new JPanel(new GridLayout(0, 1));
private ButtonGroup buttonGroup = new ButtonGroup();
public QuestionPanel() {
setLayout(new BorderLayout());
add(questionTextLabel, BorderLayout.PAGE_START);
add(answerPanel, BorderLayout.CENTER);
}
public void setQuestion(Question question) {
this.question = question;
questionTextLabel.setText(question.getQuestionText());
answerPanel.removeAll();
answerButtonList.clear();
buttonGroup = new ButtonGroup();
for (String answer : question.getShuffledAnswers()) {
JRadioButton rBtn = new JRadioButton(answer);
rBtn.setActionCommand(answer);
answerButtonList.add(rBtn);
buttonGroup.add(rBtn);
answerPanel.add(rBtn);
}
}
public boolean isCorrectAnswerSelected() {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
return false; // nothing selected
} else {
return question.checkAnswer(model.getActionCommand());
}
}
public void clearAll() {
for (JRadioButton jRadioButton : answerButtonList) {
jRadioButton.setOpaque(false);
jRadioButton.setBackground(null);
}
}
public void clearSelection() {
buttonGroup.clearSelection();
}
public void displayCorrectWrongAnswers() {
clearAll();
for (JRadioButton jRadioButton : answerButtonList) {
if (jRadioButton.isSelected()) {
jRadioButton.setOpaque(true);
if (question.checkAnswer(jRadioButton.getActionCommand())) {
jRadioButton.setBackground(CORRECT_ANSWER_SELECTED_COLOR);
} else {
jRadioButton.setBackground(CORRECT_ANSWER_NOT_SELECTED_COLOR);
}
} else if (question.checkAnswer(jRadioButton.getActionCommand())) {
jRadioButton.setOpaque(true);
jRadioButton.setBackground(INCORRECT_ANSWER_SELECTED_COLOR);
}
}
}
}
class Question {
private String questionText;
private String correctAnswer;
private List<String> incorrectAnswerList = new ArrayList<>();
public Question(String questionText, String correctAnswer, String... incorrectAnswers) {
this.questionText = questionText;
this.correctAnswer = correctAnswer;
for (String incorrectAnswer : incorrectAnswers) {
incorrectAnswerList.add(incorrectAnswer);
}
}
public String getQuestionText() {
return questionText;
}
public String getCorrectAnswer() {
return correctAnswer;
}
public List<String> getShuffledAnswers() {
List<String> answers = new ArrayList<>(incorrectAnswerList);
answers.add(correctAnswer);
Collections.shuffle(answers);
return answers;
}
public boolean checkAnswer(String test) {
return correctAnswer.equalsIgnoreCase(test);
}
}
Two immediate things jump to mind:
Where is the code you posted being called from? Making UI changes outside of the Swing worker thread is sort of undefined. Sometimes the right thing will happen, other times not.
I've never tried to set colors on radio buttons, but it seems likely that they don't have a background.
Try setting some other property, like size, just to see if you get a result. If so, then the problem is that radio buttons don't have a background and you'll have to come up with another design. If nothing happens, then it's probably the first problem.
Right so it's not working, I also tried setVisible(False) that said something about can't make static reference to boolean or something like that.
Here's my code can you please help me fix this? I won't have time to make major so small changes if possible to make it work thank you.
To make your life easier so you don't read my whole code just do ctrl + f"okbtn"
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.*;
import java.awt.event.*;
import java.util.Arrays;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class MainMenu extends javax.swing.JFrame {
private JLabel username;
private JLabel passwordlbl;
private JLabel Welco;
private JButton Cancelbtn;
private JButton OKbtn;
private JTextField Usernametxt;
double ss;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
//PASSWORD field to store new password inside
//Passwordfld.setEchoChar('*');
//Passwordfld.addActionListener(new AL());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainMenu inst = new MainMenu();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public MainMenu() {
super();
initGUI();
}
private static boolean isPasswordCorrect(char[] input) {
boolean isCorrect = true;
char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}
//Zero out the password.
Arrays.fill(correctPassword,'0');
return isCorrect;
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
getContentPane().setBackground(new java.awt.Color(11,101,149));
username = new JLabel();
getContentPane().add(username);
username.setText("User Name:");
username.setBounds(63, 113, 80, 16);
passwordlbl = new JLabel();
getContentPane().add(passwordlbl);
passwordlbl.setText("Password:");
passwordlbl.setBounds(63, 160, 72, 16);
Usernametxt = new JTextField();
getContentPane().add(Usernametxt);
Usernametxt.setBounds(198, 110, 79, 23);
final JPasswordField Passwordfld = new JPasswordField();
// Passwordfld.setText("Secret");
getContentPane().add(Passwordfld);
Passwordfld.setBounds(198, 157, 79, 23);
Passwordfld.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.out.println("Passwordfld.actionPerformed, event="+evt);
// TODO add your code for Passwordfld.actionPerformed
}
});
OKbtn = new JButton();
getContentPane().add(OKbtn);
OKbtn.setText("OK");
OKbtn.setBounds(102, 217, 59, 23);
OKbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String passText = new String(Passwordfld.getPassword());
String cmd = evt.getActionCommand();
/*This where the the majority of the code is executed
Once the user types his info in and clicks the "ok button" the code is then executed and then depending
if the user gets his info correct the system communicates with the user allowing them to know if they
succeeded in logging in.*/
if (OKbtn.getActionCommand().equals(cmd)) { // Process the password.
if (Usernametxt.getText().equals("Admin")&& (isPasswordCorrect(passText.toCharArray()))) {
JOptionPane.showMessageDialog(MainMenu.this,
"Password Accepted");
System.out.println("Password Accepted");
ItemsPage ItemsPage = new ItemsPage(ss);
this.setVisible(false);
ItemsPage.setVisible(true);
} else {
JOptionPane.showMessageDialog(MainMenu.this,
"Password Rejected");
System.out.println("Password Rejected: " + passText);
}
// Zero out the possible password, for security.
Arrays.fill(passText.toCharArray(), '0');
Passwordfld.selectAll();
/*
* else{ System.out.println("permition Rejected"); }
*/
// else{}
/*
* if (Passwordfld = Password)= true) {
* System.out.println("permition granted");}
*/
}
}
private void setVisible(boolean b) {
// TODO Auto-generated method stub
}
});
Cancelbtn = new JButton();
getContentPane().add(Cancelbtn);
Cancelbtn.setText("Exit");
Cancelbtn.setBounds(198, 217, 61, 23);
Cancelbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);//shuts down the program
//System.out.println("Cancelbtn.actionPerformed, event="+evt);
//TODO add your code for Cancelbtn.actionPerformed
}
});
Welco = new JLabel();
getContentPane().add(Welco);
Welco.setText("Welcome to Jstore please log in using your staff acount");
Welco.setBounds(51, 19, 291, 16);
pack();
setSize(400, 300);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
//static class AL implements ActionListener{
//JPasswordField input = new JPasswordField();
/* char [] passy = input.getPassword();
String p = new String (passy);{
if (p.equals (Password)){
JOptionPane.showMessageDialog(null, "Correct"); }
else
{ JOptionPane.showMessageDialog(null, "InCorrect");
}
*/
}
The question is, I try to make second textfield (textFieldGen) to print out the exact result likes console. Currently, second textfield shows one string only.
This is my first coding on java GUI.
(extra info, I built it using Eclipse with WindowBuilder + GEF )
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.TextField;
import java.awt.Label;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class PassGenerator {
private JFrame frmPasswordGenerator;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PassGenerator window = new PassGenerator();
window.frmPasswordGenerator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PassGenerator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmPasswordGenerator = new JFrame();
frmPasswordGenerator.setTitle("Password Generator");
frmPasswordGenerator.setBounds(100, 100, 419, 229);
frmPasswordGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPasswordGenerator.getContentPane().setLayout(null);
final TextField textFieldGen = new TextField();
final TextField textFieldPass = new TextField();
textFieldPass.setBounds(74, 60, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldPass);
Label labelPass = new Label("Password Length:");
labelPass.setBounds(74, 33, 177, 21);
frmPasswordGenerator.getContentPane().add(labelPass);
Button genButton = new Button("Generate");
genButton.setBounds(262, 60, 86, 23);
frmPasswordGenerator.getContentPane().add(genButton);
// Add action listener to button
genButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
//System.out.println("You clicked the button");
String getTxt = textFieldPass.getText();
boolean y = true;
do{
try{
int c = Integer.parseInt(getTxt);
Random r = new Random();
String[] alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","w","x","y","z"};
int nc = 0-c;
int c2 = c/2;
int nc2 = 0-c2;
int ncm = (nc+1)/2;
if (c%2 == 0){
for(int x = nc2; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
}
else {
for(int x = ncm; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
y = false;
}
catch (NumberFormatException e1 ){
int messageType = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(null, "Please Enter Integer only", "Error!!", messageType);
y = false;
}
}while (y);
}
});
Label labelGen = new Label("Generated Password:");
labelGen.setBounds(74, 109, 149, 21);
frmPasswordGenerator.getContentPane().add(labelGen);
textFieldGen.setBounds(74, 136, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldGen);
Button copyButton = new Button("Copy");
copyButton.setBounds(262, 136, 86, 23);
frmPasswordGenerator.getContentPane().add(copyButton);
}
}
Use textFieldGen.setText (textFieldGen.getText () + "\n" + Integer.toString(numNum))
I don't see why you are setting the contents of the text field twice. I would just do:
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
//textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
//textFieldGen.setText(Integer.toString(numNum));
textFieldGen.setText(alpha + Integer.toString(numNum));
In general it is not a good practice to replace the entire text when all you want to do is append some characters to the text field. If you don't like the above then you can do:
textField.setText(alpha);
...
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), Integer.toString(numNum), null);
Edit:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JTextField textField = new JTextField(20);
add( textField );
textField.setText( "testing: " );
try
{
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), "1", null);
}
catch(Exception e) {}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
I am trying to write a program in Java that takes a random number from 1-1000 and then as the guess it the background color changes to blue(cold) or red(warm) if they are in the number. I am new to java GUI, but I think the rest of the logic is right, not sure. It compiles, but the guess button doesn't work. Any guidance will be appreciated.
package guessGame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.color.*;
import java.util.Random;
import java.util.Random;
import java.util.logging.FileHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class GuessGame extends JFrame
{
private JFrame mainFrame;
private JButton GuessButton;
private JButton QuitButton;
private JLabel prompt1, prompt2;
private JTextField userInput;
private JLabel comment = new JLabel("What is your destiny?");
private JLabel comment2 = new JLabel (" ");
//private int number, guessCount;
//private int lastGuess;
private int randomNumber;
private Color background;
public GuessGame()
{
mainFrame = new JFrame ("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
GuessButton = new JButton("Guess");
QuitButton = new JButton("Quit");
prompt1 = new JLabel("I have a number between 1 and 1000.");
prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
comment = new JLabel ("What is your destiny?");
comment2 = new JLabel (" ");
userInput = new JTextField(5);
//userInput.addActionListener(new GuessHandler());
//content pane
Container c = mainFrame.getContentPane();
c.setLayout(new FlowLayout());
//adding component to the pane
c.add(prompt1);
c.add(prompt2);
c.add(userInput);
c.add(comment2);
c.add(GuessButton);
c.add(QuitButton);
c.add(comment);
GuessButton.setMnemonic('G');
QuitButton.setMnemonic('Q');
mainFrame.setSize(300,200);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
// define and register window event handler
// mainFrame.addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e)
// { System.exit(0); }
// });
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
GuessButton.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
QuitButton.addActionListener(qhandler);
}
public void paint (Graphics g)
{
super.paint(g);
setBackground(background);
}
class QuitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int getUserInput=0;
int diff;
int Difference;
randomNumber = new Random().nextInt(1001);
try {
getUserInput = Integer.parseInt(
userInput.getText().trim());
} catch (NumberFormatException ex){
comment.setText("Enter a VALID number!");
return;
}
if (getUserInput == randomNumber){
JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber,
JOptionPane.INFORMATION_MESSAGE);
randomNumber = new Random().nextInt(1000) + 1;
return;
}
if (getUserInput > randomNumber){
comment.setText( "Too High. Try a lower number." );
diff=getUserInput - randomNumber;
Difference=Math.abs(diff);
} else {
comment.setText( "Too Low. Try a higher number." );
diff=randomNumber - getUserInput;
Difference=Math.abs(diff);
}
if(Difference<=25){
comment2.setText("Cold");
setBackgroundColor(Color.blue);
}
if(Difference<=10){
comment2.setText("Warm");
setBackgroundColor(Color.red);
}
else {
}
}
private void setBackgroundColor(Color color) {
setBackgroundColor(color);
}
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
The colors aren't changing because your setBackgroundColor always uses Color.black. Change it to:
private void setBackgroundColor(Color color) {
setBackground(color);
}
As for the number always being zero. You do not instantiate the randomNumber field. Add this to your constructor:
randomNumber = new Random().nextInt(1001);
Another problem I noticed was you added a window listener to ensure the program exits when you close the window. This is implemented in JFrame. In the constructor add:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Instead of using the deprecated method:
mainFrame.show();
use the not deprecated:
mainFrame.setVisible(true);
Furthermore you have a field, which is never queried:
private Color background;
It's best to do the logic before connecting it to the gui. It's a lot easier to test and find the worst bugs.
Refactored code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessGame extends JFrame {
private JTextField userInput;
private JLabel comment = new JLabel("What is your destiny?");
private JLabel comment2 = new JLabel(" ");
private int randomNumber;
public GuessGame() {
super("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
JButton guessButton = new JButton("Guess");
JButton quitButton = new JButton("Quit");
JLabel prompt1 = new JLabel("I have a number between 1 and 1000.");
JLabel prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
comment = new JLabel("What is your destiny?");
comment2 = new JLabel(" ");
userInput = new JTextField(5);
//content pane
Container c = getContentPane();
setLayout(new FlowLayout());
//adding component to the pane
c.add(prompt1);
c.add(prompt2);
c.add(userInput);
c.add(comment2);
c.add(guessButton);
c.add(quitButton);
c.add(comment);
guessButton.setMnemonic('G');
quitButton.setMnemonic('Q');
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
initializeNumber();
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
guessButton.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
quitButton.addActionListener(qhandler);
}
private void initializeNumber() {
randomNumber = new Random().nextInt(1000) + 1;
}
class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int getUserInput;
int diff;
int Difference;
try {
getUserInput = Integer.parseInt(userInput.getText().trim());
if (getUserInput == randomNumber) {
JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber,
JOptionPane.INFORMATION_MESSAGE);
initializeNumber();
return;
}
if (getUserInput > randomNumber) {
comment.setText("Too High. Try a lower number.");
diff = getUserInput - randomNumber;
Difference = Math.abs(diff);
} else {
comment.setText("Too Low. Try a higher number.");
diff = randomNumber - getUserInput;
Difference = Math.abs(diff);
}
if (Difference <= 25) {
comment2.setText("Cold");
GuessGame.this.setBackgroundColor(Color.blue);
}
if (Difference <= 10) {
comment2.setText("Warm");
GuessGame.this.setBackgroundColor(Color.red);
}
} catch (NumberFormatException ex) {
comment.setText("Enter a VALID number!");
}
}
}
private void setBackgroundColor(Color color) {
getContentPane().setBackground(color);
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
You have more Swing components than you need, and you seem to be adding one set to the frame while manipulating another set. For example, you have two JTextFields, fieldBox and userInput. You add userInput to the frame, but check fieldBox for input in the Guess button handler. Since fieldBox is always empty, the NumberFormatException is caught by your exception handler (which should really just catch NumberFormatException, not Exception), and comment is updated with "Enter a VALID number!". However, just like with the double text area, comment isn't actually added to the frame, prompt1 and prompt2 are, so you can't see the change
I would write your logic without a UI first and test it until it was 100% correct. Just use a command line, text UI at first. Once that's done, put a GUI in front of it. It'll help to isolate your problems: once the text-driven logic is right, you'll know that future problems are due to UI.
It makes your MVC separation cleaner as well.