Related
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);
}
}
I'm trying to make a QUIZ Application where everytime where the questions are retrieved from the DB,Each time the user selects the right option his marks should be incremented.
While I'm trying to do that the marks doesnt seem to increase and sometimes end up staying at zero even If I select the right option.
This whole project is being done on Eclipse using WindowBuilder. I would be grateful if anyone helped me out on this.
package quiz;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JRadioButton;
import java.sql.*;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import quiz.SqlConnection;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class QuizStart extends JFrame {
SqlConnection c1= new SqlConnection();
public int tmarks=0;
public int db_marks;
String studentAnswer="";
String db_ans="";
static String username="";
String usern;
int count=0;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
QuizStart frame = new QuizStart(username);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #param username2
* #param username
*/
//public QuizStart() {
//initComponents();
//}
public QuizStart(String username) {
//initComponents();
usern=username;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 950, 631);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmBack = new JMenuItem("Back");
mntmBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Login().setVisible(true);
}
});
mnFile.add(mntmBack);
contentPane = new JPanel();
contentPane.setBackground(new Color(30, 144, 255));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBackground(new Color(30, 144, 255));
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblNewLabel.setBounds(101, 47, 715, 99);
contentPane.add(lblNewLabel);
JRadioButton radioButton = new JRadioButton("New radio button");
radioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
radioButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
radioButton.setBounds(124, 213, 230, 47);
contentPane.add(radioButton);
JRadioButton radioButton_1 = new JRadioButton("New radio button");
radioButton_1.setFont(new Font("Tahoma", Font.PLAIN, 16));
radioButton_1.setBounds(125, 289, 254, 60);
contentPane.add(radioButton_1);
JRadioButton radioButton_2 = new JRadioButton("New radio button");
radioButton_2.setFont(new Font("Tahoma", Font.PLAIN, 16));
radioButton_2.setBounds(418, 201, 254, 71);
contentPane.add(radioButton_2);
JRadioButton radioButton_3 = new JRadioButton("New radio button");
radioButton_3.setFont(new Font("Tahoma", Font.PLAIN, 16));
radioButton_3.setBounds(418, 289, 303, 60);
contentPane.add(radioButton_3);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Statement str1= c1.con.createStatement();
ResultSet rs=str1.executeQuery("select Question,Option1,Option2,Option3,Option4,CorrectOption,Marks from question ORDER BY RAND() LIMIT 10");
while(rs.next())
{
String v1=rs.getString("Question");
String v2=rs.getString("Option1");
String v3=rs.getString("Option2");
String v4=rs.getString("Option3");
String v5=rs.getString("Option4");
db_ans=rs.getString("CorrectOption");
db_marks=rs.getInt("Marks");
lblNewLabel.setText(v1);
radioButton.setText(v2);
radioButton_1.setText(v3);
radioButton_2.setText(v4);
radioButton_3.setText(v5);
System.out.print("second");
}
if(radioButton.isSelected())
{
studentAnswer=radioButton.getText();
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_1.isSelected())
{
studentAnswer=radioButton_1.getText();
radioButton.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_2.isSelected())
{
studentAnswer=radioButton_2.getText();
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_3.setSelected(false);
}
else {
studentAnswer=radioButton_3.getText();
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
}
if(db_ans.equals(studentAnswer))
{
tmarks=tmarks+db_marks;
System.out.println("correct-second");
}
count++;
//System.out.println(count);
//System.out.println("two");
System.out.println(tmarks);
if(count == 11)
{
btnNext.setEnabled(false);
}
//for(int i = qhist.size()-1;i>=0; i--){
// System.out.println(qhist.get(i));
//}
}
catch(Exception s) {
System.out.println("Error due to :"+s);
}
}
});
btnNext.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnNext.setBounds(338, 440, 159, 60);
contentPane.add(btnNext);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new QuizResult(usern,tmarks).setVisible(true);
}
});
btnSubmit.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnSubmit.setBounds(706, 524, 159, 60);
contentPane.add(btnSubmit);
JLabel lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(48, 10, 184, 27);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(username);
try {
Statement str= c1.con.createStatement();
ResultSet rs=str.executeQuery("select QID,Question,Option1,Option2,Option3,Option4,CorrectOption,Marks from question ORDER BY RAND() LIMIT 10");
while(rs.next())
{
//qhist.push(rs.getInt("QID"));
String v1=rs.getString("Question");
String v2=rs.getString("Option1");
String v3=rs.getString("Option2");
String v4=rs.getString("Option3");
String v5=rs.getString("Option4");
db_ans=rs.getString("CorrectOption");
db_marks=rs.getInt("Marks");
lblNewLabel.setText(v1);
radioButton.setText(v2);
radioButton_1.setText(v3);
radioButton_2.setText(v4);
radioButton_3.setText(v5);
System.out.print("first");
}
if(radioButton.isSelected())
{
studentAnswer=radioButton.getText();
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_1.isSelected())
{
studentAnswer=radioButton_1.getText();
radioButton.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_2.isSelected())
{
studentAnswer=radioButton_2.getText();
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_3.setSelected(false);
}
else {
studentAnswer=radioButton_3.getText();
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
}
if(db_ans.equals(studentAnswer) )
{
//tmarks=tmarks+db_marks;
//System.out.println("correct");
tmarks=tmarks+db_marks;
System.out.println(tmarks);
System.out.println("correct-first");
}
count++;
//System.out.println("first");
//System.out.println(count);
//System.out.println("one");
}
catch(Exception a) {
System.out.println("Error due to :"+a);
}
}
}
I created a Swing application. I'm using a JProgressBar to show the progres and I want the progress to change when some tasks execute inside a button handler(ActionListener.actionPerformed), but it ins't working. Here is the code:
package com.capgemini.skillparser.ui;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import com.capgemini.skillparser.domain.Employee;
import com.capgemini.skillparser.excel.impl.SkillsXlsxReader;
import com.capgemini.skillparser.excel.impl.SkillsXlsxWriter;
import com.capgemini.skillparser.text.impl.EmployeeNumbersTextReader;
public class TelaPrincipal extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TelaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 427);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel(
new ImageIcon(
new ImageIcon(getClass().getClassLoader().getResource("capgemini-logo.jpg"))
.getImage().getScaledInstance(300, 100, Image.SCALE_DEFAULT)
)
);
label.setBounds(10, 11, 414, 73);
contentPane.add(label);
textField = new JTextField();
textField.setBackground(Color.LIGHT_GRAY);
textField.setBounds(10, 113, 414, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSelecionarPlanilha = new JButton("Selecionar planilha");
btnSelecionarPlanilha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarPlanilha.setBounds(10, 144, 217, 23);
contentPane.add(btnSelecionarPlanilha);
textField_1 = new JTextField();
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(10, 178, 414, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnSelecionarArquivoTxtfiltro = new JButton("Selecionar arquivo txt (filtro)");
btnSelecionarArquivoTxtfiltro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.txt", "txt");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_1.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarArquivoTxtfiltro.setBounds(10, 209, 217, 23);
contentPane.add(btnSelecionarArquivoTxtfiltro);
textField_2 = new JTextField();
textField_2.setBackground(Color.LIGHT_GRAY);
textField_2.setBounds(10, 243, 414, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JButton btnSelecionarDestino = new JButton("Selecionar destino");
btnSelecionarDestino.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_2.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarDestino.setBounds(10, 274, 217, 23);
contentPane.add(btnSelecionarDestino);
JProgressBar progressBar = new JProgressBar();
progressBar.setBounds(10, 318, 414, 23);
progressBar.setValue(0);
progressBar.setStringPainted(true);
contentPane.add(progressBar);
JButton btnGerarPlanilhaAjustada = new JButton("Gerar Planilha Ajustada");
btnGerarPlanilhaAjustada.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//---------------PROBLEM HERE---------------------------------------
try {
progressBar.setIndeterminate(true);
progressBar.setValue(30);
//read a xlsx file
progressBar.setValue(50);
//write a xlsx file
progressBar.setValue(100);
progressBar.setIndeterminate(false);
//nothing above related to progressBar works properly, these statements only execute after the button handler code finishes
}catch(Exception ex) {
ex.printStackTrace();
}
}
});
btnGerarPlanilhaAjustada.setBounds(101, 354, 230, 23);
contentPane.add(btnGerarPlanilhaAjustada);
}
}
I tried many alternative codes, but nothing worked. Some places suggests multi-thread approaches but I don't know how to structure my code to work with multi-thread in a manner that works well. All my tries in this sense have failed.
Can someone help me please? Thank you
Reading and writing are "heavy" operations that might take time to finish. That's why you will have to do them in background, otherwise the GUI thread, a.k.a the Event Dispatch Thread will be busy hence events will not be able to take place (gui will freeze).
You have to create a SwingWorker. The whole idea is this:
Button gets clicked
SwingWorker starts
Worker does a part-step of a heavy operation in background
Worker publishes the progress bar value to the GUI thread
Repeat 3 & 4
Worker is done.
See my example in your code (comments inside the code):
public class TelaPrincipal extends JFrame {
private SwingWorker<Void, Integer> worker;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JProgressBar progressBar;
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
});
}
/**
* Create the frame.
*/
public TelaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 427);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel();
label.setBounds(10, 11, 414, 73);
contentPane.add(label);
textField = new JTextField();
textField.setBackground(Color.LIGHT_GRAY);
textField.setBounds(10, 113, 414, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSelecionarPlanilha = new JButton("Selecionar planilha");
btnSelecionarPlanilha.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx", "xlsx");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarPlanilha.setBounds(10, 144, 217, 23);
contentPane.add(btnSelecionarPlanilha);
textField_1 = new JTextField();
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(10, 178, 414, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnSelecionarArquivoTxtfiltro = new JButton("Selecionar arquivo txt (filtro)");
btnSelecionarArquivoTxtfiltro.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.txt", "txt");
j.setFileFilter(filter);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_1.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarArquivoTxtfiltro.setBounds(10, 209, 217, 23);
contentPane.add(btnSelecionarArquivoTxtfiltro);
textField_2 = new JTextField();
textField_2.setBackground(Color.LIGHT_GRAY);
textField_2.setBounds(10, 243, 414, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JButton btnSelecionarDestino = new JButton("Selecionar destino");
btnSelecionarDestino.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int r = j.showSaveDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
textField_2.setText(j.getSelectedFile().getAbsolutePath());
}
}
});
btnSelecionarDestino.setBounds(10, 274, 217, 23);
contentPane.add(btnSelecionarDestino);
progressBar = new JProgressBar();
progressBar.setBounds(10, 318, 414, 23);
progressBar.setValue(0);
progressBar.setStringPainted(true);
contentPane.add(progressBar);
JButton btnGerarPlanilhaAjustada = new JButton("Gerar Planilha Ajustada");
btnGerarPlanilhaAjustada.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!worker.isDone())
worker.cancel(true); //destroy previous worker
initWorker();
worker.execute();
}
});
btnGerarPlanilhaAjustada.setBounds(101, 354, 230, 23);
contentPane.add(btnGerarPlanilhaAjustada);
initWorker();
}
private void initWorker() {
worker = new SwingWorker<Void, Integer>() {
#Override
protected void process(List<Integer> chunks) {
int value = chunks.get(0);
progressBar.setValue(value);
}
#Override
protected Void doInBackground() throws Exception {
publish(10); //progress bar value that will be sent to process() method
Thread.sleep(2000); //assume read file takes 2 seconds
publish(50); //progress bar value that will be sent to process() method
Thread.sleep(2000); //assume another bg operation takes 2 secs
publish(99);
return null;
}
};
}
}
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.