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);
}
}
Related
My teacher wants me to create a Java program that functions like a vending machine. She wants it to have multidimensional arrays and one-dimensional arrays. I already created the program but I failed because it doesn't have any array in it. It works perfectly fine but there are no arrays in it that's why I failed. She gave me another chance until tomorrow morning. I am really bad at using arrays, to be honest, and I don't really know how to use them in GUI apps. Thank you so much in advance for your help. Below is my code and the output of the current program I have so far.
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.SystemColor;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Cursor;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JRadioButton;
public class Finals {
private JFrame frame;
private JTextField itemField;
private JTextField priceField;
private JButton pushButton, button1, button2, button3;
private JRadioButton day1RB, day2RB, day3RB;
private JTextArea resultsTA;
//----Counter Variables for items A1, A2, and A3 for 3 days with 0 as the initial value
int A1d1=0; int A1d2=0; int A1d3=0;
int A2d1=0; int A2d2=0; int A2d3=0;
int A3d1=0; int A3d2=0; int A3d3=0;
//----Amount Variables for items A1, A2, and A3 for 3 days with 0 as the initial value
int A1d1Amount=0; int A1d2Amount=0; int A1d3Amount=0;
int A2d1Amount=0; int A2d2Amount=0; int A2d3Amount=0;
int A3d1Amount=0; int A3d2Amount=0; int A3d3Amount=0;
//----Variables for items B1, B2, and B3 for 3 days with 0 as the initial value
int B1d1=0; int B1d2=0; int B1d3=0;
int B2d1=0; int B2d2=0; int B2d3=0;
int B3d1=0; int B3d2=0; int B3d3=0;
//----Amount Variables for items B1, B2, and B3 for 3 days with 0 as the initial value
int B1d1Amount=0; int B1d2Amount=0; int B1d3Amount=0;
int B2d1Amount=0; int B2d2Amount=0; int B2d3Amount=0;
int B3d1Amount=0; int B3d2Amount=0; int B3d3Amount=0;
//----Variables used for storing total sales for all items for 3 days with 0 as the initial value
double A1total = 0; double A2total=0; double A3total=0;
double B1total = 0; double B2total=0; double B3total=0;
/**
* Launching the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Finals window = new Finals();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Creating the application.
*/
public Finals() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("Vending Machine");
frame.setResizable(false);
frame.setBounds(100, 100, 914, 334);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel itemsPanel = new JPanel();
itemsPanel.setBackground(SystemColor.activeCaption);
itemsPanel.setBounds(10, 11, 264, 191);
frame.getContentPane().add(itemsPanel);
itemsPanel.setLayout(null);
JLabel a1Label = new JLabel();
a1Label.setBounds(10, 11, 60, 57);
ImageIcon a1Icon = new ImageIcon("cookie.png");
a1Label.setIcon(a1Icon);
itemsPanel.add(a1Label);
JLabel a2Label = new JLabel();
a2Label.setBounds(102, 11, 60, 57);
ImageIcon a2Icon = new ImageIcon("gum.png");
a2Label.setIcon(a2Icon);
itemsPanel.add(a2Label);
JLabel a3Label = new JLabel();
a3Label.setBounds(195, 11, 60, 57);
ImageIcon a3Icon = new ImageIcon("pretzel.png");
a3Label.setIcon(a3Icon);
itemsPanel.add(a3Label);
JLabel b1Label = new JLabel("");
b1Label.setBounds(10, 100, 60, 57);
ImageIcon b1Icon = new ImageIcon("pretzel.png");
b1Label.setIcon(b1Icon);
itemsPanel.add(b1Label);
JLabel b2Label = new JLabel();
b2Label.setBounds(102, 100, 60, 57);
ImageIcon b2Icon = new ImageIcon("cookie.png");
b2Label.setIcon(b2Icon);
itemsPanel.add(b2Label);
JLabel b3Label = new JLabel();
b3Label.setBounds(195, 100, 60, 57);
ImageIcon b3Icon = new ImageIcon("soda.png");
b3Label.setIcon(b3Icon);
itemsPanel.add(b3Label);
JLabel a1lbl = new JLabel("A1");
a1lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
a1lbl.setBounds(27, 63, 25, 26);
itemsPanel.add(a1lbl);
JLabel a2lbl = new JLabel("A2");
a2lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
a2lbl.setBounds(120, 63, 25, 26);
itemsPanel.add(a2lbl);
JLabel a3lbl = new JLabel("A3");
a3lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
a3lbl.setBounds(213, 63, 25, 26);
itemsPanel.add(a3lbl);
JLabel b1lbl = new JLabel("B1");
b1lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
b1lbl.setBounds(27, 154, 25, 26);
itemsPanel.add(b1lbl);
JLabel b2lbl = new JLabel("B2");
b2lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
b2lbl.setBounds(120, 154, 25, 26);
itemsPanel.add(b2lbl);
JLabel b3lbl = new JLabel("B3");
b3lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
b3lbl.setBounds(213, 154, 25, 26);
itemsPanel.add(b3lbl);
pushButton = new JButton("PUSH");
pushButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String selectedItem = itemField.getText();
if(selectedItem.equals("A1") && day1RB.isSelected()) {
A1d1Amount=A1d1Amount+10;
A1d1+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
}
else if(selectedItem.equals("A1") && day2RB.isSelected()) {
A1d2Amount=A1d2Amount+10;
A1d2+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
}else if(selectedItem.equals("A1") && day3RB.isSelected()) {
A1d3Amount=A1d3Amount+10;
A1d3+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
}
else if(selectedItem.equals("A2") && day1RB.isSelected()) {
A2d1Amount=A2d1Amount+20;
A2d1+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
}
else if(selectedItem.equals("A2") && day2RB.isSelected()) {
A2d2Amount=A2d2Amount+20;
A2d2+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
}
else if(selectedItem.equals("A2") && day3RB.isSelected()) {
A2d3Amount=A2d3Amount+20;
A2d3+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
}
else if(selectedItem.equals("A3") && day1RB.isSelected()) {
A3d1Amount=A3d1Amount+30;
A3d1+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
}
else if(selectedItem.equals("A3") && day2RB.isSelected()) {
A3d2Amount=A3d2Amount+30;
A3d2+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
}
else if(selectedItem.equals("A3") && day3RB.isSelected()) {
A3d3Amount=A3d3Amount+30;
A3d3+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
}
else if(selectedItem.equals("B1") && day1RB.isSelected()) {
B1d1Amount=B1d1Amount+15;
B1d1+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
}
else if(selectedItem.equals("B1") && day2RB.isSelected()) {
B1d2Amount=B1d2Amount+15;
B1d2+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
}
else if(selectedItem.equals("B1") && day3RB.isSelected()) {
B1d3Amount=B1d3Amount+15;
B1d3+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
}
else if(selectedItem.equals("B2") && day1RB.isSelected()) {
B2d1Amount=B2d1Amount+25;
B2d1+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
}
else if(selectedItem.equals("B2") && day2RB.isSelected()) {
B2d2Amount=B2d2Amount+25;
B2d2+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
}
else if(selectedItem.equals("B2") && day3RB.isSelected()) {
B2d3Amount=B2d3Amount+25;
B2d3+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
}
else if(selectedItem.equals("B3") && day1RB.isSelected()) {
B3d1Amount=B3d1Amount+35;
B3d1+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
}
else if(selectedItem.equals("B3") && day2RB.isSelected()) {
B3d2Amount=B3d2Amount+35;
B3d2+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
}
else if(selectedItem.equals("B3") && day3RB.isSelected()) {
B3d3Amount=B3d3Amount+35;
B3d3+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
}
double grandTotal = A1total+A2total+A3total+B1total+B2total+B3total;
resultsTA.setText("Item Day1 Day2 Day3 Sales Amount\n\n"
+"A1 "+A1d1+" "+A1d2+" "+A1d3+" ₱"+A1total+"0"
+"\nA2 "+A2d1+" "+A2d2+" "+A2d3+" ₱"+A2total+"0"
+"\nA3 "+A3d1+" "+A3d2+" "+A3d3+" ₱"+A3total+"0"
+"\nB1 "+B1d1+" "+B1d2+" "+B1d3+" ₱"+B1total+"0"
+"\nB2 "+B2d1+" "+B2d2+" "+B2d3+" ₱"+B2total+"0"
+"\nB3 "+B3d1+" "+B3d2+" "+B3d3+" ₱"+B3total+"0"
+"\n\nTotal ₱"+grandTotal+"0"
);
clear();
}
});
pushButton.setEnabled(false);
pushButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
pushButton.setFont(new Font("Tahoma", Font.BOLD, 16));
pushButton.setToolTipText("Press to buy.");
pushButton.setBounds(10, 207, 264, 34);
frame.getContentPane().add(pushButton);
itemField = new JTextField();
itemField.setFont(new Font("Tahoma", Font.BOLD, 16));
itemField.setEditable(false);
itemField.setBounds(293, 11, 218, 34);
frame.getContentPane().add(itemField);
itemField.setColumns(10);
priceField = new JTextField();
priceField.setFont(new Font("Tahoma", Font.BOLD, 16));
priceField.setEditable(false);
priceField.setColumns(10);
priceField.setBounds(293, 56, 218, 34);
frame.getContentPane().add(priceField);
JPanel panel = new JPanel();
panel.setBackground(SystemColor.activeCaption);
panel.setBounds(293, 101, 218, 140);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel label1 = new JLabel("Select a Day of sale first and make");
label1.setFont(new Font("Tahoma", Font.BOLD, 12));
label1.setBounds(2, 2, 216, 14);
panel.add(label1);
JButton aButton = new JButton("A");
aButton.setEnabled(false);
aButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
priceField.setText(null);
pushButton.setEnabled(false);
itemField.setText("A");
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
}
});
aButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aButton.setFont(new Font("Tahoma", Font.BOLD, 15));
aButton.setBounds(62, 47, 46, 33);
panel.add(aButton);
JButton bButton = new JButton("B");
bButton.setEnabled(false);
bButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
priceField.setText(null);
pushButton.setEnabled(false);
itemField.setText("B");
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
}
});
bButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
bButton.setFont(new Font("Tahoma", Font.BOLD, 15));
bButton.setBounds(118, 47, 46, 33);
panel.add(bButton);
button1 = new JButton("1");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pushButton.setEnabled(true);
String itemVal = itemField.getText();
itemField.setText(itemVal+"1");
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
String newVal = itemField.getText();
if(newVal.equals("A1")) {
priceField.setText("₱10.00");
}
else {
priceField.setText("₱15.00");
}
}
});
button1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
button1.setEnabled(false);
button1.setFont(new Font("Tahoma", Font.BOLD, 15));
button1.setBounds(10, 91, 46, 33);
panel.add(button1);
button2 = new JButton("2");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pushButton.setEnabled(true);
String itemVal = itemField.getText();
itemField.setText(itemVal+"2");
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
String newVal = itemField.getText();
if(newVal.equals("A2")) {
priceField.setText("₱20.00");
}
else {
priceField.setText("₱25.00");
}
}
});
button2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
button2.setEnabled(false);
button2.setFont(new Font("Tahoma", Font.BOLD, 15));
button2.setBounds(87, 91, 46, 33);
panel.add(button2);
button3 = new JButton("3");
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pushButton.setEnabled(true);
String itemVal = itemField.getText();
itemField.setText(itemVal+"3");
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
String newVal = itemField.getText();
if(newVal.equals("A3")) {
priceField.setText("₱30.00");
}
else {
priceField.setText("₱35.00");
}
}
});
button3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
button3.setEnabled(false);
button3.setFont(new Font("Tahoma", Font.BOLD, 15));
button3.setBounds(162, 91, 46, 33);
panel.add(button3);
JLabel label2 = new JLabel("a selection from the items.");
label2.setFont(new Font("Tahoma", Font.BOLD, 12));
label2.setBounds(2, 22, 171, 14);
panel.add(label2);
resultsTA = new JTextArea();
resultsTA.setEditable(false);
resultsTA.setBounds(521, 11, 368, 230);
frame.getContentPane().add(resultsTA);
day1RB = new JRadioButton("Day 1");
day1RB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
aButton.setEnabled(true);
bButton.setEnabled(true);
day2RB.setSelected(false);
day3RB.setSelected(false);
}
});
day1RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
day1RB.setFont(new Font("Tahoma", Font.BOLD, 12));
day1RB.setBounds(531, 248, 64, 23);
frame.getContentPane().add(day1RB);
day2RB = new JRadioButton("Day 2");
day2RB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
aButton.setEnabled(true);
bButton.setEnabled(true);
day1RB.setSelected(false);
day3RB.setSelected(false);
}
});
day2RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
day2RB.setFont(new Font("Tahoma", Font.BOLD, 12));
day2RB.setBounds(665, 248, 64, 23);
frame.getContentPane().add(day2RB);
day3RB = new JRadioButton("Day 3");
day3RB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
aButton.setEnabled(true);
bButton.setEnabled(true);
day1RB.setSelected(false);
day2RB.setSelected(false);
}
});
day3RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
day3RB.setFont(new Font("Tahoma", Font.BOLD, 12));
day3RB.setBounds(797, 249, 64, 23);
frame.getContentPane().add(day3RB);
}
//------Clearing everything after transaction
void clear() {
itemField.setText(null);
priceField.setText(null);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
pushButton.setEnabled(false);
}
}
output
As a tip to get you started, you could replace your 3 by 3 set of variabls:
int A1d1=0; int A1d2=0; int A1d3=0;
int A2d1=0; int A2d2=0; int A2d3=0;
int A3d1=0; int A3d2=0; int A3d3=0;
With a multi dimensional array with 3 columns and 3 rows:
int[][] num = new int[3][3];
Or like this:
int[][] num = {{0,0,0},
{0,0,0},
{0,0,0}};
Then to replace the first value in the second column and first row we use:
num[1][0] = newValue;
Be careful because the first value of an array is at position num[0][0] not num[1][1]. So for example, when editing/getting a value the last value in an array it would be at position num[2][2], not at num[3][3]
I'm trying to create a screen to change the options of my game, so I'd a problem that using a JRadioButton works in a case and not in the other, and I didn't understand why... Does anybody know what happened?
package com.damas.screen;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class Options {
private JFrame frame;
protected com.damas.entidades.Options opcoes;
private JRadioButton radioPlayersNo;
private JRadioButton radioPlayersYes;
private JRadioButton radioSoundYes;
private JRadioButton radioSoundNo;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Options window = new Options();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Options() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
opcoes = new com.damas.entidades.Options();
frame = new JFrame();
frame.setBounds(100, 100, 280, 180);
frame.setResizable(Boolean.FALSE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
radioPlayersYes =new JRadioButton("Yes");
radioPlayersNo = new JRadioButton("No");
radioSoundYes = new JRadioButton("Yes");
radioSoundNo = new JRadioButton("No");
JLabel labelSound = new JLabel("Sound");
labelSound.setBounds(50, 99, 86, 23);
radioPlayersYes.setBounds(129, 39, 55, 14);
radioPlayersNo.setBounds(190, 30, 55, 32);
/* Setting default options*/
radioSoundYes.setSelected(opcoes.getSound());
radioPlayersYes.setSelected(opcoes.getTwoPlayers());
/* Setting labels*/
JLabel lblPlayers = new JLabel("Two Players");
lblPlayers.setBounds(50, 43, 73, 14);
JLabel lblColor = new JLabel("Color");
lblColor.setBounds(50, 74, 46, 14);
JLabel lblOptions = new JLabel("Options");
lblOptions.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 16));
lblOptions.setBounds(109, 11, 46, 14);
/* Setting radios*/
JRadioButton radioColorBlack = new JRadioButton("Black");
radioColorBlack.setBounds(115, 65, 77, 32);
JRadioButton radioColorWhite = new JRadioButton("White");
radioColorWhite.setBounds(194, 70, 61, 23);
JRadioButton radioSoundYes = new JRadioButton("Yes");
radioSoundYes.setBounds(120, 94, 55, 32);
JRadioButton radioSoundNo = new JRadioButton("No");
radioSoundNo.setBounds(194, 99, 61, 23);
addItemListeners();
frame.getContentPane().add(radioPlayersYes);
frame.getContentPane().add(radioPlayersNo);
frame.getContentPane().add(radioSoundYes);
frame.getContentPane().add(radioSoundNo);
frame.getContentPane().add(labelSound);
frame.getContentPane().add(lblPlayers);
frame.getContentPane().add(lblColor);
frame.getContentPane().add(radioColorBlack);
frame.getContentPane().add(radioColorWhite);
frame.getContentPane().add(lblOptions);
}
private void addItemListeners(){
radioPlayersYes.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == 1){
opcoes.setTwoPlayers(Boolean.TRUE);
radioPlayersNo.setSelected(Boolean.FALSE);
}else{
opcoes.setTwoPlayers(Boolean.FALSE);
radioPlayersNo.setSelected(Boolean.TRUE);
}
}
});
radioPlayersNo.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == 1){
opcoes.setTwoPlayers(Boolean.FALSE);
System.out.println(opcoes.getTwoPlayers());
radioPlayersNo.setSelected(Boolean.TRUE);
radioPlayersYes.setSelected(Boolean.FALSE);
}else{
opcoes.setTwoPlayers(Boolean.TRUE);
System.out.println(opcoes.getTwoPlayers());
radioPlayersNo.setSelected(Boolean.FALSE);
radioPlayersYes.setSelected(Boolean.TRUE);
}
}
});
radioSoundYes.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
radioSoundYes.setEnabled(Boolean.TRUE);
System.out.println("Radio Sound Yes: Enabled");
radioSoundNo.setEnabled(Boolean.FALSE);
}else{
radioSoundYes.setEnabled(Boolean.FALSE);
System.out.println("Radio Sound Yes: Disabled");
radioSoundNo.setEnabled(Boolean.TRUE);
}
}
});
radioSoundNo.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
radioSoundNo.setEnabled(Boolean.TRUE);
radioSoundYes.setEnabled(Boolean.FALSE);
}else{
radioSoundNo.setEnabled(Boolean.FALSE);
radioSoundYes.setEnabled(Boolean.TRUE);
}
}
});
}
}
Group the radio buttons like
ButtonGroup playOptionsButtonGroup = new ButtonGroup();
playOptionsButtonGroup.add(radioPlayersNo);
playOptionsButtonGroup.add(radioPlayersYes);
playOptionsButtonGroup.add(radioSoundYes);
playOptionsButtonGroup.add(radioSoundNo);
I have a JFrame with three tabs: Home, Statistics, and About.
On the Home tab, I have a counter that tracks how many times you click your left or right arrow, and it updates a counter (I use the KeyListener method):
On the Statistics tab, I want to somehow import these Left and Right values that I generate from the counter.
But, I don't know how to. Can someone help me out here?
Edit:
Here is the code for the Home tab (Left/Right counter)
import java.awt.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class HomePanel extends JPanel implements KeyListener {
// Variables
private int counter = 0;
private int counter2 = 0;
private JLabel counterLabel;
private JLabel counterLabel2;
private JButton countUpButton;
private JButton countDownButton;
// Panel Elements
public HomePanel() {
countUpButton = new JButton ("Left");
countUpButton.setBounds(195, 121, 75, 29);
countUpButton.addKeyListener(this);
countDownButton = new JButton ("Right");
countDownButton.setBounds(195, 162, 77, 29);
countDownButton.addKeyListener(this);
counterLabel = new JLabel("" + counter);
counterLabel.setBounds(282, 126, 34, 16);
counterLabel2 = new JLabel("" + counter2);
counterLabel2.setBounds(282, 167, 34, 16);
setLayout(null);
add (countUpButton);
add (counterLabel);
add (countDownButton);
add (counterLabel2);
}
// Key Listener
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
// Ensures counter updates once per stroke
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
counter++;
counterLabel.setText("" + counter);
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
counter2++;
counterLabel2.setText("" + counter2);
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
And here is the code for the Statistics tab:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class StatsPanel extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
public StatsPanel() {
setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(41, 43, 371, 234);
add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("LEFT:");
lblNewLabel.setBounds(115, 39, 33, 16);
panel.add(lblNewLabel);
JLabel lblRight = new JLabel("RIGHT:");
lblRight.setBounds(105, 67, 43, 16);
panel.add(lblRight);
JLabel lblNewLabel_2 = new JLabel("TOTAL:");
lblNewLabel_2.setBounds(102, 95, 46, 16);
panel.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("% LEFT:");
lblNewLabel_3.setBounds(102, 123, 46, 16);
panel.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("% RIGHT: ");
lblNewLabel_4.setBounds(91, 151, 60, 16);
panel.add(lblNewLabel_4);
textField_2 = new JTextField();
textField_2.setBounds(160, 33, 134, 28);
panel.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(160, 61, 134, 28);
panel.add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(160, 89, 134, 28);
panel.add(textField_4);
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(160, 117, 134, 28);
panel.add(textField_5);
textField_5.setColumns(10);
textField_6 = new JTextField();
textField_6.setBounds(160, 145, 134, 28);
panel.add(textField_6);
textField_6.setColumns(10);
JButton btnCalculate = new JButton("Calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Variables
double num1, num2, ans, percEq1, percEq2, percLeft, percRight;
try {
num1 = Double.parseDouble(textField_2.getText());
num2 = Double.parseDouble(textField_3.getText());
ans = num1 + num2;
textField_4.setText(Double.toString(ans));
percEq1 = (num1/(num1+num2))*100;
percLeft = Math.round(percEq1);
textField_5.setText(Double.toString(percLeft));
percEq2 = (num2/(num1+num2))*100;
percRight = Math.round(percEq2);
textField_6.setText(Double.toString(percRight));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Please enter a valid number!");
}
}
});
btnCalculate.setBounds(79, 185, 117, 29);
panel.add(btnCalculate);
JButton btnRest = new JButton("Reset");
btnRest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField_2.setText("");
textField_3.setText("");
textField_4.setText("");
textField_5.setText("");
textField_6.setText("");
}
});
btnRest.setBounds(197, 185, 117, 29);
panel.add(btnRest);
}
}
I suggest using variables in the parent container so every tab can access them or, from the statistics tab, ask the values to the parent frame and the parent asks to the home tab.
It's not a short code and you haven't attached yours, so I hope your get the idea.
In the main container you have something like this:
KeyPressStats statistics = new KeyPressStats();
HomePanel home = new HomePanel(statistics);
StatsPanel stats = new StatsPanel(statistics);
JTabbedPane tabbed = new JTabbedPane();
tabbed.addTab("Home", home);
tabbed.addTab("Stats", stats);
tabbed.setVisible(true);
KeyPressStats is as follows:
public class KeyPressStats {
private int leftCount = 0;
private int rightCount = 0;
public int getLeftCount() {
return leftCount;
}
public void setLeftCount(int leftCount) {
this.leftCount = leftCount;
}
public int getRightCount() {
return rightCount;
}
public void setRightCount(int rightCount) {
this.rightCount = rightCount;
}
public void incrementRight() {
rightCount++;
}
public void incrementLeft() {
leftCount++;
}
}
And the code in the Home and stats tabs will have these changes:
public class HomePanel extends JPanel implements KeyListener {
...
private KeyPressStats stats;
public HomePanel(KeyPressStats stats) {
this.stats = stats;
countUpButton = new JButton("Left");
countUpButton.setBounds(195, 121, 75, 29);
...
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
stats.incrementLeft();
counterLabel.setText("" + stats.getLeftCount());
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
stats.incrementRight();
counterLabel2.setText("" + stats.getRightCount());
}
}
public class StatsPanel extends JPanel {
...
public StatsPanel(KeyPressStats stats) {
...
textField_2 = new JTextField(""+stats.getLeftCount());
textField_2.setBounds(160, 33, 134, 28);
...
textField_3 = new JTextField(""+stats.getRightCount());
textField_3.setBounds(160, 61, 134, 28);
...
}
}
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.
So i have a bit of a weird issue, i just posted and fixed my other error, but that seems to have created this one, and it makes no sense.
Basically, the user presses a button, this window opens, then whether he presses cancel, or register, this window should setVisible to false. but when this code gets executed, it says my window is null.
package frontend;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Registration extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private static boolean ranOnce = false;
private JPanel contentPane;
private Registration reg;
private JTextField userTF;
private JTextField passTF;
private JTextField emailTF;
private LoginProcess lp = new LoginProcess();
private JLabel error;
private JButton cancelBtn;
/**
* Create the frame.
*/
public Registration() {
if (!ranOnce) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
reg = new Registration();
reg.setVisible(true);
ranOnce = true;
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 245, 212);
setLocationRelativeTo(null);
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, 75, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 75, 14);
contentPane.add(lblPassword);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(10, 61, 75, 14);
contentPane.add(lblEmail);
userTF = new JTextField();
userTF.setBounds(95, 8, 130, 20);
contentPane.add(userTF);
userTF.setColumns(10);
passTF = new JTextField();
passTF.setColumns(10);
passTF.setBounds(95, 33, 130, 20);
contentPane.add(passTF);
emailTF = new JTextField();
emailTF.setColumns(10);
emailTF.setBounds(95, 58, 130, 20);
contentPane.add(emailTF);
error = new JLabel("");
error.setBounds(10, 154, 215, 14);
contentPane.add(error);
JButton regBtn = new JButton("Register");
regBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!userTF.getText().equals("") || !passTF.getText().equals("") || !emailTF.getText().equals("")) {
try {
if (lp.newUser(userTF.getText(), passTF.getText(), emailTF.getText())) {
// THIS IS LINE 117 reg.setVisible(false);
Main.mainFrame.setVisible(true);
} else {
if (lp.duplicateAccount) {
error.setText("Error: Username already in use.");
}
}
} catch (SQLException e) {
}
}
}
});
regBtn.setBounds(10, 120, 215, 23);
contentPane.add(regBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
reg.setVisible(false);
Main.mainFrame.setVisible(true);
}
});
cancelBtn.setBounds(10, 86, 215, 23);
contentPane.add(cancelBtn);
}
}
this is the abnormal error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at frontend.Registration$3.actionPerformed(Registration.java:117)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
i really have no clue as to why it's saying my window is null, when it's not. it has to be something i've done when initialising the window.
Why is it not working ?
You are not using Singleton design pattern correctly. Did you notice that you have two JFrame popping up ?
if (!ranOnce)
{
EventQueue.invokeLater(new Runnable()//this call the run method in a separate thread
{
public void run()
{
try
{
// for the current instance of Registration, you are setting
// the reg variable by calling another instance of Registration => thats not the correct way to do a Singleton
reg = new Registration();
reg.setVisible(true);
ranOnce = true;
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
So, let's assume you are calling new Registration() in your main method, you will enter the public Registration() constructor (let's call it instance1) and set the variable reg by calling one more time the constructor new Registration() (instance2) but by this time, ranOnce will be true and so EventQueue.invokeLater will not be called => reg will not be set in instance2 => NullPointerException when clicking on Jbutton in the second frame (the one on the top) (instance2). Clicking on first frame (instance1) button's will hide the second frame (instance2).
How to fix it ?
Use a proper Singleton :
private static final long serialVersionUID = 1L;
private static boolean ranOnce = false;
private JPanel contentPane;
private static Registration reg;
private JTextField userTF;
private JTextField passTF;
private JTextField emailTF;
private LoginProcess lp = new LoginProcess();
private JLabel error;
private JButton cancelBtn;
public static synchronized Registration getRegistration()
{
if(reg == null)
reg = new Registration();
return reg;
}
/**
* Create the frame.
*/
private Registration()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 245, 212);
setLocationRelativeTo(null);
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, 75, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 75, 14);
contentPane.add(lblPassword);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(10, 61, 75, 14);
contentPane.add(lblEmail);
userTF = new JTextField();
userTF.setBounds(95, 8, 130, 20);
contentPane.add(userTF);
userTF.setColumns(10);
passTF = new JTextField();
passTF.setColumns(10);
passTF.setBounds(95, 33, 130, 20);
contentPane.add(passTF);
emailTF = new JTextField();
emailTF.setColumns(10);
emailTF.setBounds(95, 58, 130, 20);
contentPane.add(emailTF);
error = new JLabel("");
error.setBounds(10, 154, 215, 14);
contentPane.add(error);
JButton regBtn = new JButton("Register");
regBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!userTF.getText().equals("") || !passTF.getText().equals("") || !emailTF.getText().equals("")) {
try {
if (lp.newUser(userTF.getText(), passTF.getText(), emailTF.getText())) {
setVisible(false);
Main.mainFrame.setVisible(true);
} else {
if (lp.duplicateAccount) {
error.setText("Error: Username already in use.");
}
}
} catch (SQLException e) {
}
}
}
});
regBtn.setBounds(10, 120, 215, 23);
contentPane.add(regBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
setVisible(false);
}
});
cancelBtn.setBounds(10, 86, 215, 23);
contentPane.add(cancelBtn);
}
public static void main(String[] args)
{
Registration registration = Registration.getRegistration();
registration.setVisible(true);
}
Try setVisible(fasle) instead of reg.setVisible(false)