Focus on Keylistener - java

So what I've got is that I would love to try and make an little login applet. I'm using Java Windowsbuilder for it, to make it easyer for me. I hope the code isn't to messy, because I'm just a starter.
The problem I've got is that My JButton "login" only registers a keyevent when it's selected trought tab, or when you first click it. What I want is that I can use the button always just by pressing the "ENTER" key.
Hope you guys solve my problem :)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import java.awt.event.KeyAdapter;
public class nummer1 extends JFrame{
private JPanel contentPane;
public static nummer1 theFrame;
private JTextField textFieldUsername;
private JTextField textFieldPass;
private nummer1 me;
private JLabel lblCheck;
private String password = "test", username = "test";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nummer1 frame = new nummer1();
nummer1.theFrame = frame;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void Check(){
String Pass = textFieldPass.getText();
String Username = textFieldUsername.getText();
System.out.println(Pass);
if (Pass.equals(password) && Username.equals(username)){
lblCheck.setText("Correct Login");
}else{
lblCheck.setText("Invalid username or password");
}
}
/**
* Create the frame.
*/
public nummer1() {
me = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 356, 129);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 61, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 61, 14);
contentPane.add(lblPassword);
textFieldUsername = new JTextField();
textFieldUsername.setBounds(81, 8, 107, 20);
contentPane.add(textFieldUsername);
textFieldUsername.setColumns(10);
me.textFieldUsername = textFieldUsername;
textFieldPass = new JTextField();
textFieldPass.setBounds(81, 33, 107, 20);
contentPane.add(textFieldPass);
textFieldPass.setColumns(10);
me.textFieldPass = textFieldPass;
JButton btnLogin = new JButton("Login");
contentPane.requestFocusInWindow();
btnLogin.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
me.Check();
System.out.println("hi");
}
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
me.Check();
}
});
btnLogin.setBounds(198, 7, 89, 23);
contentPane.add(btnLogin);
JLabel lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.TRAILING);
lblCheck.setBounds(10, 65, 264, 14);
contentPane.add(lblCheck);
me.lblCheck = lblCheck;
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new
Component[]{lblUsername, lblPassword, textFieldUsername, textFieldPass, btnLogin, lblCheck}));
}
}
Thanks Emil!

What I want is that I can use the button always just by pressing the "ENTER" key
Sounds like you want to make the "login" button the default button for the dialog.
See Enter Key and Button for the problem and solution.

When using panels KeyListeners won't work unless the panel is focusable. What you can do is make a KeyBinding to the ENTER key using the InputMap and ActionMap for your panel.
public class Sample extends JPanel{
//Code
Sample() {
//More code
this.getInputMap().put(KeyStroke.getKeyStroke((char)KeyEvent.VK_ENTER), "Enter" );
this.getActionMap().put("Enter", new EnterAction());
}
private class EnterAction extends AbstractAction(){
#Override
public void ActionPerformed(ActionEvent e){
//Acion
}
}
}

Related

JTextField setText()

I was making a GUI to reverse an input string, I am taking input from the first textfield, then reversing the string using my function strRev() then trying to produce the result on the second textfield. But am not getting any output on 2nd textfield.
package com.awt;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.InputMethodEvent;
public class Buttons{
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Buttons window = new Buttons();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Buttons() {
initialize();
}
public String strRev(String s) {
char a;
String ans="";
for(int i=0;i<s.length();i++) {
a=s.charAt(i);
ans=a+ans;
}
return ans;
}
private void initialize() {
frame = new JFrame("Label Demo");
frame.setBounds(150, 200, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
textField = new JTextField();
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton okButton = new JButton("Reverse");
frame.getContentPane().add(okButton);
textField_1 = new JTextField();
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
String str=textField.getText();
final String ans=strRev(str);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField_1.setText(ans);
}
});
}
}
The GUI looks like this:-
Please let me know my mistake, Thanks
You need to read the contents of textField only when the user clicks on the Reverse button. At the moment, you read the contents when the GUI loads at which time there is nothing in the textField. So calling a reverse on empty string is going to give you an empty string and that is what you see in your textField_1. Move the code where you read the textField into your addActionListener.
private void initialize() {
frame = new JFrame("Label Demo");
frame.setBounds(150, 200, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
textField = new JTextField();
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton okButton = new JButton("Reverse");
frame.getContentPane().add(okButton);
textField_1 = new JTextField();
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// THIS BLOCK IS RUN EVERYTIME THE BUTTON IS CLICKED!
// Read the contents of textField
String str=textField.getText();
// Reverse the string you just read
final String ans=strRev(str);
// Set the answer on the other textField.
textField_1.setText(ans);
}
});
}

Invoke a serie of actions when Enter key is pressed

I have one Swing project and I have an action listener on JTextField for Tab key as follows.
There is a JOptionPane.showMessageDialog() inside the action listener. And when Tab is pressed option pane will show an Information message.
My problem is that, when I press Enter on OK button of Information Message dialog, a serie of action is invoked viz Tab action of JTextField and Enter action of btnNewButton.
If I use mouse click on OK button of Error Message dialog, every thing is fine and no problem.
Can I solve this using key bindings instead of key listener?
Please suggest a solution
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnNewButton;
private JDialog dialog;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
contentPane.setLayout(null);
textField = new JTextField();
textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.emptySet());
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
JOptionPane.showMessageDialog(dialog, " Please Press ENTER Key", "information",
JOptionPane.INFORMATION_MESSAGE);
btnNewButton.grabFocus();
}
}
});
textField.setBounds(73, 28, 178, 28);
contentPane.add(textField);
textField.setColumns(10);
btnNewButton = new JButton("New button");
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(dialog, " That Invoked New Button Also", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(223, 137, 117, 25);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("Please Press TAB Key");
lblNewLabel.setBounds(83, 55, 183, 15);
contentPane.add(lblNewLabel);
dialog = new JDialog();
dialog.setAlwaysOnTop(true);
}
}
The problem is that you are overriding method keyReleased(). The JOptionPane is closing before the keyReleased() method is called and since you make btnNewButton the focused component after the JOptionPane is closed, the keyReleased() method is invoked – which displays the other JOptionPane.
Simply rename the method to keyPressed().
Also, you don't need the dialog member. The first parameter to JOptionPane#showMessageDialog should be the JFrame.
Here is your code with my corrections.
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
contentPane.setLayout(null);
textField = new JTextField();
textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.emptySet());
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
JOptionPane.showMessageDialog(Test.this, " Please Press ENTER Key", "information",
JOptionPane.INFORMATION_MESSAGE);
btnNewButton.grabFocus();
}
}
});
textField.setBounds(73, 28, 178, 28);
contentPane.add(textField);
textField.setColumns(10);
btnNewButton = new JButton("New button");
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(Test.this, " That Invoked New Button Also", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(223, 137, 117, 25);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("Please Press TAB Key");
lblNewLabel.setBounds(83, 55, 183, 15);
contentPane.add(lblNewLabel);
}
}
Note that (at least in JDK 15) there is no need to explicitly set the default close operation for JFrame since the default is EXIT_ON_CLOSE

Passing info from one Jframe to another

I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.

Loop to beginning with JFrame, accessing method in different class

So I'm revising a random number generator I made a while back and instead of making it in JOptionPane, I decided to try to create it in JFrame. The 2 problems I'm having is:
I can't figure out how to access the number of attempts in class "Easy" to use for class "PlayAgain".
How could I loop back to the beginning of the program and start at the Menu screen again if they decide to click btnPlayAgain? Creating a new instance of Menu does not work the way I want it to, as the Menu frame doesn't close after you choose a difficulty.
The code is for the 3 classes, Menu, Easy, and PlayAgain. I didn't include the code for buttons Medium or Hard as it is pretty much identical to Easy.
Menu
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Menu extends JFrame {
private JPanel contentPane;
public static Menu frame;
public static Easy eFrame;
public static Medium mFrame;
public static Hard hFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Menu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Menu() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 149);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSelectADifficulty = new JLabel("Select a difficulty");
lblSelectADifficulty.setBounds(10, 49, 424, 19);
lblSelectADifficulty.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblSelectADifficulty.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblSelectADifficulty);
JLabel lblRandomNumberGuessing = new JLabel("Random Number Guessing Game");
lblRandomNumberGuessing.setHorizontalAlignment(SwingConstants.CENTER);
lblRandomNumberGuessing.setFont(new Font("Tahoma", Font.PLAIN, 22));
lblRandomNumberGuessing.setBounds(10, 11, 424, 27);
contentPane.add(lblRandomNumberGuessing);
JButton btnEasy = new JButton("Easy (0-100)");
btnEasy.setBounds(10, 79, 134, 23);
contentPane.add(btnEasy);
JButton btnMedium = new JButton("Medium (0-1000)");
btnMedium.setBounds(155, 79, 134, 23);
contentPane.add(btnMedium);
JButton btnHard = new JButton("Hard (0-10000)");
btnHard.setBounds(300, 79, 134, 23);
contentPane.add(btnHard);
btnEasy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
eFrame = new Easy();
eFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
}
}
Easy
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Easy extends JFrame {
private JPanel contentPane;
private JTextField textField;
private int rand;
public int attempts;
public Easy() {
attempts = 1;
Random rnd = new Random();
rand = rnd.nextInt(100 + 1);
setResizable(false);
setTitle("Take a guess");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 135);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblGuessANumber = new JLabel("Guess a number between 0 - 100");
lblGuessANumber.setBounds(10, 11, 274, 19);
lblGuessANumber.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblGuessANumber.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblGuessANumber);
textField = new JTextField();
textField.setBounds(20, 41, 110, 20);
contentPane.add(textField);
textField.setColumns(10);
final JButton btnGuess = new JButton("Guess");
btnGuess.setBounds(164, 41, 110, 20);
contentPane.add(btnGuess);
final JLabel label = new JLabel("");
label.setFont(new Font("Tahoma", Font.PLAIN, 12));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(10, 72, 274, 24);
contentPane.add(label);
btnGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if((Integer.parseInt(textField.getText())) >= 0 && (Integer.parseInt(textField.getText())) <= 100){
if((Integer.parseInt(textField.getText())) < rand){
label.setText("You guessed too low.");
System.out.println(rand);
attempts++;
}
else if((Integer.parseInt(textField.getText())) > rand){
label.setText("You guessed too high.");
attempts++;
}
else if((Integer.parseInt(textField.getText())) == rand){
dispose();
PlayAgain pl = new PlayAgain();
pl.setVisible(true);
}
}
else
label.setText("Please enter a valid input.");
}
});
}
public int returnAttempts(){
return attempts;
}
}
PlayAgain
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class PlayAgain extends JFrame {
private JPanel contentPane;
public PlayAgain() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 240, 110);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPlayAgain = new JLabel("Play Again?");
lblPlayAgain.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPlayAgain.setHorizontalAlignment(SwingConstants.CENTER);
lblPlayAgain.setBounds(10, 27, 214, 23);
contentPane.add(lblPlayAgain);
JButton btnYes = new JButton("Yes");
btnYes.setBounds(10, 49, 89, 23);
contentPane.add(btnYes);
JButton btnQuit = new JButton("Quit");
btnQuit.setBounds(135, 49, 89, 23);
contentPane.add(btnQuit);
//Need to return number of attempts from Easy.java in lblYouGuessedCorrectly
JLabel lblYouGuessedCorrectly = new JLabel("You guessed correctly! Attempts: ");
lblYouGuessedCorrectly.setHorizontalAlignment(SwingConstants.CENTER);
lblYouGuessedCorrectly.setBounds(10, 11, 214, 14);
contentPane.add(lblYouGuessedCorrectly);
btnYes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Need to start the program over again, starting with from the Menu screen
}
});
btnQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
Suggestions:
You're creating an event-driven Swing GUI, and so you won't "loop" back to the beginning of your program as you would in a linear console program, because that's not how event driven programs work. Rather you'd simply display the menu view when needed, usually in response to some event such as within the ActionListener of a JButton and/or JMenuItem.
So add a reset JButton or JMenuItem or both, have them share the same ResetAction AbstractAction, and inside of that Action, re-show the menu view.
Side recommendation 1 (not related to your main problem): Don't use null layouts or setBounds as that will lead to rigid hard to debug and enhance GUI's that look good on one platform only.
Side recommendation 2: Don't code towards creation of JFrames but rather JPanel views as this will increase the flexibility of your program greatly, allowing you to swap JPanel views if need be using a CardLayout, or displaying views within a JFrame or JDialog or anywhere else they're needed.
For example using a CardLayout to swap JPanel views and a JOptionPane to get user input on re-starting:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class Main2 extends JPanel {
private MenuPanel menuPanel = new MenuPanel(this);
private GamePanel gamePanel = new GamePanel(this);
private CardLayout cardLayout = new CardLayout();
public Main2() {
setLayout(cardLayout);
add(menuPanel, MenuPanel.NAME);
add(gamePanel, GamePanel.NAME);
}
public void setDifficulty(Difficulty difficulty) {
gamePanel.setDifficulty(difficulty);
}
public void showCard(String name) {
cardLayout.show(Main2.this, name);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Main2());
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 MenuPanel extends JPanel {
public static final String NAME = "menu panel";
private static final String MAIN_TITLE = "Random Number Guessing Game";
private static final String SUB_TITLE = "Select a difficulty";
private static final int GAP = 3;
private static final float TITLE_SIZE = 20f;
private static final float SUB_TITLE_SIZE = 16;
private Main2 main2;
public MenuPanel(Main2 main2) {
this.main2 = main2;
JLabel titleLabel = new JLabel(MAIN_TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_SIZE));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel);
JLabel subTitleLabel = new JLabel(SUB_TITLE, SwingConstants.CENTER);
subTitleLabel.setFont(subTitleLabel.getFont().deriveFont(Font.PLAIN, SUB_TITLE_SIZE));
JPanel subTitlePanel = new JPanel();
subTitlePanel.add(subTitleLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
for (Difficulty difficulty : Difficulty.values()) {
buttonPanel.add(new JButton(new DifficultyAction(difficulty)));
}
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(titlePanel);
add(subTitlePanel);
add(buttonPanel);
}
private class DifficultyAction extends AbstractAction {
private Difficulty difficulty;
public DifficultyAction(Difficulty difficulty) {
this.difficulty = difficulty;
String name = String.format("%s (0-%d)", difficulty.getText(), difficulty.getMaxValue());
putValue(NAME, name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
main2.setDifficulty(difficulty);
main2.showCard(GamePanel.NAME);
}
}
}
enum Difficulty {
EASY("Easy", 100), MEDIUM("Medium", 1000), HARD("Hard", 10000);
private String text;
private int maxValue;
private Difficulty(String text, int maxValue) {
this.text = text;
this.maxValue = maxValue;
}
public String getText() {
return text;
}
public int getMaxValue() {
return maxValue;
}
}
#SuppressWarnings("serial")
class GamePanel extends JPanel {
public static final String NAME = "game panel";
private String labelText = "Guess a number between 0 - ";
private JLabel label = new JLabel(labelText + Difficulty.HARD.getMaxValue(), SwingConstants.CENTER);
private Main2 main2;
GuessAction guessAction = new GuessAction("Guess");
private JTextField textField = new JTextField(10);
private JButton guessButton = new JButton(guessAction);
private boolean guessCorrect = false;
private Difficulty difficulty;
public GamePanel(Main2 main2) {
this.main2 = main2;
textField.setAction(guessAction);
JPanel guessPanel = new JPanel();
guessPanel.add(textField);
guessPanel.add(Box.createHorizontalStrut(10));
guessPanel.add(guessButton);
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(guessPanel);
setLayout(new BorderLayout());
add(label, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
public void setDifficulty(Difficulty difficulty) {
this.difficulty = difficulty;
label.setText(labelText + difficulty.getMaxValue());
}
private class GuessAction extends AbstractAction {
private int attempts = 1;
public GuessAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO use difficulty and all to check guesses, and reply to user
// we'll just show the go back to main menu dialog
guessCorrect = true; // TODO: Delete this later
if (guessCorrect) {
String message = "Attempts: " + attempts + ". Play Again?";
String title = "You've Guessed Correctly!";
int optionType = JOptionPane.YES_NO_OPTION;
int selection = JOptionPane.showConfirmDialog(GamePanel.this, message, title, optionType);
if (selection == JOptionPane.YES_OPTION) {
textField.setText("");
main2.showCard(MenuPanel.NAME);
} else {
Window window = SwingUtilities.getWindowAncestor(GamePanel.this);
window.dispose();
}
}
}
}
}

Eclipse Java 8 Error: Label cannot be resolved

I am trying to program an 'Inch-to-Centimeter Calculator'. I've got a problem with the method umrechnen(). The label lblCenti cannot be resolved. My Code is equal to the Solutioncode. I am grateful for every answer or tip I get.
I don't know what I should add to my Description, but StackOverflow forces me to write more, so I'm writing this.
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class ZollZentimeter extends JFrame {
private JPanel contentPane;
private JTextField tfInch;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ZollZentimeter frame = new ZollZentimeter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ZollZentimeter() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 359, 157);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnCalculate = new JButton("Umrechnen");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
umrechnen();
}
});
btnCalculate.setBounds(12, 77, 116, 25);
contentPane.add(btnCalculate);
JButton btnEnde = new JButton("Ende");
btnEnde.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnEnde.setBounds(214, 77, 116, 25);
contentPane.add(btnEnde);
JLabel lblZoll = new JLabel("Zoll");
lblZoll.setBounds(12, 13, 56, 16);
contentPane.add(lblZoll);
tfInch = new JTextField();
tfInch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER){
umrechnen();
}
}
});
JLabel lblCenti = new JLabel("");
lblCenti.setBounds(214, 42, 116, 22);
contentPane.add(lblCenti);
tfInch.setBounds(12, 42, 116, 22);
contentPane.add(tfInch);
tfInch.setColumns(10);
}
private void umrechnen(){
DecimalFormat f=new DecimalFormat("#0.00");
double z, cm;
z=Double.parseDouble(tfInch.getText());
cm=z*2.54;
lblCenti.setText(f.format(cm+" cm"));
tfInch.requestFocus();
tfInch.selectAll();
}
}
JLabel lblCenti = new JLabel("");
"lblCenti" is defined as a local variable so it can only be accessible in the method/constructor where you define it.
It you want to access the label in another method you need to define it as an instance variable, the same way you do with the "tfInch" variable.

Categories

Resources