Toggle Java JPanels - each panel deifferent class - java

I'm a beginer in Java GUI, and i have an issue with trying to toggle between panel in other class.
My main Class "MyBoxGUI" has 2 Panels, "Login" and "UserMenu"
The default is "Login" panel, when pressing "OK" the window moved to "UserMenu" Panel.
So far so good while in the same class.
The issue is, when i set a new panel in new class and setvisibe that panel, i can't go back to "UserMenu" panel - (The actionlistener is working fine).
Can someone help me please?
MyBoxGUI Class
package main;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import java.awt.Component;
//import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.Toolkit;
import GUIs.*;
//import ocsf.client.*;
public class MyBoxGUI extends JPanel
{
private Mtds mtd;
public JFrame frmMybox;
private static JTextField UserName;
private static JTextField port;
private static JTextField IP;
private static JPasswordField passwordField;
public final JPanel Login = new JPanel();
public final JPanel UserMenu = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
MyBoxGUI window = new MyBoxGUI();
window.frmMybox.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyBoxGUI()
{
mtd = new Mtds();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frmMybox = new JFrame();
frmMybox.setFont(new Font("Tempus Sans ITC", Font.BOLD, 15));
// frmMybox.setIconImage(Toolkit.getDefaultToolkit().getImage(MyBoxGUI.class.getResource("/images/gift-ideas-gift-card-bridal-gift-baby-shower-gift-gift-box-groom-gift-christmas-gift-party-gift-gift-for-wedding-friend-gift-birthday-gift-baby-gift-good-gift-box-ideas-for-friend-necklace-gift-box.jpg")));
frmMybox.setBounds(100, 100, 800, 500);
frmMybox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMybox.getContentPane().setLayout(new CardLayout(0, 0));
frmMybox.setTitle("MyBox");
frmMybox.getContentPane().add(Login);
Login.setLayout(null);
JButton btnNewButton = new JButton("OK");
btnNewButton.addActionListener(new ActionListener()
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0)
{
Boolean ok = false;
String UName, Pass, Prt, SIP;
UName = UserName.getText();
Pass = passwordField.getText();
Prt = port.getText();
SIP = IP.getText();
if( ( mtd.isUserValid(UName) && mtd.isPasswordValid(Pass) && mtd.isPortValid(Prt) && mtd.isIPValid(SIP))
&& ( !UName.equals("") && !Pass.equals("") && !Prt.equals("") && !SIP.equals("") ) )
ok = true;
else
{
if(!mtd.isUserValid(UName) || UName.equals(""))
JOptionPane.showMessageDialog(frmMybox,"User Name Can Contain Only The Following Characters: ( 0-9 , a-z , A-Z , _ )"
+ " ","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPasswordValid(Pass) || Pass.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Invalid characters","Error Message",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPortValid(Prt) || Prt.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Port Can Contain Only Numbers","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isIPValid(SIP) || SIP.equals(""))
JOptionPane.showMessageDialog(frmMybox,"IP Address Can Contain Only Numbers seperated By Dots '.' ","Invalid characters",JOptionPane.WARNING_MESSAGE);
}
if(ok)
{
//LoginController user = new LoginController();
//chat= new ClientGUI(IP.getText(),port.getText());
//client = ClientGUI.getClient();
//msg=new Msg("login",user);
//client.handleMessageFromClientUI(msg);
setScreen(Login,UserMenu);
// frmMybox.getContentPane().add(UserMenu, "UserMenu");
// UserMenu.setVisible(true);
// Login.setVisible(false);
}
}
});
btnNewButton.setBounds(344, 313, 82, 48);
Login.add(btnNewButton);
JLabel lblWellcomeToMybox = new JLabel("Wellcome to MyBox");
lblWellcomeToMybox.setForeground(new Color(51, 204, 255));
lblWellcomeToMybox.setFont(new Font("Arial", Font.PLAIN, 36));
lblWellcomeToMybox.setBounds(224, 23, 327, 42);
Login.add(lblWellcomeToMybox);
JLabel lblUserName = new JLabel("User Name:");
lblUserName.setBounds(268, 109, 89, 14);
lblUserName.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblUserName);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(268, 139, 69, 14);
lblPassword.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblPassword);
JLabel lblServerPort = new JLabel("Server port:");
lblServerPort.setBounds(268, 197, 82, 14);
lblServerPort.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerPort);
JLabel lblServerIp = new JLabel("Server IP:");
lblServerIp.setBounds(266, 222, 71, 14);
lblServerIp.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerIp);
UserName = new JTextField();
UserName.setBounds(406, 107, 96, 20);
Login.add(UserName);
UserName.setColumns(10);
port = new JTextField();
port.setBounds(406, 195, 96, 20);
Login.add(port);
port.setColumns(10);
IP = new JTextField();
IP.setBounds(406, 220, 96, 20);
Login.add(IP);
IP.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(406, 137, 96, 20);
Login.add(passwordField);
frmMybox.getContentPane().add(UserMenu, "User Menu");
UserMenu.setLayout(null);
JButton LeaveGOI = new JButton("Back");
LeaveGOI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UserMenu,Login);
}
});
LeaveGOI.setBounds(10, 66, 153, 23);
UserMenu.add(LeaveGOI);
JButton btnJoinAGoi = new JButton("Join a GOI");
btnJoinAGoi.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
}
});
btnJoinAGoi.setBounds(10, 100, 153, 23);
UserMenu.add(btnJoinAGoi);
JButton btnSearchForA = new JButton("Search for a GOI");
btnSearchForA.setBounds(10, 134, 153, 23);
UserMenu.add(btnSearchForA);
JButton btnCreateAGoi = new JButton("Create a GOI");
btnCreateAGoi.setBounds(10, 32, 153, 23);
UserMenu.add(btnCreateAGoi);
JButton btnFilesSharedWith = new JButton("Files shared with you");
btnFilesSharedWith.setBounds(271, 66, 153, 23);
UserMenu.add(btnFilesSharedWith);
JButton btnUploadAFile = new JButton("Upload a file");
btnUploadAFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JPanel UpLoad = new UploadFile();
setScreen(UserMenu,UpLoad);
// frmMybox.getContentPane().add(UpLoad, "UpLoad");
// UserMenu.setVisible(false);
// UpLoad.setVisible(true);
}
});
btnUploadAFile.setBounds(271, 32, 153, 23);
UserMenu.add(btnUploadAFile);
JButton btnSignout = new JButton("Sign-Out");
btnSignout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int dialog=JOptionPane.showConfirmDialog(Login, getUserName()+", are you sure you wants to leave?", "Do you want to leave?", JOptionPane.YES_NO_OPTION);
if(dialog==0){
//client.quit();
}
}
});
btnSignout.setBounds(293, 227, 131, 23);
UserMenu.add(btnSignout);
JButton btnHelpme = new JButton("Help-Me");
btnHelpme.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JOptionPane.showMessageDialog(Login,"Hello "+ getUserName()+", wellcom to Mybox!\n"
+ "Inside GOIs buttons you can ask to join, leave and even create a GOI.\n"
+ "Inside Files buttons you can check and edit files people shared with you.\n"
+ "You can even become an uploader and share files you own.\n"
+ "We wish you good luck and have fun using MyBox!");
}
});
btnHelpme.setBounds(10, 227, 131, 23);
UserMenu.add(btnHelpme);
}
public static String getUserName(){
return UserName.getText();
}
#SuppressWarnings("deprecation")
public static String getPassword(){
return passwordField.getText();
}
public static String getIP(){
return IP.getText();
}
public static String getPort(){
return port.getText();
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
}
}
UploadFile Class
package GUIs;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import main.MyBoxGUI;
public class UploadFile extends MyBoxGUI {
private JTextField textField;
/**
* Create the panel.
*/
public static final JPanel UpLoad = new JPanel();
public UploadFile()
{
setBounds(100, 100, 800, 500);
setLayout(null);
JButton btnNewButton = new JButton("Back");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UpLoad,UserMenu);
System.out.print("A+++");
}
});
btnNewButton.setBounds(126, 145, 205, 30);
add(btnNewButton);
textField = new JTextField();
textField.setBounds(409, 150, 300, 20);
add(textField);
textField.setColumns(10);
JButton btnDone = new JButton("Done");
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDone.setBounds(365, 223, 89, 30);
add(btnDone);
JButton btnHelpMe = new JButton("Help Me");
btnHelpMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnHelpMe.setBounds(188, 390, 122, 52);
add(btnHelpMe);
JButton SignOut = new JButton("Sign-Out");
SignOut.setBounds(501, 392, 122, 48);
add(SignOut);
}
}

public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
frmMybox.getContentPane().revalidate();
frmMybox.getContentPane().repaint();
}
update your setScreen method as above.

Related

Java Swing Application Window - Second Form showing empty

The first class or JFrame that displays just fine
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Window;
import java.awt.Color;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
public class ATM_Display extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JPasswordField jpass_passfield;
char[] password = new char[5]; // field for our password
private StringBuilder tempPin = new StringBuilder(); // temporary pin placeholder
private static List<Account> listOfAccounts = new ArrayList<Account>(); // list of the banks accounts
private static List<JButton> btnList = new ArrayList<JButton>();
private static OptionsMenu frame2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ATM_Display window = new ATM_Display();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ATM_Display() {
initialize();
frame2 = new OptionsMenu();
InstantiateAccList(listOfAccounts); // instantiate our list of accounts including clients names/pin/balance
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 508, 481);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
jpass_passfield = new JPasswordField();
jpass_passfield.setHorizontalAlignment(SwingConstants.CENTER);
jpass_passfield.setFont(new Font("Tahoma", Font.PLAIN, 30));
jpass_passfield.setToolTipText("please enter a valid 4 digit pin number using the numeric buttons below");
jpass_passfield.setEditable(false);
jpass_passfield.setBounds(114, 113, 233, 41);
frame.getContentPane().add(jpass_passfield);
//button 1
JButton btn_1 = new JButton("1");
btn_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("1"); // add to temporary placeholder
jpass_passfield.setText(GetPin()); // set the actual text of the password field
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_1.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_1.setBounds(22, 256, 89, 23);
frame.getContentPane().add(btn_1);
//button 2
JButton btn_2 = new JButton("2");
btn_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("2");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_2.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_2.setBounds(128, 256, 89, 23);
frame.getContentPane().add(btn_2);
//button 3
JButton btn_3 = new JButton("3");
btn_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("3");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_3.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_3.setBounds(229, 256, 89, 23);
frame.getContentPane().add(btn_3);
//button 4
JButton btn_4 = new JButton("4");
btn_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("4");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_4.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_4.setBounds(22, 301, 89, 23);
frame.getContentPane().add(btn_4);
//button 5
JButton btn_5 = new JButton("5");
btn_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("5");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_5.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_5.setBounds(128, 301, 89, 23);
frame.getContentPane().add(btn_5);
//button 6
JButton btn_6 = new JButton("6");
btn_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("6");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_6.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_6.setBounds(229, 301, 89, 23);
frame.getContentPane().add(btn_6);
//button 7
JButton btn_7 = new JButton("7");
btn_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("7");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_7.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_7.setBounds(22, 347, 89, 23);
frame.getContentPane().add(btn_7);
//button 8
JButton btn_8 = new JButton("8");
btn_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("8");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_8.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_8.setBounds(128, 347, 89, 23);
frame.getContentPane().add(btn_8);
//button 9
JButton btn_9 = new JButton("9");
btn_9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("9");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_9.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_9.setBounds(229, 347, 89, 23);
frame.getContentPane().add(btn_9);
//button 0
JButton btn_0 = new JButton("0");
btn_0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddToPassword("1");
jpass_passfield.setText(GetPin());
CheckPinLength(); // check the length of the pin SB
if(CheckPinLength()) { // check the length of the pin SB if >= 5
DisableKeypad(btnList); //disable buttons
}
}
});
btn_0.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_0.setBounds(128, 389, 89, 23);
frame.getContentPane().add(btn_0);
JButton btn_cancel = new JButton("CANCEL");
btn_cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
btn_cancel.setBackground(new Color(255, 0, 0));
btn_cancel.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_cancel.setBounds(328, 256, 127, 23);
frame.getContentPane().add(btn_cancel);
JButton btn_clear = new JButton("CLEAR");
btn_clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClearTempPin(); // clear our temporary pin
jpass_passfield.setText(""); // clear the password field
EnableKeypad(btnList);
}
});
btn_clear.setBackground(Color.YELLOW);
btn_clear.setForeground(Color.BLACK);
btn_clear.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_clear.setBounds(328, 301, 127, 23);
frame.getContentPane().add(btn_clear);
JButton btn_enter = new JButton("ENTER");
btn_enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(isPinValid()) {
frame.setVisible(false);
frame2.setVisible(true);
}
}
});
btn_enter.setBackground(Color.GREEN);
btn_enter.setFont(new Font("Tahoma", Font.BOLD, 16));
btn_enter.setBounds(328, 347, 127, 23);
frame.getContentPane().add(btn_enter);
JLabel lblNewLabel = new JLabel("Enter Pin");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 21));
lblNewLabel.setBounds(179, 79, 114, 23);
frame.getContentPane().add(lblNewLabel);
JLabel lblWelcomePlease = new JLabel("INVESCO ATM");
lblWelcomePlease.setForeground(new Color(0, 128, 0));
lblWelcomePlease.setFont(new Font("Tahoma", Font.BOLD, 25));
lblWelcomePlease.setBounds(144, 11, 189, 23);
frame.getContentPane().add(lblWelcomePlease);
//add buttons to our list
AddBtnsToList(btn_1, btn_2, btn_3, btn_4, btn_5, btn_6, btn_7, btn_8, btn_9, btn_0);
}
// method for accessing private jpass_passfield
/*
* public void AddValToPassField(int i) { this.jpass_passfield. }
*/
// method to instantiate list of accounts
public static void InstantiateAccList(List<Account> x) {
final Account a = new Account("Henry", "Ford", 10000, 12345);
final Account b = new Account("Martha", "Stewart", 3454453, 22345);
final Account c = new Account("Cletus", "Shines", 199, 32345);
final Account d = new Account("Warren", "Scruffet", 28488, 42345);
x.add(a);
x.add(b);
x.add(c);
x.add(d);
}
//method to validate client PIN
// if pin is correct return true
// otherwise return false
public boolean isPinValid() {
for(Account y : listOfAccounts) {
if(y.getPin() == Integer.parseInt(GetPin())) {
return true;
}
}
return false;
}
// Method for adding buttons to the list of buttons
public static void AddBtnsToList(JButton a, JButton b, JButton c, JButton d, JButton e,
JButton f, JButton g, JButton h, JButton i, JButton j) {
btnList.add(a);
btnList.add(b);
btnList.add(c);
btnList.add(d);
btnList.add(e);
btnList.add(f);
btnList.add(g);
btnList.add(h);
btnList.add(i);
btnList.add(j);
}
// method for adding string to the temporary pin string we will be comparing to
public void AddToPassword(String x) {
StringBuilder s = new StringBuilder(x);
this.tempPin.append(s);
}
// gets the current pin string
public String GetPin() {
return this.tempPin.toString();
}
// clears the temporary pin placeholder
public void ClearTempPin() {
this.tempPin.setLength(0);
}
// checks to see if pin is at 5 characters
public boolean CheckPinLength() {
String temp = this.tempPin.toString();
if (temp.length() == 5) {
return true;
}
else { return false;}
}
//method to disable keypad if length is at 5
public void DisableKeypad(List<JButton> x) {
for(JButton y : x) {
y.setEnabled(false);
}
}
//method to Enable under a particular condition
public void EnableKeypad(List<JButton> x) {
for(JButton y : x) {
y.setEnabled(true);
}
}
}
And now my second class.. I'm sorry I'm a complete noob, when I run the debugger it looks like Options Menu is constructing correctly, but then it just displays as the minimize, full screen and exit button and nothing else. It will also run perfectly fine independently if I run it on it's own page. I'm really confused at this point and would appreciate any help. I have seen a lot of examples on here where the JFrame isn't set to isVisible or instantiated, but that isn't the case here. Thank you so much for any help!
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class OptionsMenu extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField tb_deposit;
/**
* Launch the application.
*/
/*
* public static void main(String[] args) { EventQueue.invokeLater(new
* Runnable() { public void run() { try { OptionsMenu window = new
* OptionsMenu(); window.frame.setVisible(true); } catch (Exception e) {
* e.printStackTrace(); } } }); }
*/
/**
* Create the application.
*/
public OptionsMenu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 490, 461);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btn_balance = new JButton("1");
btn_balance.setFont(new Font("Tahoma", Font.BOLD, 25));
btn_balance.setBounds(207, 267, 64, 31);
frame.getContentPane().add(btn_balance);
JButton btn_Withdrawal = new JButton("2");
btn_Withdrawal.setFont(new Font("Tahoma", Font.BOLD, 25));
btn_Withdrawal.setBounds(207, 301, 64, 31);
frame.getContentPane().add(btn_Withdrawal);
JButton btn_deposit = new JButton("3");
btn_deposit.setFont(new Font("Tahoma", Font.BOLD, 25));
btn_deposit.setBounds(207, 335, 64, 31);
frame.getContentPane().add(btn_deposit);
/// exit button
JButton btn_exit = new JButton("4");
btn_exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(frame,
"Do you want to Exit ?", "Exit Confirmation : ",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
frame.dispose();
else if (result == JOptionPane.NO_OPTION)
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
});
btn_exit.setFont(new Font("Tahoma", Font.BOLD, 25));
btn_exit.setBounds(207, 369, 64, 31);
frame.getContentPane().add(btn_exit);
JLabel lblNewLabel = new JLabel("BALANCE INQUIRY:");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel.setBounds(37, 267, 160, 31);
frame.getContentPane().add(lblNewLabel);
JLabel lblWithdrawal = new JLabel("WITHDRAWAL:");
lblWithdrawal.setFont(new Font("Tahoma", Font.BOLD, 15));
lblWithdrawal.setBounds(72, 309, 116, 19);
frame.getContentPane().add(lblWithdrawal);
JLabel lblDeposit = new JLabel("DEPOSIT:");
lblDeposit.setFont(new Font("Tahoma", Font.BOLD, 15));
lblDeposit.setBounds(114, 339, 74, 19);
frame.getContentPane().add(lblDeposit);
JLabel lblExit = new JLabel("EXIT:");
lblExit.setFont(new Font("Tahoma", Font.BOLD, 15));
lblExit.setBounds(140, 369, 48, 14);
frame.getContentPane().add(lblExit);
JButton btn_get20 = new JButton("$20");
btn_get20.setBounds(10, 34, 89, 23);
frame.getContentPane().add(btn_get20);
JButton btn_get40 = new JButton("$40");
btn_get40.setBounds(10, 80, 89, 23);
frame.getContentPane().add(btn_get40);
JButton btn_get60 = new JButton("$60");
btn_get60.setBounds(10, 127, 89, 23);
frame.getContentPane().add(btn_get60);
JButton btn_get100 = new JButton("$100");
btn_get100.setBounds(338, 34, 89, 23);
frame.getContentPane().add(btn_get100);
JButton btn_get200 = new JButton("$200");
btn_get200.setBounds(338, 80, 89, 23);
frame.getContentPane().add(btn_get200);
JButton btn_cancel = new JButton("CANCEL");
btn_cancel.setBounds(338, 127, 89, 23);
frame.getContentPane().add(btn_cancel);
tb_deposit = new JTextField();
tb_deposit.setBounds(157, 128, 96, 20);
frame.getContentPane().add(tb_deposit);
tb_deposit.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Enter Deposit Amount");
lblNewLabel_1.setBounds(157, 103, 114, 14);
frame.getContentPane().add(lblNewLabel_1);
}
public JFrame GetFrame2() {
return this.frame;
}
}
The problem is that your classes (ATM_Display and OptionsMenu) extend JFrame but are never really used as JFrames (you create a separate JFrame instance in each).
That means that when you make the OptionsMenu visible there is nothing to show (because you add all elements to the OptionsMenu.frame).
You should drop the extends clause:
public class ATM_Display {
// ...
}
and
public class OptionsMenu {
// ...
}
Now you will have a compile error in ATM_Display on the following line because the OptionsMenu doesn't have a setVisible() method:
frame2.setVisible(true);
To make the code work again the OptionsMenu needs this setVisible() method to make its frame visible:
public class OptionsMenu {
// ...
public void setVisible(boolean b) {
frame.setVisible(b);
}
}

Graphical User Interface and Main Method needs sorting

Im trying to sort my GUI so it will be able to use the methods from the other classes
in the JProject i also want to call it from the main.
The action listeners i had just learnt today so i need feedback on what to do there as well.
Any Ideas??
It would be a great help to get some insight on this!
(I am new to stack so my code posted in the explanation and in the actual script idk
why).
package test;
import javax.swing.JPanel;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.Container;
import java.awt.SystemColor;
import java.awt.Color;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.io.File;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.util.ArrayList;
import java.util.Scanner;
//Main Method
public class TextUI{
protected StormTracker var;
public TextUI(StormTracker var)
{
this.var=var;
}
public static void main(String[] args)
{
ShowGUI gui = new SHOWGUI();
while(gui.running)
if(gui.buttonPress == -1)
continue;
StormTracker obj = new StormTracker("config.txt");
WeatherAuthority wa = new WeatherAuthority("stormfile.txt");
int xcoord=0;
int ycoord=0;
TextUI uiobj = new TextUI(obj);
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("---------------------------------------------------------------");
System.out.println("Welcome to the StormTracker Application.");
System.out.println("Type the following commands to carry out the associated actions.");
System.out.println("\n");
System.out.println("----------------------{Commands Menu}---------------------
-------");
System.out.println("(1) NEW STORM x y");
System.out.println("(2) UPGRADE <name of storm>");
System.out.println("(3) DOWNGRADE <name of storm>");
System.out.println("(4) TICK");
System.out.println("(5) EXIT");
System.out.println("----------------------------------------------------------------");
String option=scan.nextLine();
if (option.substring(0,4).equals("TICK")){
obj.tick();
continue;
}
if (option.substring(0,9).equals("NEW STORM")){
if(option.length()==13){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,13));
}
else if (option.length()==14){
if (option.substring(11,12).equals(" ")){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,14));
}
else{
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,14));
}
}
else if (option.length()==15){
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,15));
}
obj.newstorm(xcoord,ycoord);
}
if (option.substring(0,7).equals("UPGRADE")){
String storm_name = option.substring(8);
obj.upgrade(storm_name);
}
if (option.substring(0,9).equals("DOWNGRADE")){
String storm_name = option.substring(10);
obj.downgrade(storm_name);
}
}
}
//GUI Class
public ShowGUI extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
System.out.println("GUI Successfully Loaded");
createAndShow();
setToolTipText("Select Storm");
setBackground(Color.WHITE);
}
private void createAndShow(){
JPanel mainFrame = new JPanel("Storm Tracker V1.0");
}
private void addComponents(Container pane){
pane.setLayout(null);
JLabel lblStormTrackerV = DefaultComponentFactory.getInstance().createTitle("
Storm Tracker V1.0");
lblStormTrackerV.setBackground(SystemColor.activeCaption);
lblStormTrackerV.setFont(new Font("Calibri", Font.PLAIN, 22));
lblStormTrackerV.setBounds(162, 11, 430, 41);
add(lblStormTrackerV);
JRadioButton rdbtnMap = new JRadioButton("MAP");
rdbtnMap.setBounds(283, 59, 72, 23);
add(rdbtnMap);
JRadioButton rdbtnBulletin = new JRadioButton("Bulletin");
rdbtnBulletin.setBounds(406, 60, 72, 23);
add(rdbtnBulletin);
textField = new JTextField();
textField.setBounds(61, 103, 72, 20);
add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(61, 134, 72, 20);
add(textField_1);
textField_1.setColumns(10);
JTextPane txtpnX = new JTextPane();
txtpnX.setText("X:");
txtpnX.setBounds(23, 103, 28, 20);
add(txtpnX);
JTextPane txtpnY = new JTextPane();
txtpnY.setText("Y:");
txtpnY.setBounds(23, 134, 12, 20);
add(txtpnY);
JTextPane txtpnSpeed = new JTextPane();
txtpnSpeed.setText("Speed:");
txtpnSpeed.setBounds(10, 165, 41, 20);
add(txtpnSpeed);
textField_2 = new JTextField();
textField_2.setBounds(61, 165, 72, 20);
add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(61, 196, 72, 20);
add(textField_3);
textField_3.setColumns(10);
JTextPane txtpnSpeed_1 = new JTextPane();
txtpnSpeed_1.setText("Speed:");
txtpnSpeed_1.setBounds(10, 196, 41, 20);
add(txtpnSpeed_1);
JTextPane txtpnBearing = new JTextPane();
txtpnBearing.setText("Bearing:");
txtpnBearing.setBounds(10, 227, 41, 20);
add(txtpnBearing);
textField_4 = new JTextField();
textField_4.setBounds(61, 227, 72, 20);
add(textField_4);
textField_4.setColumns(10);
File input = new File(new
FileReader("C:\\Users\\620086793\\Documents\\test\\src\\test"));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}
}
catch (FileNotFoundException e) {
System.err.println("Error, file " + "C:\\Users\\620086793\\Documents\\test\\src\\test" + " didn't exist.");
}
finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
JComboBox comboBox = new JComboBox(lineArray);
JComboBox comboBox = new JComboBox();
comboBox.setToolTipText("Select Storm");
comboBox.setEditable(true);
comboBox.setBounds(20, 60, 113, 20);
add(comboBox);
JButton btnUpdate = new JButton("UPDATE");
btnUpdate.setFont(new Font("Calibri", Font.BOLD, 11));
btnUpdate.setBounds(10, 273, 110, 28);
add(btnUpdate);
JButton btnNewButton = new JButton("NEW STORM\r\n");
btnNewButton.setFont(new Font("Calibri", Font.BOLD, 11));
btnNewButton.setBounds(10, 312, 110, 28);
add(btnNewButton);
addActionListeners();
pane.add(rdbtnMap);
pane.add(rdbtnBulletin);
pane.add(textField);
pane.add(textField_1);
pane.add(textField_2);
pane.add(textField_3);
pane.add(textField_4);
pane.add(comboBox);
pane.add(btnUpdate);
pane.add(btnNewButton);
}
//Im not sure how to properly add the action listeners i first learned about them
today.
private void addActionListeners(){
rdbtnMap.addActionListener(new ActionListener){
public void actionPerformed(ActionEvent ){
}
}
rdbtnBulletin.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_2.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_3.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_4.addActionListener(){
public void actionPerformed(ActionEvent ){
stormTracker.tick = textField_4;
}
}
comboBox.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
btnUpdate.addActionListener(){
public void actionPerformed(ActionEvent ){
obj.upgrade() = btnUpdate;
return btnUpdate;
}
}
btnNewButton.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
}

JAVA - can't get return from isSelected()

I have this part of code here, but whenever I launch the program I only get left brain. even though I check one or the other box.
chckbxMusic = new JCheckBox("Music");
chckbxMusic.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMath.setSelected(false);
}
});
chckbxMusic.setBounds(46, 107, 85, 23);
Question_1.add(chckbxMusic);
chckbxMath = new JCheckBox("Math");
chckbxMath.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMusic.setSelected(false);
}
});
chckbxMath.setBounds(243, 107, 128, 23);
Question_1.add(chckbxMath);
if(chckbxMusic.isSelected()) brain_right++;
else brain_left++;
Ok maybe the full code can help a bit more..
I rewrite it a little bit, but the result is always 0 for both variables??
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class PrgVeloce {
private JFrame frame;
private JPanel Question;
private JPanel Result;
public int brain_left;
public int brain_right;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PrgVeloce window = new PrgVeloce();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PrgVeloce() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
Question = new JPanel();
frame.getContentPane().add(Question, "name_971195205673");
Question.setLayout(null);
final JCheckBox chckbxMath = new JCheckBox("Math");
chckbxMath.setBounds(39, 115, 128, 23);
Question.add(chckbxMath);
final JCheckBox chckbxMusic = new JCheckBox("Music");
chckbxMusic.setBounds(237, 115, 128, 23);
Question.add(chckbxMusic);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(chckbxMusic.isSelected())
{
brain_left = 10;
}
if(chckbxMath.isSelected())
{
brain_right = 10;
}
Question.setVisible(false);
Result.setVisible(true);
}
});
btnNext.setBounds(158, 210, 117, 29);
Question.add(btnNext);
Result = new JPanel();
frame.getContentPane().add(Result, "name_978670915264");
Result.setLayout(null);
JLabel lblEmisferoDx = new JLabel("Right brain:");
lblEmisferoDx.setBounds(90, 118, 110, 16);
Result.add(lblEmisferoDx);
JLabel lblNewLabel = new JLabel("Left Brain:");
lblNewLabel.setBounds(90, 157, 84, 16);
Result.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel(brain_right + "%");
lblNewLabel_1.setBounds(218, 118, 61, 16);
Result.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel(brain_left + "%");
lblNewLabel_2.setBounds(218, 157, 61, 16);
Result.add(lblNewLabel_2);
}
}

Transferring of data from one JPanel to another

I am curious to ask that is it possible to transfer a data from one JPanel to another. I'm currently doing a swing java project which has a profile page and a profile edit page. I wanted to try out creating a method to get the text in a textfield in the profile edit page and then return the textfield.getText();. Then I will follow by calling the exact method from the profile page and setting it as a JLabel. However, I wasn't sure how to do this...
I updated the codes below.
Here is the Profile Edit Page:
package Project;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.border.LineBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ProfileEdit extends MasterPanel {
private JTextField txtbxFullName;
private JTextField txtAdmissionNo;
private JTextField txtbxContactNo;
private JTextField txtFieldDiploma;
/**
* Create the panel.
*/
public ProfileEdit(JFrame mf) {
super(mf);
JLabel lblUserProfile = new JLabel("");
lblUserProfile.setBorder(BorderFactory.createTitledBorder(null,"User Profile",0,0, new Font("Tahoma", Font.PLAIN, 15), Color.WHITE));
lblUserProfile.setForeground(Color.WHITE);
lblUserProfile.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblUserProfile.setBounds(60, 103, 514, 297);
add(lblUserProfile);
JLabel lblDisplayPic = new JLabel("");
lblDisplayPic.setBorder(new LineBorder(Color.WHITE));
lblDisplayPic.setIcon(new ImageIcon(ProfileEdit.class.getResource("/javaProject/images/default-avatar.png")));
lblDisplayPic.setBounds(100, 132, 90, 100);
add(lblDisplayPic);
JLabel lblFullName = new JLabel("Full Name:");
lblFullName.setForeground(Color.WHITE);
lblFullName.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblFullName.setBounds(235, 132, 76, 14);
add(lblFullName);
JLabel lblGender = new JLabel("Gender: ");
lblGender.setForeground(Color.WHITE);
lblGender.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblGender.setBounds(235, 168, 60, 14);
add(lblGender);
JRadioButton rdbtnMale = new JRadioButton("Male");
rdbtnMale.setBackground(Color.DARK_GRAY);
rdbtnMale.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbtnMale.setForeground(Color.WHITE);
rdbtnMale.setBounds(326, 164, 68, 23);
add(rdbtnMale);
JRadioButton rdbtnFemale = new JRadioButton("Female");
rdbtnFemale.setBackground(Color.DARK_GRAY);
rdbtnFemale.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbtnFemale.setForeground(Color.WHITE);
rdbtnFemale.setBounds(396, 164, 77, 23);
add(rdbtnFemale);
ButtonGroup genderRdBtn = new ButtonGroup();
genderRdBtn.add(rdbtnFemale);
genderRdBtn.add(rdbtnMale);
JLabel lblAdmissionNo = new JLabel("Admission No:");
lblAdmissionNo.setForeground(Color.WHITE);
lblAdmissionNo.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblAdmissionNo.setBounds(235, 203, 97, 14);
add(lblAdmissionNo);
JLabel lblContactNo = new JLabel("Contact No:");
lblContactNo.setForeground(Color.WHITE);
lblContactNo.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblContactNo.setBounds(235, 240, 77, 14);
add(lblContactNo);
JLabel lblDiploma = new JLabel("Diploma In:");
lblDiploma.setForeground(Color.WHITE);
lblDiploma.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblDiploma.setBounds(235, 275, 76, 14);
add(lblDiploma);
txtbxFullName = new JTextField();
txtbxFullName.setBounds(326, 130, 147, 20);
add(txtbxFullName);
txtbxFullName.setColumns(10);
txtAdmissionNo = new JTextField();
txtAdmissionNo.setBounds(326, 201, 147, 20);
add(txtAdmissionNo);
txtAdmissionNo.setColumns(10);
txtbxContactNo = new JTextField();
txtbxContactNo.setBounds(326, 238, 147, 20);
add(txtbxContactNo);
txtbxContactNo.setColumns(10);
txtFieldDiploma = new JTextField();
txtFieldDiploma.setBounds(326, 273, 147, 20);
add(txtFieldDiploma);
txtFieldDiploma.setColumns(10);
JButton btnSubmit = new JButton("SUBMIT");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home home = new Home(mf);
mf.setContentPane(home);
mf.setVisible(true);
}
});
btnSubmit.setBounds(235, 336, 114, 23);
add(btnSubmit);
JButton btnCancel = new JButton("CANCEL");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home home = new Home(mf);
mf.setContentPane(home);
mf.setVisible(true);
}
});
btnCancel.setBounds(359, 336, 114, 23);
add(btnCancel);
JButton btnBrowse = new JButton("Browse");
btnBrowse.setBounds(101, 247, 89, 23);
add(btnBrowse);
}
}
Here is the Profile Page :
package Project;
import java.awt.Color;
import Project.ProfileEdit;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.border.LineBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import Project.ProfileEdit;
public class Home extends MasterPanel {
/**
* Create the panel.
*/
public Home(JFrame mf) {
super(mf);
JLabel lblUserProfile = new JLabel("");
//createTitledBorder(border, string, int, int, font, color)
lblUserProfile.setBorder(BorderFactory.createTitledBorder(null,"User Profile",0,0, new Font("Tahoma", Font.PLAIN, 15), Color.WHITE));
//setBounds(left, top, right, bottom)
lblUserProfile.setBounds(60, 103, 510, 267);
add(lblUserProfile);
JLabel lblDisplayPic = new JLabel("");
lblDisplayPic.setBorder(new LineBorder(Color.WHITE));
lblDisplayPic.setIcon(new ImageIcon(Home.class.getResource("/javaProject/images/default-avatar.png")));
lblDisplayPic.setBounds(108, 142, 90, 100);
add(lblDisplayPic);
JLabel lblFullName = new JLabel("Full Name:");
lblFullName.setForeground(Color.WHITE);
lblFullName.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblFullName.setBounds(251, 131, 76, 14);
add(lblFullName);
JLabel lblGender = new JLabel("Gender: ");
lblGender.setForeground(Color.WHITE);
lblGender.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblGender.setBounds(251, 151, 60, 14);
add(lblGender);
JLabel lblAdmissionNo = new JLabel("Admission No:");
lblAdmissionNo.setForeground(Color.WHITE);
lblAdmissionNo.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblAdmissionNo.setBounds(251, 176, 97, 14);
add(lblAdmissionNo);
JLabel lblContactNo = new JLabel("Contact No:");
lblContactNo.setForeground(Color.WHITE);
lblContactNo.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblContactNo.setBounds(251, 195, 77, 14);
add(lblContactNo);
JLabel lblDiploma = new JLabel("Diploma In:");
lblDiploma.setForeground(Color.WHITE);
lblDiploma.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblDiploma.setBounds(251, 218, 76, 14);
add(lblDiploma);
JButton btnEdit = new JButton("Edit ");
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ProfileEdit ProfileEdit = new ProfileEdit(mf);
mf.setContentPane(ProfileEdit);
mf.setVisible(true);
}
});
btnEdit.setBounds(251, 309, 89, 23);
add(btnEdit);
}
}
and Lastly, here is the Master Panel if you guys need it :
package Project;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import java.awt.Color;
import javax.swing.JSeparator;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MasterPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
protected JFrame myFrame = null;
/**
* Create the panel.
*/
public MasterPanel(JFrame mf) {
myFrame = mf;
setBackground(Color.DARK_GRAY);
setLayout(null);
//set a new menubar for home
JMenuBar menuBarHome = new JMenuBar();
menuBarHome.setForeground(Color.BLACK);
menuBarHome.setBackground(Color.WHITE);
// x,y,width,height
// >x = right, <x = left
// >y = bottom, <y = up
menuBarHome.setBounds(80, 40, 97, 21);
//length and height
menuBarHome.setSize(48, 20);
add(menuBarHome);
JMenu home = new JMenu("HOME");
home.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Home home = new Home(mf);
mf.setContentPane(home);
mf.setVisible(true);
}
});
menuBarHome.add(home);
//set a new menubar for calendar
JMenuBar menuBarCalendar = new JMenuBar();
menuBarCalendar.setForeground(Color.BLACK);
menuBarCalendar.setBackground(Color.WHITE);
menuBarCalendar.setBounds(145, 40, 97, 21);
menuBarCalendar.setSize(75, 20);
add(menuBarCalendar);
JMenu calendar = new JMenu("CALENDAR");
calendar.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Calendar calendar = new Calendar(mf);
mf.setContentPane(calendar);
mf.setVisible(true);
}
});
menuBarCalendar.add(calendar);
JMenuBar menuBarAcademic = new JMenuBar();
menuBarAcademic.setForeground(Color.BLACK);
menuBarAcademic.setBackground(Color.WHITE);
menuBarAcademic.setBounds(235, 40, 220, 21);
menuBarAcademic.setSize(72, 20);
add(menuBarAcademic);
JMenu academic = new JMenu("ACADEMIC");
menuBarAcademic.add(academic);
//add sub menu into the academic
JMenuItem lectureNotes = new JMenuItem("Lecture Notes");
lectureNotes.setForeground(Color.BLACK);
lectureNotes.setBackground(Color.WHITE);
lectureNotes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
LectureNotes LectureNotes = new LectureNotes(mf);
mf.setContentPane(LectureNotes);
mf.setVisible(true);
}
});
academic.add(lectureNotes);
JMenuItem resulttracker = new JMenuItem("Result Tracker");
resulttracker.setForeground(Color.BLACK);
resulttracker.setBackground(Color.WHITE);
resulttracker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ResultTracker resulttracker = new ResultTracker(mf);
mf.setContentPane(resulttracker);
mf.setVisible(true);
}
});
academic.add(resulttracker);
JMenuItem studyplan = new JMenuItem("Study Planner");
studyplan.setForeground(Color.BLACK);
studyplan.setBackground(Color.WHITE);
studyplan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StudyPlanner studyplanner = new StudyPlanner(mf);
mf.setContentPane(studyplanner);
mf.setVisible(true);
}
});
academic.add(studyplan);
JMenuItem timetable = new JMenuItem("Timetable");
timetable.setForeground(Color.BLACK);
timetable.setBackground(Color.WHITE);
timetable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TimeTable timetable = new TimeTable(mf);
mf.setContentPane(timetable);
mf.setVisible(true);
}
});
academic.add(timetable);
JMenuBar menuBarEmail = new JMenuBar();
menuBarEmail.setForeground(Color.BLACK);
menuBarEmail.setBackground(Color.WHITE);
menuBarEmail.setBounds(320, 40, 97, 21);
menuBarEmail.setSize(47, 20);
add(menuBarEmail);
JMenu email = new JMenu("EMAIL");
menuBarEmail.add(email);
JMenuItem composeemail = new JMenuItem("Compose");
composeemail.setForeground(Color.BLACK);
composeemail.setBackground(Color.WHITE);
composeemail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Email email = new Email(mf);
mf.setContentPane(email);
mf.setVisible(true);
}
});
email.add(composeemail);
JMenuItem inboxemail = new JMenuItem("Inbox");
inboxemail.setForeground(Color.BLACK);
inboxemail.setBackground(Color.WHITE);
email.add(inboxemail);
JMenuBar menuBarContactus = new JMenuBar();
menuBarContactus.setForeground(Color.BLACK);
menuBarContactus.setBackground(Color.WHITE);
menuBarContactus.setBounds(380, 40, 97, 21);
menuBarContactus.setSize(85, 20);
add(menuBarContactus);
JMenu contactus= new JMenu("CONTACT US");
contactus.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
ContactUs contactus = new ContactUs(mf);
mf.setContentPane(contactus);
mf.setVisible(true);
}
});
menuBarContactus.add(contactus);
JMenuBar menuBarLogout = new JMenuBar();
menuBarLogout.setForeground(Color.BLACK);
menuBarLogout.setBackground(Color.WHITE);
menuBarLogout.setBounds(480, 40, 97, 21);
menuBarLogout.setSize(60, 20);
add(menuBarLogout);
JMenu logout = new JMenu("LOGOUT");
logout.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Login login = new Login(mf);
mf.setContentPane(login);
mf.setVisible(true);
}
});
menuBarLogout.add(logout);
JSeparator separatorTop = new JSeparator();
separatorTop.setBounds(50, 23, 524, 2);
add(separatorTop);
JSeparator separatorBottom = new JSeparator();
separatorBottom.setBounds(50, 79, 524, 2);
add(separatorBottom);
}
}

Using a variable from another class in an Action Listener outputs 'null'

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.....

Categories

Resources