this button does nothing what would be the mistake?
its a login, I dont know why it doesnt work seems pretty well, could somebody help me to indentify the issue?.....................................................................................................................
package Operaciones_Logicas;
import Mainargs.FirstClass;
import java.awt.event.*;
import javax.swing.*;
public class Main1 extends JFrame implements ActionListener {
private JLabel usuario;
private JLabel contraseña;
public JButton blogin;
public JTextField jtusuario, jtcontra;
public static String susuario = "", scontra = "";
public Main1() {
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Cajero Automatico");
JLabel usuario = new JLabel();
usuario.setVisible(true);
usuario.setBounds(20, 100, 100, 50);
add(usuario);
JLabel contraseña = new JLabel();
contraseña.setBounds(20, 300, 100, 50);
add(contraseña);
JButton blogin = new JButton("Login");
blogin.setBounds(50, 400, 100, 30);
blogin.addActionListener(this);
add(blogin);
JTextField jtusuario = new JTextField();
jtusuario.setBounds(20, 120, 150, 30);
add(jtusuario);
JTextField jtcontra = new JTextField();
jtcontra.setBounds(20, 150, 150, 30);
add(jtcontra);
}
//control para el login
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == blogin) {
susuario = jtusuario.getText();
scontra = jtcontra.getText();
if (susuario.equals("josmart96") && (scontra.equals("rojo2000"))) {
FirstClass secondwindow = new FirstClass();
secondwindow.setBounds(0, 0, 600, 360);
secondwindow.setVisible(true);
secondwindow.setResizable(false);
secondwindow.setLocationRelativeTo(null);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "Usuario y/o Contraseña
incorrectas");
}
}
}
public static void main(String[] args) {
Main1 firstwindow = new Main1();
firstwindow.setBounds(0, 0, 360, 600);
firstwindow.setVisible(true);
firstwindow.setResizable(false);
firstwindow.setLocationRelativeTo(null);
}
}
no erros just doesnt work, when hit button does nothing I can compile it and everything is good I think it could be the IDE itself
You are using local variable blogin instead of using instance variable blogin
Inside the contructor, change
JButton blogin = new JButton("Login");
to
blogin = new JButton("Login");
you also need to use other declared instance variables rather than declaring local variables inside the constructor
Related
Im developing an little "clicker" but, if i press the button, and i should get 1+ Score, it dont work! Is there any way to reload or anything else?
Heres my code: (ClickEvent)
public class event implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("PRESS");
game.timesClicked.add(1);
points.setText(game.seePoints);
}
}
And there is my JFrame:
public class game extends JFrame
{
public static JButton buttonStart;
JButton buttonCredits;
JButton buttonBack;
JButton buttonLeave;
public static JFrame panel = new game();
public static ArrayList<Integer> timesClicked = new ArrayList<Integer>();
public static JLabel label1;
public static JLabel points;
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
public game()
{
setLayout(null);
label1 = new JLabel("ButtonClicker");
points = new JLabel(seePoints);
points.setFont(new Font("Tahoma", Font.BOLD, 15));
points.setBounds(0, 0, 200, 200);
label1.setFont(new Font("Tahoma", Font.BOLD, 50));
label1.setBounds(315, 50, 500, 200);
event e1 = new event();
JButton b = new JButton("KNOPF");
b.setBackground(new Color(96, 140, 247));
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
b.setFont(new Font("Tahoma", Font.BOLD, 15));
b.setBounds( 402, 380, 180, 50 );
b.addActionListener(e1);
add(b);
add(label1);
add(points);
}
}
(Sorry For My Bad English)
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
This is only being called once at the start of your program. When you add to timesClicked, it does not recalculate seePoints.
You will need to set this variable to the correct value every time you click.
This is my first post!
I'm trying to implement the combo box made in the TutCombo program into the ExamGradesGUI + ExamGrades one. As you can see in the TutCombo program, there is the 'String subjectUnitTxt'. Ideally, I would like this to replace the 'subjectUnitTxt' in the ExamGradesGUI program, but having the functionality of the combo box and being able to be saved to the file along with firstName, lastName and examMark. If someone could tell me how to do this, that would be great. Sorry if I have added too much code. Thanks
I got this to work by making some minor changes in your code (see attached code). Search for "unitCombo".
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ExamGradesGUI {
public static void main(String[] args) {
new ExamGradesGUI();
}
String[] firstName = new String[20];
String[] lastName = new String[20];
String[] subjectUnit = new String[20];
double[] examMark = new double[20];
private JLabel firstNameLbl, lastNameLbl, unitLbl, markLbl;
private JTextField firstNameTxt, lastNameTxt, subjectUnitTxt, examMarkTxt;
private JComboBox<String> unitCombo;
private JButton btnClear, btnSave, btnOpen, btnExit;
private JPanel panel;
private JFrame frame;
public ExamGradesGUI(){
buildFrame();
buildFields();
buildButtons();
frame.setVisible(true);
frame.add(panel);
}
public void buildFrame(){
frame = new JFrame("GradeEnter");
frame.setSize(650,450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.white);
}
public void buildFields(){
// Labels, User Input + Location
firstNameTxt = new JTextField(10);
firstNameTxt.setBounds(180, 80, 150, 20);
panel.add(firstNameTxt);
String str = firstNameTxt.getText();
if(str.matches("[-a-zA-Z]*"))
{
}
else
{
JOptionPane.showMessageDialog(null, "Please enter amount donating");
}
lastNameTxt = new JTextField(10);
lastNameTxt.setBounds(180, 110, 150, 20);
panel.add(lastNameTxt);
subjectUnitTxt = new JTextField(10);
String[] courses = {"Computing","Forensic","Business"};
unitCombo = new JComboBox<String>(courses);
//subjectUnitTxt.setBounds(180, 140, 150, 20);
//panel.add(subjectUnitTxt);
unitCombo.setBounds(180, 140, 150, 20);
panel.add(unitCombo);
// IF HAVE TIME: Turn Combo Box into GUI - Refer to testgui.java
examMarkTxt = new JTextField(10);
examMarkTxt.setBounds(180, 170, 150, 20);
panel.add(examMarkTxt);
firstNameLbl = new JLabel("First Name:");
firstNameLbl.setBounds(70, 80, 100, 20);
panel.add (firstNameLbl);
lastNameLbl = new JLabel("Last Name:");
lastNameLbl.setBounds(70, 110, 100, 20);
panel.add (lastNameLbl);
unitLbl = new JLabel("Unit:");
unitLbl.setBounds(70, 140, 100, 20);
panel.add (unitLbl);
markLbl = new JLabel("Mark:");
markLbl.setBounds(70, 170, 100, 20);
panel.add (markLbl);
}
public void buildButtons() {
btnClear = new JButton ("Reset Fields");
btnClear.setBounds(55, 220, 110, 20);
btnClear.addActionListener(new ClearButtonListener());
panel.add (btnClear);
btnSave = new JButton ("Save");
btnSave.setBounds(155, 220, 70, 20);
btnSave.addActionListener(new SaveButton());
panel.add (btnSave);
btnOpen = new JButton ("Open 'GradeEnter.txt' ");
btnOpen.setBounds(90, 250, 200, 20);
btnOpen.addActionListener(new OpenButton());
panel.add (btnOpen);
btnExit = new JButton ("Exit");
btnExit.setBounds(255, 220, 70, 20);
btnExit.addActionListener(new ExitButton());
panel.add (btnExit);
}
public void setText() {
firstNameTxt.setText("");
lastNameTxt.setText("");
subjectUnitTxt.setText("");
examMarkTxt.setText("");
}
public void getText() {
int i = 0;
i++;
firstName[i] = firstNameTxt.getText();
lastName[i] = lastNameTxt.getText();
subjectUnit[i] = unitCombo.getItemAt(unitCombo.getSelectedIndex());
examMark[i] = Double.parseDouble(examMarkTxt.getText());
}
private class ClearButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
setText();
}
}
private class SaveButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
getText();
setText();
ExamGrades save = new ExamGrades();
save.fileOpen();
save.addRecords(firstName, lastName, subjectUnit, examMark);
JOptionPane.showMessageDialog(null, "Entry Saved!");
save.fileClose();
}
}
private class OpenButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
JOptionPane.showMessageDialog(null, "'GradeEnter.txt' opening in Java!");
Thread.sleep(2); // Adds a 2 second delay so user can read dialog message
Runtime.getRuntime().exec("eclipse GradeEnter.txt" );
} catch (Exception NoFileFound) {
System.out.println("Couldn't open or find the file.");
}
}
}
class ExitButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
I almost have this code working. I can launch the GUI, however, when I press any of the buttons, I get the following error message:
The type TextFieldDemo must implement the inherited abstract method ActionListener
I have looked around online and can't see any issues with the code. Can someone help me please?
Thanks :)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TextFieldDemo implements ActionListener{
private JLabel lblName, lblAddress, lblPhone;
private JTextField txtName, txtAddress, txtPhone;
private JButton btnUpper, btnLower, btnExit;
private JPanel panel;
private JFrame frame;
public static void main(String[] args){
new TextFieldDemo();
}
public TextFieldDemo(){
createForm();
addFields();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createForm(){
frame = new JFrame();
frame.setTitle("Student Form");
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
}
public void addFields(){
txtName = new JTextField("Fred Bloggs");
txtName.setBounds(110, 50, 150, 20);
panel.add(txtName);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
panel.add (lblAddress);
txtAddress = new JTextField ("Ashley Road");
txtAddress.setBounds(110, 70, 150, 20);
panel.add (txtAddress);
lblPhone = new JLabel ("Phone Number");
lblPhone.setBounds(10, 90, 100, 20);
panel.add (lblPhone);
txtPhone= new JTextField("01202 191 3333");
txtPhone.setBounds(110, 90, 150, 20);
panel.add (txtPhone);
lblName = new JLabel("Student Name");
lblName.setBounds(10, 50, 100, 20);
panel.add(lblName);
}
public void addButtons(){
btnUpper = new JButton ("UpperCase");
btnUpper.setBounds(50, 200, 100, 20);
btnUpper.addActionListener(this);
panel.add (btnUpper);
btnLower = new JButton ("LowerCase");
btnLower.setBounds(150, 200, 100, 20);
btnLower.addActionListener(this);
panel.add (btnLower);
btnExit = new JButton ("Exit");
btnExit.setBounds(250, 200, 100, 20);
btnExit.addActionListener(this);
panel.add (btnExit);
}
class UpperCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toUpperCase());
txtAddress.setText(txtAddress.getText().toUpperCase());
}
class LowerCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toLowerCase());
txtAddress.setText(txtAddress.getText().toLowerCase());
}
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
}
}
You say TextFieldDemo implements ActionListener, but it doesn't have an actionPerformed() method, so it's not actually implementing the interface.
Either implement the method or don't claim it implements the interface.
I didn't think it would compile like you have it, but there you go!
The error should make you check the documentation of ActionListener to find out what method(s) is missing. Sometimes eclipse will prompt you to add stubs for the missing methods.
The documentation shows the interface ActionListener has one method to be implemented, actionPerformed();
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
Strange, the compiler should throw an error on this.
So I'm starting a new project and I was wondering how can I setup multiple classes for my different JPanels. It looks very messy in one class. Let me show you the example. I would like the JPanel for a menu screen in it's own class.
import java.awt.EventQueue;
public class TakeAwayLogin {
private JFrame frmTakeAwaySystem;
private JTextField textFieldId;
private JPasswordField passwordField;
/**
* Launch the application.
* #return
*/
public void login() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TakeAwayLogin window = new TakeAwayLogin();
window.frmTakeAwaySystem.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TakeAwayLogin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTakeAwaySystem = new JFrame();
frmTakeAwaySystem.setTitle("Take Away System Alpha");
frmTakeAwaySystem.setBounds(100, 100, 450, 300);
frmTakeAwaySystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTakeAwaySystem.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panelLogin = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelLogin, "name_254735117500687");
panelLogin.setLayout(null);
panelLogin.setVisible(true);
final JLabel lblIncorrect = new JLabel("Incorrect login, try again");
lblIncorrect.setHorizontalAlignment(SwingConstants.CENTER);
lblIncorrect.setFont(new Font("Tahoma", Font.PLAIN, 9));
lblIncorrect.setForeground(Color.RED);
lblIncorrect.setBounds(148, 74, 139, 14);
panelLogin.add(lblIncorrect);
lblIncorrect.setVisible(false);
final JPanel panelPassword = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPassword, "name_254738265432897");
panelPassword.setLayout(null);
passwordField = new JPasswordField();
passwordField.setBounds(112, 157, 205, 41);
panelLogin.add(passwordField);
passwordField.setHorizontalAlignment(JPasswordField.CENTER);
JButton btnNewButton = new JButton("Lock Application");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelPassword.setVisible(false);
panelLogin.setVisible(true);
passwordField.setText("");
textFieldId.disable();
}
});
btnNewButton.setBounds(135, 155, 172, 50);
panelPassword.add(btnNewButton);
panelPassword.setVisible(false);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String login = textFieldId.getText();
char[] pass = passwordField.getPassword();
String p = new String(pass);
String password = "pass";
if (login.equalsIgnoreCase("milan") && p.equals(password)) {
panelPassword.setVisible(true);
panelLogin.setVisible(false);
}else {
lblIncorrect.setVisible(true);
}
}
});
btnLogin.setBounds(160, 209, 97, 41);
panelLogin.add(btnLogin);
textFieldId = new JTextField();
textFieldId.setBounds(112, 88, 205, 43);
panelLogin.add(textFieldId);
textFieldId.setColumns(10);
textFieldId.setHorizontalAlignment(JTextField.CENTER);
JLabel lblId = new JLabel("Enter the business login:");
lblId.setHorizontalAlignment(SwingConstants.CENTER);
lblId.setBounds(112, 63, 205, 14);
panelLogin.add(lblId);
JLabel lblEnterYourPassword = new JLabel("Enter your password");
lblEnterYourPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterYourPassword.setBounds(148, 142, 139, 14);
panelLogin.add(lblEnterYourPassword);
JPanel panelPizza = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPizza, "name_254741096954780");
}
}
So help would be great.
Thanks very much.
I don't know why creating a second class would be necessary. If you just want the code to look less messy, then add comment separators between Panels or something to that effect. I think that splitting up the Panels into their own classes would be just cause you to have to write more calls to be able to create the same functionality. But if you must, then make a class within your initiate class and work from there.
Simplifying, you want something like:
public class MyMainJFrame extends JFrame{
private JPanel panel1 = new MyFooPanel();
private JPanel panel2 = new MyBarPanel();
public MyMainPanel(){
initialize();
}
void initialize(){
//init the JFrame
this.setTitle("Take Away System Alpha");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new CardLayout(0, 0));
//and add the panels
this.add(panel1);
this.add(panel2);
}
}
// a file for each one
public class MyFooPanel extends JPanel{
private JButton button;
//... add components and logic
}
public class MyBarPanel extends JPanel{
private JTextField field;
//... add components and logic
}
If you want to use specific methods for each custom panel, then change the type of variable for the same name of the custom class.
This is another problem that has come up after having solved my earlier question here:
How to use a variable created in class1, in another class?
The answer to the question above allows me to use a variable created in class 3 to be printed by calling a method in class 4, from class 4.
However, when I try to print that variable as part of an action listener, it prints out 'null' instead of whatever the user inputs in the JTexfield create_u1 (in class 3).
Updated for sajjadG: please try it yourself
class 1
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class class1 extends JFrame {
public static void main(String[] args) {
mainPage MP = new mainPage();
MP.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MP.setLocationRelativeTo(null);
MP.setSize(300,200);
MP.setVisible(true);
}
}
class 2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class mainPage extends JFrame {
create_account crAcc = new create_account();
change_username chU = new change_username();
change_password chPW = new change_password();
sign_in signIn = new sign_in();
private JButton create_account, change_username, change_password, signIn_button;
public mainPage(){
super("Password Programme");
setPreferredSize (new Dimension (400, 100));
setLayout (null);
create_account = new JButton("Create an Account");
add(create_account);
change_username = new JButton("Change Username");
add(change_username);
change_password = new JButton("Change Password");
add(change_password);
signIn_button = new JButton("Sign in and Access Files");
add(signIn_button);
create_account.setBounds (10, 20, 150, 20);
change_username.setBounds (10, 50, 150, 20);
change_password.setBounds (10, 80, 150, 20);
signIn_button.setBounds (10, 110, 200, 20);
HandlerClass handler = new HandlerClass();
create_account.addActionListener(handler);
change_username.addActionListener(handler);
change_password.addActionListener(handler);
signIn_button.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()==create_account) {
crAcc.setLocationRelativeTo(null);
crAcc.setSize(300,200);
crAcc.setVisible(true);
}
if(event.getSource()==change_username) {
chU.setLocationRelativeTo(null);
chU.setSize(300,200);
chU.setVisible(true);
}
if(event.getSource()==change_password) {
chPW.setLocationRelativeTo(null);
chPW.setSize(300,200);
chPW.setVisible(true);
}
if(event.getSource()==signIn_button) {
signIn.setLocationRelativeTo(null);
signIn.setSize(300,200);
signIn.setVisible(true);
}
}
}
}
class 3
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class create_account extends JFrame{
private String u1, pw1;
private JLabel cU1, cpw1, statusBar;
public JTextField create_u1;
public JPasswordField create_pw1;
private JButton change;
public String userName3, passWord3;
public void checkUserName(String u, String pw) {
System.out.println(u); ///// this prints it out correctly
System.out.println(pw);
if (create_u1.getText()==u){
System.out.println("correct");
}else { /// it tests incorrect even though i inputted same thing
System.out.println("incorrect");
System.out.println(create_u1.getText());
System.out.println(userName3); /// prints out null }
}
public create_account() {
super("Create Account");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Create a username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 110, 250, 30);
cU1 = new JLabel("Username");
cpw1 = new JLabel("Password");
create_u1 = new JTextField(10);
create_pw1 = new JPasswordField(10);
cU1.setBounds(10, 10, 150, 30);
create_u1.setBounds(100, 10, 100, 30);
cpw1.setBounds(10, 50, 150, 30);
create_pw1.setBounds(100, 50, 100, 30);
add(create_u1);
add(cU1);
create_u1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "Username saved. Now create a password");
statusBar.setText("Create a password");
add(cpw1);
add(create_pw1);
cpw1.repaint();
create_pw1.repaint();
create_pw1.requestFocus();
}
}
);
create_pw1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "Password saved");
statusBar.setText("Account created. Return to main programme");
statusBar.requestFocus();
}
}
);
}
}
class 4
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class change_username extends JFrame {
private JLabel uT1, pwT, uCh, statusBar;
private JTextField username_input, username_change;
private JPasswordField password_input;
create_account objOfClass3 = new create_account();
public void checkUserName() {
objOfClass3.checkUserName(username_input.getText(), password_input.getText());
}
public change_username() {
super("Change Username");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
username_input = new JTextField(10);
pwT = new JLabel("Password");
password_input = new JPasswordField(10);
uCh = new JLabel("New Username");
username_change = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
username_input.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
password_input.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
username_change.setBounds(100, 90, 100, 30);
add(uT1);
add(username_input);
username_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Enter your password");
add(pwT);
add(password_input);
pwT.repaint();
password_input.repaint();
password_input.requestFocus();
}
}
);
password_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Enter your new username");
add(uCh);
add(username_change);
uCh.repaint();
username_change.repaint();
username_change.requestFocus();
checkUserName();
}
}
);
username_change.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Username Changed. Return to main programme");
username_change.requestFocus();
}
}
);
}
}
That is because you are not setting userName attribute first. you should set usernName first then try getUserName()
Try adding below line in your actionPerformed method before printing userName
setUserName(username_input.getText());
here is the corrected and tested code:
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class ChangeUsername extends JFrame {
private JLabel uT1, pwT, uCh, statusBar;
private JTextField usernameInput, usernameChange;
private JPasswordField passwordInput;
public String userName, passWord;
public String getUserName() {
return this.userName;
}
public void setUserName(String givenUserName) {
this.userName = givenUserName;
System.out.println(getUserName()); /////// this correctly prints the variable
}
public ChangeUsername() {
super("Change Username");
setPreferredSize(new Dimension(400, 85));
setLayout(null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
usernameInput = new JTextField(10);
pwT = new JLabel("Password");
passwordInput = new JPasswordField(10);
uCh = new JLabel("New Username");
usernameChange = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
usernameInput.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
passwordInput.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
usernameChange.setBounds(100, 90, 100, 30);
add(uT1);
add(usernameInput);
usernameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
statusBar.setText("Enter your password");
add(pwT);
add(passwordInput);
pwT.repaint();
passwordInput.repaint();
passwordInput.requestFocus();
setUserName(usernameInput.getText());// setting the username
// statusBar.setText(statusBar.getText() + " " + getUserName());
System.out.println(getUserName()); ////// this line does not
}
});
}
public static void main(String argv[]) {
new ChangeUsername().setVisible(true);
}
}
Also I should mention that you should start using Java naming convention and use meaningful names for your classes, attributes and methods.
classes start with Upercase letter
methods and attribute start with lower case
all of identifiers are camelCase so don't use _ between them. write getUserName instead of get_user_name
Read this link for more rules on Java naming convention.
And you need to learn more about OOP. So I suggest reading book Thinking in Java. TIJ third edition is free and good.
Here, you are not setting the value for the text field.
Do something like
username_input.setText(userName);
Put the above line in setUserName(){}
OR
public change_username() {
super("Change Username");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
username_input = new JTextField(10);
pwT = new JLabel("Password");
password_input = new JPasswordField(10);
uCh = new JLabel("New Username");
username_change = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
username_input.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
password_input.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
username_change.setBounds(100, 90, 100, 30);
add(uT1);
add(username_input);
// SET THE TEXT HERE Before the Listener **************************
username_input.setText(getUserName());
// *****************************************************************
Then your code ahead.....