I'm currently working on a GUI where you enter your name and it tells you whether or not it has been accepted. Say that if the names "John" or "Jane" are entered then you get a "Verified" message or "Unverified" message if you type any other name. Here's what I have so far, just really unsure how to add the IF statement for detecting the certain names. Thanks.
NamePrompt.java
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
public NamePrompt(){
setLayout(new BorderLayout());
JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
SubmitButton.java
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class SubmitButton implements ActionListener {
JTextField nameInput;
public SubmitButton(JTextField textfield){
nameInput = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText() + " which is allowed.");
}
}
As mentioned in another answer, this should be handled in the actionPerformed method. However, going based on what you've presented to the community, here's something that should work;
if the names are case sensitive, your modification would be as such:
public SubmitButton(JTextField textfield){
nameInput = textfield;
if (nameInput.equals("InsertCaseSensitiveName")) {
//TODO: Verified Name
} else {
//TODO: Unverified Name
}
}
if case insensitive:
public SubmitButton(JTextField textfield){
nameInput = textfield;
if (nameInput.equalsIgnoreCase("InsertCaseSensitiveName")) {
//TODO: Verified Name
} else {
//TODO: Unverified Name
}
}
To use a list:
//initialize your list (formed so backwards compatible)
List<String> valid = new java.util.concurrent.CopyOnWriteArrayList<String>();
//Within a function, add all names to the list in lowercase (java.lang.String.toLowerCase())
public SubmitButton(JTextField textfield){
nameInput = textfield;
if (valid.contains(nameInput.toLowerCase()) {
//TODO: Verified Name
} else {
//TODO: Unverified Name
}
}
References:
conditional if statements
java.lang.String.equals
java.lang.String.equalsIgnoreCase
java.lang.String.toLowerCase
java.util.List
java.util.concurrent.CopyOnWriteArrayList
The actionPerformed method is called after clicking the submit button.
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText() + " which is allowed.");
// You can store the value of whatever the user enters.
String inputName = nameInput.getText();
// And add the if statements:
if(inputName.equals("John") {
JOptionPane.showMessageDialog(frame, "Verified");
}
}
Alternatively you can create a List of Strings that contains all the names that is accepted. Example:
List<String> acceptedNames = Arrays.asList(new String[]{"John", "Jane"});
// and check
if acceptedNames.contains(inputName) {
// verified.
}
Related
This program uses a user input file( users.txt) and gets the username and password. If the user enters the form with the correct username and password, it should display login successful.
For some reason when i test the program with users.txt, I am getting an Arrayindex out of bound exception.
LoginFrame.java:
/*
* 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 emptyframeviewer;
/**
*
* #author ACER
*/
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/*Business P11.26 Write a program with a graphical interface that implements a login window with text
fields for the user name and password. When the login is successful, hide the login
window and open a new window with a welcome message. Follow these rules for
validating the password:
1. The user name is not case sensitive.
2. The password is case sensitive.
3. The user has three opportunities to enter valid credentials.
Otherwise, display an error message and terminate the program. When the program
starts, read the file users.txt . Each line in that file contains a username and password,
separated by a space. You should make a users.txt file for testing your program.
Business P11.27 In Exercise P11.26, the password is shown as it is typed. Browse the Swing documentation
to find an appropriate component for entering a password. Improve the
solution of Exercise P11.26 by using this component instead of a text field. Each
time the user types a letter, show a ■ character.*/
#SuppressWarnings("serial")
public class LoginFrame extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private HashMap<String, String> usernamesAndPasswords;
private JTextField usernameField;
private JTextField passwordField;
private JButton loginButton;
private JPanel loginPanel;
private JPanel welcomePanel;
private JPanel mainPanel;
private CardLayout cardLayout;
public LoginFrame() {
this.createComponents();
super.setTitle("Login Panel");
super.setSize(FRAME_WIDTH, FRAME_HEIGHT);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setVisible(true);
}
private void createComponents() {
this.mainPanel = new JPanel(new CardLayout());
this.createHashMap();
this.loginPanel = this.createLoginPanel();
this.welcomePanel = this.createWelcomePanel();
this.mainPanel.add(this.loginPanel, "LoginPanel");
this.mainPanel.add(this.welcomePanel, "WelcomePanel");
this.cardLayout = (CardLayout) this.mainPanel.getLayout();
this.cardLayout.show(this.mainPanel, "LoginPanel");
super.add(this.mainPanel);
}
private JPanel createLoginPanel() {
JPanel panel = new JPanel(new GridLayout(3, 2));
this.loginButton = new JButton("Login");
final int TEXT_FIELD_SIZE = 10;
this.usernameField = new JTextField(TEXT_FIELD_SIZE);
this.passwordField = new JPasswordField(TEXT_FIELD_SIZE);
this.loginButton.addActionListener(new ActionListener() {
private int loginAttempts = 3;
#Override
public void actionPerformed(ActionEvent arg0) {
boolean loggedIn = false;
String inputUsername = usernameField.getText().toLowerCase();
String inputPassword = passwordField.getText();
if (this.loginAttempts == 1) {
JOptionPane.showMessageDialog(null, "Number of login attemtps exceeded. Exitting...");
System.exit(1);
}
for (Map.Entry<String, String> validUser : usernamesAndPasswords.entrySet()) {
if (inputUsername.equals(validUser.getKey().toLowerCase())) {
if (inputPassword.equals(validUser.getValue())) {
System.out.println("Login successful!");
cardLayout.show(mainPanel, "WelcomePanel");
loggedIn = true;
}
}
}
if (!loggedIn) {
this.loginAttempts -= 1;
String message = String.format("Invalid username/password. %d %s remaining", this.loginAttempts,
(this.loginAttempts > 1) ? "attempts" : "attempt");
JOptionPane.showMessageDialog(null, message, "LOGIN FAILED", JOptionPane.INFORMATION_MESSAGE);
}
}
});
panel.add(new JLabel("Username"));
panel.add(this.usernameField);
panel.add(new JLabel("Password"));
panel.add(this.passwordField);
panel.add(this.loginButton);
return panel;
}
private JPanel createWelcomePanel() {
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.add(new JLabel("Welcome"));
panel.add(new JButton("Change password"));
JButton logoutBtn = new JButton("Logout");
logoutBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
panel.add(logoutBtn);
return panel;
}
private void createHashMap() {
this.usernamesAndPasswords = new HashMap<String, String>();
try {
Scanner fileScanner = new Scanner(new File("usersff.txt"));
while (fileScanner.hasNextLine()) {
String[] line = fileScanner.nextLine().split(" ");
this.usernamesAndPasswords.put(line[0], line[1]);
System.out.println(line[0] + " " + line[1]);
}
fileScanner.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null,
"Error: no users.txt file found. No users/passwords available to read.", "USERS.TXT NOT FOUND!",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame testFrame = new LoginFrame();
}
}
test file: users.txt
John 234 Peter abc
If that is the only content in the file, please check the end of file for new line. You may also add small check.
Based on the only noticeable Array in the snippet
String[] line = fileScanner.nextLine().split(" ");
if(line.length == 2)
{
this.usernamesAndPasswords.put(line[0], line[1]);
System.out.println(line[0] + " " + line[1]);
}
There are many possibilities...
In my ActionListener class I have my if statements prompting the user to enter a string. When I try to execute the program, nothing happens. Before I added the JButton, the spelling game would appear in a small window and text could be entered, and a message displayed whether the correct spelling was given.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class spelling extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frame = new JFrame();
JButton button1;
public spelling() {
super("Question 1");
setLayout(new FlowLayout());
button1 = new JButton("Spelling game");
add(button1);
HandlerClass handler = new HandlerClass();
button1.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
JFrame frame2 = new JFrame();
String answer1 = JOptionPane.showInputDialog("recipracate, reciprocate, reciprokate");
if (answer1.equals("reciprocate")) {
JOptionPane.showMessageDialog(frame2, "recriprocate is the correct answer");
}
else {
JOptionPane.showMessageDialog(frame2, "is the wrong answer");
}
String answer2 = JOptionPane.showInputDialog("quintessence, quintessance, qwintessence");
if (answer2.equals("quintessence")) {
JOptionPane.showMessageDialog(frame2, "quintessence is the correct answer");
}
else {
JOptionPane.showMessageDialog(frame2, "That is the wrong answer");
}
}
}
}
import javax.swing.JFrame;
public class spellingmain {
public static void main(String[] args) {
spelling test = new spelling();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(300, 150);
test.setVisible(true);
}
}
Your complete example raises several issues that merit consideration going forward:
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
To avoid a NullPointerException, a common practice is to invoke the equals() method on the constant, which is known to be non-null.
"reciprocate".equals(answer1)
Make your error dialog easier to read by including relevant text.
answer1 + " is the wrong answer"
Don't extend JFrame unless you are adding new functionality.
Don't open a new frame needlessly; you can use the existing frame; a message dialog may have a parentComponent, but one is not required.
Test your program by clicking Cancel on a question to see the result. Consider how you intend to handle this.
Code as tested:
import java.awt.FlowLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class Spelling extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frame = new JFrame();
JButton button1;
public Spelling() {
super("Questionss");
setLayout(new FlowLayout());
button1 = new JButton("Spelling game");
add(button1);
HandlerClass handler = new HandlerClass();
button1.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
String answer1 = JOptionPane.showInputDialog("recipracate, reciprocate, reciprokate");
if ("reciprocate".equals(answer1)) {
JOptionPane.showMessageDialog(null, "recriprocate is the correct answer");
}
else {
JOptionPane.showMessageDialog(null, answer1 + " is the wrong answer");
}
String answer2 = JOptionPane.showInputDialog("quintessence, quintessance, qwintessence");
if ("quintessence".equals(answer2)) {
JOptionPane.showMessageDialog(null, "quintessence is the correct answer");
}
else {
JOptionPane.showMessageDialog(null, answer2 + " is the wrong answer");
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Spelling test = new Spelling();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
});
}
}
a basic problem that i can't figure out, tried a lot of things and can't get it to work, i need to be able to get the value/text of the variable
String input;
so that i can use it again in a different class in order to do an if statement based upon the result
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class pInterface extends JFrame {
String input;
private JTextField item1;
public pInterface() {
super("PAnnalyser");
setLayout(new FlowLayout());
item1 = new JTextField("enter text here", 10);
add(item1);
myhandler handler = new myhandler();
item1.addActionListener(handler);
System.out.println();
}
public class myhandler implements ActionListener {
// class that is going to handle the events
public void actionPerformed(ActionEvent event) {
// set the variable equal to empty
if (event.getSource() == item1)// find value in box number 1
input = String.format("%s", event.getActionCommand());
}
public String userValue(String input) {
return input;
}
}
}
You could display the window as a modal JDialog, not a JFrame and place the obtained String into a private field that can be accessed via a getter method. Then the calling code can easily obtain the String and use it. Note that there's no need for a separate String field, which you've called "input", since we can easily and simply extract a String directly from the JTextField (in our "getter" method).
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TestPInterface {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JFrame frame = new JFrame("TestPInterface");
// JDialog to hold our JPanel
final JDialog pInterestDialog = new JDialog(frame, "PInterest",
ModalityType.APPLICATION_MODAL);
final MyPInterface myPInterface = new MyPInterface();
// add JPanel to dialog
pInterestDialog.add(myPInterface);
pInterestDialog.pack();
pInterestDialog.setLocationByPlatform(true);
final JTextField textField = new JTextField(10);
textField.setEditable(false);
textField.setFocusable(false);
JPanel mainPanel = new JPanel();
mainPanel.add(textField);
mainPanel.add(new JButton(new AbstractAction("Get Input") {
#Override
public void actionPerformed(ActionEvent e) {
// show dialog
pInterestDialog.setVisible(true);
// dialog has returned, and so now extract Text
textField.setText(myPInterface.getText());
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// by making the class a JPanel, you can put it anywhere you want
// in a JFrame, a JDialog, a JOptionPane, another JPanel
#SuppressWarnings("serial")
class MyPInterface extends JPanel {
// no need for a String field since we can
// get our Strings directly from the JTextField
private JTextField textField = new JTextField(10);
public MyPInterface() {
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
add(new JLabel("Enter Text Here:"));
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = (Window) SwingUtilities.getWindowAncestor(MyPInterface.this);
win.dispose();
}
});
}
public String getText() {
return textField.getText();
}
}
A Good way of doing this is use Callback mechanism.
I have already posted an answer in the same context.
Please find it here JFrame in separate class, what about the ActionListener?.
Your method is a bit confusing:
public String userValue(String input) {
return input;
}
I guess you want to do something like this:
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
Also your JFrame is not visible yet. Set the visibility like this setVisible(true)
I have created buttons 1-9 as well as 4 text fields. I am trying to allow the user to click on any number 1-9 to input into each text field. However, I cannot determine which field the user is clicked on. Currently the 1-9 buttons only input text to the amt text field. How can I check which field is clicked and enter input into there?
New Question
public void actionPerformed(ActionEvent e) {
String iamt, ii, iterm,ipay;
iamt = amt.getText();
ii = interest.getText();
iterm = term.getText();
ipay = payment.getText();
Is there a way to shorten this if statement so I do not have redundant code for buttons 1-10?
if(e.getSource()==btn1) {
if(previouslyFocusedTextBox.equals(amt)){
amt.setText("1");
amt_number+=amt.getText();
amt.setText(amt_number);
}
else if (previouslyFocusedTextBox.equals(interest)){
interest.setText("1");
int_number+=interest.getText();
interest.setText(int_number);
}
else if (previouslyFocusedTextBox.equals(term)){
term.setText("1");
t_number+=term.getText();
term.setText(t_number);
}
else if (previouslyFocusedTextBox.equals(payment)){
payment.setText("1");
p_number+=payment.getText();
payment.setText(p_number);
}
}
if(e.getSource()==btnPay){
Loan = new LoanforCalc(Double.parseDouble(iamt),Double.parseDouble(ii),Integer.parseInt(iterm));
payment.setText(Double.toString(Loan.getPayment()));
}
I figured out what the OP meant, and made a quick solution:
Essentially, the textboxes lose focus as soon as the button is clicked, so we have to keep track of what had the focus before.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.FileNotFoundException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class FocusAwareWindow extends JFrame implements ActionListener, FocusListener {
public static void main(String[] args) throws FileNotFoundException {
FocusAwareWindow c = new FocusAwareWindow();
}
private JTextField textFieldA, textFieldB;
private JButton buttonA, buttonB;
private JTextField previouslyFocusedTextBox = textFieldA;
public FocusAwareWindow(){
super();
this.setLayout(new FlowLayout());
textFieldA = new JTextField();
textFieldA.setText("Field A");
textFieldA.setFocusable(true);
textFieldA.addFocusListener(this);
this.add(textFieldA);
textFieldB = new JTextField();
textFieldB.setText("Field B");
textFieldB.setFocusable(true);
textFieldB.addFocusListener(this);
this.add(textFieldB);
buttonA = new JButton("Which is focused?");
buttonA.addActionListener(this);
this.add(buttonA);
this.pack();
this.setVisible(true);;
}
public void actionPerformed(ActionEvent ev) {
if(previouslyFocusedTextBox.equals(textFieldA)){
System.out.println("Text Field A");
} else if(previouslyFocusedTextBox.equals(textFieldB)){
System.out.println("Text Field B");
}
}
public void focusGained(FocusEvent ev) {
if(ev.getSource() instanceof JTextField) {
previouslyFocusedTextBox = (JTextField) ev.getSource();
}
}
public void focusLost(FocusEvent ev) {
}
}
Maybe add a mouseListener and create areas over the textFields? Just guessing here but it might work. If this is possible then all you need is a variable to keep track of which area you clicked on and then check the variable for the textField you want.
I'm trying to create a hangman program. The phrase they have to guess is "bad hair day", and they see "* * **". When the user inputs a character nothing changes. I'm not 100% sure were I am going wrong but maybe it's in the passwordlabel2 or somewhere in the loop.
Demo Class
public class SecretPhrase {
int wrong = 0; //ignore for now
String phrase = "Bad hair day"; //hidden, what the user has to guess
String hiddenPhrase = "*** **** ***"; //what the user originally sees
public void changeLetter(char input)
{
StringBuilder checker = new StringBuilder(input);
StringBuilder(hiddenPhrase);
boolean wrongGuess = true;
for (int i=0; i<phrase.length(); i++)
{
if (phrase.charAt(i) == input){
checker.setCharAt(i, input);
wrongGuess = false;
}
}
hiddenPhrase = checker.toString();
if (wrongGuess){
wrong++;
}
}
private void StringBuilder(String hiddenPhrase) {
// TODO Auto-generated method stub
}
}
UI Class
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class SecretPhraseUI extends JApplet implements ActionListener {
SecretPhrase phrase = new SecretPhrase();
JLabel passwordLabel = new JLabel("Enter a letter to guess the phrase." ); //sets label to display message
JLabel passwordLabel2 = new JLabel( phrase.hiddenPhrase ); //sets label to display message
JTextField inputBox = new JTextField(40); //sets text field
JButton runButton = new JButton("Run"); //button that starts program
Container con = getContentPane(); //gets container
public void init()
{
con.setLayout(new FlowLayout());//sets flowlayout
con.add(new JLabel()); //jlabel container
con.add(inputBox); //input box container
con.add(runButton); //run button container
con.add(passwordLabel); //password label container
con.add(passwordLabel2); //password label container
runButton.addActionListener(this);//looks to see if run is clicked
inputBox.addActionListener(this);//looks to see if input box is used
}
public void actionPerformed(ActionEvent e)
{
String userInput = inputBox.getText(); //gets input from user
}
}
You have to make label.setText("The text you want to be displayed after action") . So when you do check the char, then do passwordLabel2.setText(phrase.hiddenPhrase) if the char is guessed right. :)
Working example
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class SecretPhraseUI
extends JApplet
implements ActionListener {
SecretPhrase phrase = new SecretPhrase();
JLabel passwordLabel = new JLabel("Enter a letter to guess the phrase."); //sets label to display message
JLabel passwordLabel2 = new JLabel(
phrase.hiddenPhrase ); //sets label to display message
JTextField inputBox = new JTextField(40); //sets text field
JButton runButton = new JButton("Run"); //button that starts program
Container con = getContentPane(); //gets container
public void init() {
con.setLayout(new FlowLayout());//sets flowlayout
con.add(new JLabel()); //jlabel container
con.add(inputBox); //input box container
con.add(runButton); //run button container
con.add(passwordLabel); //password label container
con.add(passwordLabel2); //password label container
runButton.addActionListener(this);//looks to see if run is clicked
inputBox.addActionListener(this);//looks to see if input box is used
}
public void actionPerformed(ActionEvent e) {
if (!inputBox.getText().isEmpty()) {
phrase.changeLetter(
inputBox.getText().charAt(0)); //gets input from user
passwordLabel2.setText(phrase.hiddenPhrase);
}
}
}
public class SecretPhrase {
int wrong = 0; //ignore for now
String phrase = "Bad hair day"; //hidden, what the user has to guess
String hiddenPhrase = "*** **** ***"; //what the user originally sees
public void changeLetter(char input) {
StringBuilder checker = new StringBuilder(hiddenPhrase);
boolean wrongGuess = true;
for (int i=0; i<phrase.length(); i++) {
if (phrase.charAt(i) == input){
checker.setCharAt(i, input);
wrongGuess = false;
}
}
hiddenPhrase = checker.toString();
if (wrongGuess){
wrong++;
}
}
}
It doesn't look like you've done anything with the user input. You could do something with the user input. Append the user input to another String and use the setText method of a label to update a label with the user input.