This is my first post!
I'm trying to implement the combo box made in the TutCombo program into the ExamGradesGUI + ExamGrades one. As you can see in the TutCombo program, there is the 'String subjectUnitTxt'. Ideally, I would like this to replace the 'subjectUnitTxt' in the ExamGradesGUI program, but having the functionality of the combo box and being able to be saved to the file along with firstName, lastName and examMark. If someone could tell me how to do this, that would be great. Sorry if I have added too much code. Thanks
I got this to work by making some minor changes in your code (see attached code). Search for "unitCombo".
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ExamGradesGUI {
public static void main(String[] args) {
new ExamGradesGUI();
}
String[] firstName = new String[20];
String[] lastName = new String[20];
String[] subjectUnit = new String[20];
double[] examMark = new double[20];
private JLabel firstNameLbl, lastNameLbl, unitLbl, markLbl;
private JTextField firstNameTxt, lastNameTxt, subjectUnitTxt, examMarkTxt;
private JComboBox<String> unitCombo;
private JButton btnClear, btnSave, btnOpen, btnExit;
private JPanel panel;
private JFrame frame;
public ExamGradesGUI(){
buildFrame();
buildFields();
buildButtons();
frame.setVisible(true);
frame.add(panel);
}
public void buildFrame(){
frame = new JFrame("GradeEnter");
frame.setSize(650,450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.white);
}
public void buildFields(){
// Labels, User Input + Location
firstNameTxt = new JTextField(10);
firstNameTxt.setBounds(180, 80, 150, 20);
panel.add(firstNameTxt);
String str = firstNameTxt.getText();
if(str.matches("[-a-zA-Z]*"))
{
}
else
{
JOptionPane.showMessageDialog(null, "Please enter amount donating");
}
lastNameTxt = new JTextField(10);
lastNameTxt.setBounds(180, 110, 150, 20);
panel.add(lastNameTxt);
subjectUnitTxt = new JTextField(10);
String[] courses = {"Computing","Forensic","Business"};
unitCombo = new JComboBox<String>(courses);
//subjectUnitTxt.setBounds(180, 140, 150, 20);
//panel.add(subjectUnitTxt);
unitCombo.setBounds(180, 140, 150, 20);
panel.add(unitCombo);
// IF HAVE TIME: Turn Combo Box into GUI - Refer to testgui.java
examMarkTxt = new JTextField(10);
examMarkTxt.setBounds(180, 170, 150, 20);
panel.add(examMarkTxt);
firstNameLbl = new JLabel("First Name:");
firstNameLbl.setBounds(70, 80, 100, 20);
panel.add (firstNameLbl);
lastNameLbl = new JLabel("Last Name:");
lastNameLbl.setBounds(70, 110, 100, 20);
panel.add (lastNameLbl);
unitLbl = new JLabel("Unit:");
unitLbl.setBounds(70, 140, 100, 20);
panel.add (unitLbl);
markLbl = new JLabel("Mark:");
markLbl.setBounds(70, 170, 100, 20);
panel.add (markLbl);
}
public void buildButtons() {
btnClear = new JButton ("Reset Fields");
btnClear.setBounds(55, 220, 110, 20);
btnClear.addActionListener(new ClearButtonListener());
panel.add (btnClear);
btnSave = new JButton ("Save");
btnSave.setBounds(155, 220, 70, 20);
btnSave.addActionListener(new SaveButton());
panel.add (btnSave);
btnOpen = new JButton ("Open 'GradeEnter.txt' ");
btnOpen.setBounds(90, 250, 200, 20);
btnOpen.addActionListener(new OpenButton());
panel.add (btnOpen);
btnExit = new JButton ("Exit");
btnExit.setBounds(255, 220, 70, 20);
btnExit.addActionListener(new ExitButton());
panel.add (btnExit);
}
public void setText() {
firstNameTxt.setText("");
lastNameTxt.setText("");
subjectUnitTxt.setText("");
examMarkTxt.setText("");
}
public void getText() {
int i = 0;
i++;
firstName[i] = firstNameTxt.getText();
lastName[i] = lastNameTxt.getText();
subjectUnit[i] = unitCombo.getItemAt(unitCombo.getSelectedIndex());
examMark[i] = Double.parseDouble(examMarkTxt.getText());
}
private class ClearButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
setText();
}
}
private class SaveButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
getText();
setText();
ExamGrades save = new ExamGrades();
save.fileOpen();
save.addRecords(firstName, lastName, subjectUnit, examMark);
JOptionPane.showMessageDialog(null, "Entry Saved!");
save.fileClose();
}
}
private class OpenButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
JOptionPane.showMessageDialog(null, "'GradeEnter.txt' opening in Java!");
Thread.sleep(2); // Adds a 2 second delay so user can read dialog message
Runtime.getRuntime().exec("eclipse GradeEnter.txt" );
} catch (Exception NoFileFound) {
System.out.println("Couldn't open or find the file.");
}
}
}
class ExitButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
Related
I am trying to add a "profile picture" to a user's profile page. Basically, I have it to where they can select a file from their computer and upload it to the application, and it will display their profile picture. However it is not working, I think that it currently cannot display it, but generates it incorrectly.
Here is my code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFileChooser;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
class createProfilePage extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel name = new JLabel("Name: ");
JTextField nameField = new JTextField();
JLabel age = new JLabel("Age: ");
JTextField ageField = new JTextField();
JLabel interest = new JLabel("Interests: ");
JTextField interestField = new JTextField();
JLabel aboutMe = new JLabel("About me: ");
JTextField aboutMeField = new JTextField();
JLabel phoneNum = new JLabel("Phone Number: ");
JTextField phoneNumberField = new JTextField();
JButton submit = new JButton("Save Profile");
JButton deleteProfile = new JButton("Delete Profile");
JButton uploadPic = new JButton("Upload Profile Picture");
createProfilePage()
{
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//setting container
setLayoutManager();
setLocationAndSize();
addComponents();
addActionEvent();
setTitle("Welcome");
setSize(600, 500);
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize()
{
//Setting location and Size of each components using setBounds() method.
name.setBounds(50,100,100,30);
age.setBounds(50,170,100,30);
phoneNum.setBounds(50,240,100,30);
interest.setBounds(50,310,100,30);
aboutMe.setBounds(50,380,100,30);
submit.setBounds(350, 240, 150, 30);
deleteProfile.setBounds(350,310,150,30);
uploadPic.setBounds(350,380,150,30);
nameField.setBounds(150,100,150,30);
ageField.setBounds(150,170,150,30);
phoneNumberField.setBounds(150,240,150,30);
interestField.setBounds(150,310,150,30);
aboutMeField.setBounds(150,380,150,30);
}
public void addComponents() {
container.add(name);
container.add(age);
container.add(phoneNum);
container.add(interest);
container.add(aboutMe);
container.add(nameField);
container.add(ageField);
container.add(phoneNumberField);
container.add(interestField);
container.add(aboutMeField);
container.add(submit);
container.add(deleteProfile);
container.add(uploadPic);
}
public void addActionEvent() {
submit.addActionListener(this);
deleteProfile.addActionListener(this);
uploadPic.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submit) {
String name = nameField.getText();
String age = ageField.getText();
String phoneNum = phoneNumberField.getText();
String interest = interestField.getText();
String aboutMe = aboutMeField.getText();
try {
Socket socket = new Socket("localhost", 4242);
ObjectInputStream reader = new ObjectInputStream(socket.getInputStream());
//creating user object to send to the server
User user = new User();
} catch (IOException b) {
b.printStackTrace();
}
JOptionPane.showMessageDialog(this, "Profile Creation Successful");
} else if (e.getSource() == deleteProfile) {
String name = null;
String age = null;
String phoneNum = null;
String interest = null;
String aboutMe = null;
JOptionPane.showMessageDialog(this, "Profile Deletion Successful");
} else if (e.getSource() == uploadPic) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
//ImageDrawer drawer = new ImageDrawer();
Toolkit toolkit = Toolkit.getDefaultToolkit();
String stringFile = file.toString();
Image image = toolkit.getImage(stringFile);
Path path = Paths.get(stringFile);
Path imagePath = path.toAbsolutePath();
String newStr = imagePath.toString();
BufferedImage picture = ImageIO.read(new File(newStr));
JLabel picLabel = new JLabel(new ImageIcon(picture));
picLabel.setBounds(350, 170, 150, 30);
add(picLabel);
} catch (IOException g) {
JOptionPane.showMessageDialog(null,"ERROR");
}
}
}
}
}
Well it 'works' now. This code can open and display an image the user selects. The layout is still broken(1), as hinted by Upload Profile Pict.... That guessed width and cut off text on this computer is one of the many reasons to use layout managers, padding & borders to position elements in a GUI.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
final class createProfilePage extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel name = new JLabel("Name: ");
JTextField nameField = new JTextField();
JLabel age = new JLabel("Age: ");
JTextField ageField = new JTextField();
JLabel interest = new JLabel("Interests: ");
JTextField interestField = new JTextField();
JLabel aboutMe = new JLabel("About me: ");
JTextField aboutMeField = new JTextField();
JLabel phoneNum = new JLabel("Phone Number: ");
JTextField phoneNumberField = new JTextField();
JLabel picLabel = new JLabel();
JButton submit = new JButton("Save Profile");
JButton deleteProfile = new JButton("Delete Profile");
JButton uploadPic = new JButton("Upload Profile Picture");
createProfilePage() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//setting container
setLayoutManager();
setLocationAndSize();
addComponents();
addActionEvent();
setTitle("Welcome");
setSize(600, 500);
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize() {
//Setting location and Size of each components using setBounds() method.
name.setBounds(50, 100, 100, 30);
age.setBounds(50, 170, 100, 30);
phoneNum.setBounds(50, 240, 100, 30);
interest.setBounds(50, 310, 100, 30);
aboutMe.setBounds(50, 380, 100, 30);
submit.setBounds(350, 240, 150, 30);
deleteProfile.setBounds(350, 310, 150, 30);
uploadPic.setBounds(350, 380, 150, 30);
nameField.setBounds(150, 100, 150, 30);
ageField.setBounds(150, 170, 150, 30);
phoneNumberField.setBounds(150, 240, 150, 30);
interestField.setBounds(150, 310, 150, 30);
aboutMeField.setBounds(150, 380, 150, 30);
picLabel.setBounds(350, 50, 150, 150);
}
public void addComponents() {
container.add(name);
container.add(age);
container.add(phoneNum);
container.add(interest);
container.add(aboutMe);
container.add(nameField);
container.add(ageField);
container.add(phoneNumberField);
container.add(interestField);
container.add(aboutMeField);
container.add(picLabel);
container.add(submit);
container.add(deleteProfile);
container.add(uploadPic);
}
public void addActionEvent() {
submit.addActionListener(this);
deleteProfile.addActionListener(this);
uploadPic.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == uploadPic) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
BufferedImage picture = ImageIO.read(file);
picLabel.setIcon(new ImageIcon(picture));
add(picLabel);
} catch (IOException ioe) {
ioe.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR");
}
}
}
}
public static void main(String[] args) {
Runnable r = () -> {
new createProfilePage().setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
Personally, I'd take a different approach to the look of this. A toolbar at top for all the buttons. the two columns of labels and fields on the left as seen there, but with the label text aligned right, and the fields different sizes as per need. Maybe even make the "About me:" a text area, rather than a field. Then, to the right of the label/field combos, the rest of the width
and height devoted to the picture label. It would be shown in a
scroll pane (unless the pictures are all the same size).
Im trying to sort my GUI so it will be able to use the methods from the other classes
in the JProject i also want to call it from the main.
The action listeners i had just learnt today so i need feedback on what to do there as well.
Any Ideas??
It would be a great help to get some insight on this!
(I am new to stack so my code posted in the explanation and in the actual script idk
why).
package test;
import javax.swing.JPanel;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.Container;
import java.awt.SystemColor;
import java.awt.Color;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.io.File;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.util.ArrayList;
import java.util.Scanner;
//Main Method
public class TextUI{
protected StormTracker var;
public TextUI(StormTracker var)
{
this.var=var;
}
public static void main(String[] args)
{
ShowGUI gui = new SHOWGUI();
while(gui.running)
if(gui.buttonPress == -1)
continue;
StormTracker obj = new StormTracker("config.txt");
WeatherAuthority wa = new WeatherAuthority("stormfile.txt");
int xcoord=0;
int ycoord=0;
TextUI uiobj = new TextUI(obj);
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("---------------------------------------------------------------");
System.out.println("Welcome to the StormTracker Application.");
System.out.println("Type the following commands to carry out the associated actions.");
System.out.println("\n");
System.out.println("----------------------{Commands Menu}---------------------
-------");
System.out.println("(1) NEW STORM x y");
System.out.println("(2) UPGRADE <name of storm>");
System.out.println("(3) DOWNGRADE <name of storm>");
System.out.println("(4) TICK");
System.out.println("(5) EXIT");
System.out.println("----------------------------------------------------------------");
String option=scan.nextLine();
if (option.substring(0,4).equals("TICK")){
obj.tick();
continue;
}
if (option.substring(0,9).equals("NEW STORM")){
if(option.length()==13){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,13));
}
else if (option.length()==14){
if (option.substring(11,12).equals(" ")){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,14));
}
else{
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,14));
}
}
else if (option.length()==15){
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,15));
}
obj.newstorm(xcoord,ycoord);
}
if (option.substring(0,7).equals("UPGRADE")){
String storm_name = option.substring(8);
obj.upgrade(storm_name);
}
if (option.substring(0,9).equals("DOWNGRADE")){
String storm_name = option.substring(10);
obj.downgrade(storm_name);
}
}
}
//GUI Class
public ShowGUI extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
System.out.println("GUI Successfully Loaded");
createAndShow();
setToolTipText("Select Storm");
setBackground(Color.WHITE);
}
private void createAndShow(){
JPanel mainFrame = new JPanel("Storm Tracker V1.0");
}
private void addComponents(Container pane){
pane.setLayout(null);
JLabel lblStormTrackerV = DefaultComponentFactory.getInstance().createTitle("
Storm Tracker V1.0");
lblStormTrackerV.setBackground(SystemColor.activeCaption);
lblStormTrackerV.setFont(new Font("Calibri", Font.PLAIN, 22));
lblStormTrackerV.setBounds(162, 11, 430, 41);
add(lblStormTrackerV);
JRadioButton rdbtnMap = new JRadioButton("MAP");
rdbtnMap.setBounds(283, 59, 72, 23);
add(rdbtnMap);
JRadioButton rdbtnBulletin = new JRadioButton("Bulletin");
rdbtnBulletin.setBounds(406, 60, 72, 23);
add(rdbtnBulletin);
textField = new JTextField();
textField.setBounds(61, 103, 72, 20);
add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(61, 134, 72, 20);
add(textField_1);
textField_1.setColumns(10);
JTextPane txtpnX = new JTextPane();
txtpnX.setText("X:");
txtpnX.setBounds(23, 103, 28, 20);
add(txtpnX);
JTextPane txtpnY = new JTextPane();
txtpnY.setText("Y:");
txtpnY.setBounds(23, 134, 12, 20);
add(txtpnY);
JTextPane txtpnSpeed = new JTextPane();
txtpnSpeed.setText("Speed:");
txtpnSpeed.setBounds(10, 165, 41, 20);
add(txtpnSpeed);
textField_2 = new JTextField();
textField_2.setBounds(61, 165, 72, 20);
add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(61, 196, 72, 20);
add(textField_3);
textField_3.setColumns(10);
JTextPane txtpnSpeed_1 = new JTextPane();
txtpnSpeed_1.setText("Speed:");
txtpnSpeed_1.setBounds(10, 196, 41, 20);
add(txtpnSpeed_1);
JTextPane txtpnBearing = new JTextPane();
txtpnBearing.setText("Bearing:");
txtpnBearing.setBounds(10, 227, 41, 20);
add(txtpnBearing);
textField_4 = new JTextField();
textField_4.setBounds(61, 227, 72, 20);
add(textField_4);
textField_4.setColumns(10);
File input = new File(new
FileReader("C:\\Users\\620086793\\Documents\\test\\src\\test"));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}
}
catch (FileNotFoundException e) {
System.err.println("Error, file " + "C:\\Users\\620086793\\Documents\\test\\src\\test" + " didn't exist.");
}
finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
JComboBox comboBox = new JComboBox(lineArray);
JComboBox comboBox = new JComboBox();
comboBox.setToolTipText("Select Storm");
comboBox.setEditable(true);
comboBox.setBounds(20, 60, 113, 20);
add(comboBox);
JButton btnUpdate = new JButton("UPDATE");
btnUpdate.setFont(new Font("Calibri", Font.BOLD, 11));
btnUpdate.setBounds(10, 273, 110, 28);
add(btnUpdate);
JButton btnNewButton = new JButton("NEW STORM\r\n");
btnNewButton.setFont(new Font("Calibri", Font.BOLD, 11));
btnNewButton.setBounds(10, 312, 110, 28);
add(btnNewButton);
addActionListeners();
pane.add(rdbtnMap);
pane.add(rdbtnBulletin);
pane.add(textField);
pane.add(textField_1);
pane.add(textField_2);
pane.add(textField_3);
pane.add(textField_4);
pane.add(comboBox);
pane.add(btnUpdate);
pane.add(btnNewButton);
}
//Im not sure how to properly add the action listeners i first learned about them
today.
private void addActionListeners(){
rdbtnMap.addActionListener(new ActionListener){
public void actionPerformed(ActionEvent ){
}
}
rdbtnBulletin.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_2.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_3.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_4.addActionListener(){
public void actionPerformed(ActionEvent ){
stormTracker.tick = textField_4;
}
}
comboBox.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
btnUpdate.addActionListener(){
public void actionPerformed(ActionEvent ){
obj.upgrade() = btnUpdate;
return btnUpdate;
}
}
btnNewButton.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
}
I'm trying to build a program and I am having trouble getting my ArrayList from another class to show up in a JComboBox. My program will look something like this but before where "Melissa" is written, I want to have a JComboBox that has a list of users and be able to select from it to get the results:
UPDATE Here is my error:
----jGRASP exec: javac -g UserHistory.java
UserHistory.java:20: error: cannot find symbol
String[] userListItems = users.toArray(new String[0]);
^
symbol: variable users
location: class UserHistory
Note: UserHistory.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Here is my incomplete code which gives me an error because it cannot locate my arrayList:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
public class UserHistory extends JPanel {
private JLabel jcomp1;
private JComboBox userList;
private JLabel jcomp3;
private JTextField selectedUser;
private JLabel jcomp5;
private JTextField pointsEarned;
private JLabel jcomp7;
private JList choresCompleted;
public UserHistory() {
//construct preComponents
String[] userListItems = users.toArray(new String[0]);
String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
//construct components
jcomp1 = new JLabel ("User History");
userList = new JComboBox(userListItems);
jcomp3 = new JLabel ("Below are the results of : ");
selectedUser = new JTextField (5);
jcomp5 = new JLabel ("Total points earned: ");
pointsEarned = new JTextField (5);
jcomp7 = new JLabel ("List of chores completed: ");
choresCompleted = new JList (choresCompletedItems);
//set components properties
userList.setToolTipText ("Select a user");
//adjust size and set layout
setPreferredSize (new Dimension (465, 343));
setLayout (null);
//add components
add (jcomp1);
add (userList);
add (jcomp3);
add (selectedUser);
add (jcomp5);
add (pointsEarned);
add (jcomp7);
add (choresCompleted);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (120, 20, 70, 25);
userList.setBounds (210, 20, 100, 25);
jcomp3.setBounds (95, 70, 155, 25);
selectedUser.setBounds (245, 70, 100, 25);
jcomp5.setBounds (125, 105, 140, 25);
pointsEarned.setBounds (245, 105, 100, 25);
jcomp7.setBounds (95, 140, 160, 25);
choresCompleted.setBounds (245, 145, 100, 75);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
}
}
Here's my code for another panel that contains the ArrayList:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public class ManageUsersGUI extends JPanel {
public ArrayList<User> users = new ArrayList<>();
private JLabel addNewUserLabel;
private JTextField addNewUserTextField;
private JLabel deleteUsersLabel;
private JButton addButton;
private JButton deleteButton;
private JPanel namePanel;
public ManageUsersGUI() {
//construct components
addNewUserLabel = new JLabel ("Add new User here:");
addNewUserTextField = new JTextField (0);
deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
addButton = new JButton ("Add");
deleteButton = new JButton ("Delete");
namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
//set components properties
addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
addButton.setToolTipText ("Click here to Add new user.");
deleteButton.setToolTipText ("Click here to delete User(s) selected.");
//adjust size and set layout
setPreferredSize (new Dimension (580, 485));
setLayout (null);
//add components
add (addNewUserLabel);
add (addNewUserTextField);
add (deleteUsersLabel);
add (namePanel);
add (addButton);
add (deleteButton);
//set component bounds (only needed by Absolute Positioning)
addNewUserLabel.setBounds (85, 130, 120, 25);
addNewUserTextField.setBounds (235, 130, 125, 25);
deleteUsersLabel.setBounds (135, 225, 281, 25);
addButton.setBounds (385, 130, 100, 25);
namePanel.setBounds(225, 270, 140, 0);
deleteButton.setBounds (230, 335, 100, 25);
addButton.addActionListener(new AddButtonListener());
deleteButton.addActionListener(new DeleteButtonListener());
}
public ArrayList<User> getUser() {
return users;
}
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = addNewUserTextField.getText();
users.add(new User(text));
// Display the changes.
JOptionPane.showMessageDialog(null, text + " has been added.");
JCheckBox nameCheckBox = new JCheckBox();
nameCheckBox.setText(addNewUserTextField.getText());
namePanel.add(nameCheckBox);
namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
JFrame frame = (JFrame) getRootPane().getParent();
frame.setSize(frame.getWidth(), frame.getHeight() + 25);
frame.pack();
}
}
private class DeleteButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : namePanel.getComponents()) {
if(component instanceof JCheckBox) {
if(((JCheckBox)component).isSelected())
namePanel.remove(component);
}
}
namePanel.revalidate();
namePanel.repaint();
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
}
Here's my User class that was used to make the ArrayList:
public class User {
private String userName;
private int points = 0;
public User(String userName) {
this.userName = userName;
}
public User() {
userName = "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void addPoints(int chorePoints) {
points += chorePoints;
}
// public String toString() {
// return userName + "\n";
// }
}
First of all you would better call user manager module from history main like
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
Which will start both JPanels so you can manage users and watch history at the same time.
Additionally,
// in ManageUsersGUI
public static void manageUsers() {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
And one more thing, as soon as you initialize userlist you need to attach a listener like below:
userList = new JComboBox(userListItems);
userList.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
userList.removeAllItems();
for (User user: users) {
userList.addItem(user.getUserName());
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
These two corrections would you make be able to list user names on the combo box and the dynamic change of user list would be reflected to the listing in the box.
Cheers.
Let me upload the whole source code here
User.java -- Source code just follows (I don't know why they came out of box.)
package userchorelist;
public class User {
private String userName;
private int points = 0;
public User(String userName) {
this.userName = userName;
}
public User() {
userName = "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void addPoints(int chorePoints) {
points += chorePoints;
}
}
ManageUsersGUI.java -- Source code just follows (I don't know why they came out of box, again.)
package userchorelist;
import javax.swing.;
import java.awt.;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public class ManageUsersGUI extends JPanel {
public static ArrayList users = new ArrayList<>();
private JLabel addNewUserLabel;
private JTextField addNewUserTextField;
private JLabel deleteUsersLabel;
private JButton addButton;
private JButton deleteButton;
private JPanel namePanel;
public ManageUsersGUI() {
//construct components
addNewUserLabel = new JLabel ("Add new User here:");
addNewUserTextField = new JTextField (0);
deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
addButton = new JButton ("Add");
deleteButton = new JButton ("Delete");
namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
//set components properties
addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
addButton.setToolTipText ("Click here to Add new user.");
deleteButton.setToolTipText ("Click here to delete User(s) selected.");
//adjust size and set layout
setPreferredSize (new Dimension (580, 485));
setLayout (null);
//add components
add (addNewUserLabel);
add (addNewUserTextField);
add (deleteUsersLabel);
add (namePanel);
add (addButton);
add (deleteButton);
//set component bounds (only needed by Absolute Positioning)
addNewUserLabel.setBounds (85, 130, 120, 25);
addNewUserTextField.setBounds (235, 130, 125, 25);
deleteUsersLabel.setBounds (135, 225, 281, 25);
addButton.setBounds (385, 130, 100, 25);
namePanel.setBounds(225, 270, 140, 0);
deleteButton.setBounds (230, 335, 100, 25);
addButton.addActionListener(new AddButtonListener());
deleteButton.addActionListener(new DeleteButtonListener());
}
public ArrayList<User> getUser() {
return users;
}
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = addNewUserTextField.getText();
users.add(new User(text));
// Display the changes.
JOptionPane.showMessageDialog(null, text + " has been added.");
JCheckBox nameCheckBox = new JCheckBox();
nameCheckBox.setText(addNewUserTextField.getText());
namePanel.add(nameCheckBox);
namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
JFrame frame = (JFrame) getRootPane().getParent();
frame.setSize(frame.getWidth(), frame.getHeight() + 25);
frame.pack();
}
}
private class DeleteButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : namePanel.getComponents()) {
if(component instanceof JCheckBox) {
if(((JCheckBox)component).isSelected())
namePanel.remove(component);
}
}
namePanel.revalidate();
namePanel.repaint();
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
// in ManageUsersGUI
public static void manageUsers() {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
}
UserHistory.java -- Source code just follows (I don't know why they came out of box, third and final time.)
import java.awt.;
import javax.swing.;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import userchorelist.ManageUsersGUI;
import static userchorelist.ManageUsersGUI.manageUsers;
import static userchorelist.ManageUsersGUI.users;
import userchorelist.User;
public class UserHistory extends JPanel {
private JLabel jcomp1;
private JComboBox userList;
private JLabel jcomp3;
private JTextField selectedUser;
private JLabel jcomp5;
private JTextField pointsEarned;
private JLabel jcomp7;
private JList choresCompleted;
public UserHistory() {
//construct preComponents
String[] userListItems = new String[users.size()];
String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
//construct components
jcomp1 = new JLabel ("User History");
userList = new JComboBox(userListItems);
userList.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
userList.removeAllItems();
for (User user: users) {
userList.addItem(user.getUserName());
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
jcomp3 = new JLabel ("Below are the results of : ");
selectedUser = new JTextField (5);
jcomp5 = new JLabel ("Total points earned: ");
pointsEarned = new JTextField (5);
jcomp7 = new JLabel ("List of chores completed: ");
choresCompleted = new JList (choresCompletedItems);
//set components properties
userList.setToolTipText ("Select a user");
//adjust size and set layout
setPreferredSize (new Dimension (465, 343));
setLayout (null);
//add components
add (jcomp1);
add (userList);
add (jcomp3);
add (selectedUser);
add (jcomp5);
add (pointsEarned);
add (jcomp7);
add (choresCompleted);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (120, 20, 70, 25);
userList.setBounds (210, 20, 100, 25);
jcomp3.setBounds (95, 70, 155, 25);
selectedUser.setBounds (245, 70, 100, 25);
jcomp5.setBounds (125, 105, 140, 25);
pointsEarned.setBounds (245, 105, 100, 25);
jcomp7.setBounds (95, 140, 160, 25);
choresCompleted.setBounds (245, 145, 100, 75);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
}
}
I suggest you add receive the list of users as an explicit parameter in both classes UserHistory and ManageUsersGUI:
class UserHistory
{
private final List<User> users;
public UserHistory(List<User> users)
{
super();
this.users=users;
...
}
}
class ManageUsersGUI
{
private final List<User> users;
public UserHistory(List<User> users)
{
super();
this.users=users;
...
}
}
Then, you can create a unique list of users as an external class, let's say UserManagement, and make it a singleton:
public class UserManagement
{
private static final UserManagement INSTANCE=new UserManagement();
private final List<User> list=new ArrayList<User>();
public static UserManagement getInstance()
{
return INSTANCE;
}
private UserManagement()
{
}
public List<User> getUsers()
{
return users;
}
}
Then, you must provide the list of users when instatiating both classes in the main methods (and further, future instatiations you may have):
public static void main (String[] args) {
...
UserManagement.getInstance().getUsers().add("winkum");
UserManagement.getInstance().getUsers().add("blinkum");
UserManagement.getInstance().getUsers().add("nod");
frame.getContentPane().add (new UserHistory(UserManagement.getInstance().getUsers()));
...
}
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.
This is another problem that has come up after having solved my earlier question here:
How to use a variable created in class1, in another class?
The answer to the question above allows me to use a variable created in class 3 to be printed by calling a method in class 4, from class 4.
However, when I try to print that variable as part of an action listener, it prints out 'null' instead of whatever the user inputs in the JTexfield create_u1 (in class 3).
Updated for sajjadG: please try it yourself
class 1
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class class1 extends JFrame {
public static void main(String[] args) {
mainPage MP = new mainPage();
MP.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MP.setLocationRelativeTo(null);
MP.setSize(300,200);
MP.setVisible(true);
}
}
class 2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class mainPage extends JFrame {
create_account crAcc = new create_account();
change_username chU = new change_username();
change_password chPW = new change_password();
sign_in signIn = new sign_in();
private JButton create_account, change_username, change_password, signIn_button;
public mainPage(){
super("Password Programme");
setPreferredSize (new Dimension (400, 100));
setLayout (null);
create_account = new JButton("Create an Account");
add(create_account);
change_username = new JButton("Change Username");
add(change_username);
change_password = new JButton("Change Password");
add(change_password);
signIn_button = new JButton("Sign in and Access Files");
add(signIn_button);
create_account.setBounds (10, 20, 150, 20);
change_username.setBounds (10, 50, 150, 20);
change_password.setBounds (10, 80, 150, 20);
signIn_button.setBounds (10, 110, 200, 20);
HandlerClass handler = new HandlerClass();
create_account.addActionListener(handler);
change_username.addActionListener(handler);
change_password.addActionListener(handler);
signIn_button.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()==create_account) {
crAcc.setLocationRelativeTo(null);
crAcc.setSize(300,200);
crAcc.setVisible(true);
}
if(event.getSource()==change_username) {
chU.setLocationRelativeTo(null);
chU.setSize(300,200);
chU.setVisible(true);
}
if(event.getSource()==change_password) {
chPW.setLocationRelativeTo(null);
chPW.setSize(300,200);
chPW.setVisible(true);
}
if(event.getSource()==signIn_button) {
signIn.setLocationRelativeTo(null);
signIn.setSize(300,200);
signIn.setVisible(true);
}
}
}
}
class 3
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class create_account extends JFrame{
private String u1, pw1;
private JLabel cU1, cpw1, statusBar;
public JTextField create_u1;
public JPasswordField create_pw1;
private JButton change;
public String userName3, passWord3;
public void checkUserName(String u, String pw) {
System.out.println(u); ///// this prints it out correctly
System.out.println(pw);
if (create_u1.getText()==u){
System.out.println("correct");
}else { /// it tests incorrect even though i inputted same thing
System.out.println("incorrect");
System.out.println(create_u1.getText());
System.out.println(userName3); /// prints out null }
}
public create_account() {
super("Create Account");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Create a username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 110, 250, 30);
cU1 = new JLabel("Username");
cpw1 = new JLabel("Password");
create_u1 = new JTextField(10);
create_pw1 = new JPasswordField(10);
cU1.setBounds(10, 10, 150, 30);
create_u1.setBounds(100, 10, 100, 30);
cpw1.setBounds(10, 50, 150, 30);
create_pw1.setBounds(100, 50, 100, 30);
add(create_u1);
add(cU1);
create_u1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "Username saved. Now create a password");
statusBar.setText("Create a password");
add(cpw1);
add(create_pw1);
cpw1.repaint();
create_pw1.repaint();
create_pw1.requestFocus();
}
}
);
create_pw1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "Password saved");
statusBar.setText("Account created. Return to main programme");
statusBar.requestFocus();
}
}
);
}
}
class 4
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class change_username extends JFrame {
private JLabel uT1, pwT, uCh, statusBar;
private JTextField username_input, username_change;
private JPasswordField password_input;
create_account objOfClass3 = new create_account();
public void checkUserName() {
objOfClass3.checkUserName(username_input.getText(), password_input.getText());
}
public change_username() {
super("Change Username");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
username_input = new JTextField(10);
pwT = new JLabel("Password");
password_input = new JPasswordField(10);
uCh = new JLabel("New Username");
username_change = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
username_input.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
password_input.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
username_change.setBounds(100, 90, 100, 30);
add(uT1);
add(username_input);
username_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Enter your password");
add(pwT);
add(password_input);
pwT.repaint();
password_input.repaint();
password_input.requestFocus();
}
}
);
password_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Enter your new username");
add(uCh);
add(username_change);
uCh.repaint();
username_change.repaint();
username_change.requestFocus();
checkUserName();
}
}
);
username_change.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Username Changed. Return to main programme");
username_change.requestFocus();
}
}
);
}
}
That is because you are not setting userName attribute first. you should set usernName first then try getUserName()
Try adding below line in your actionPerformed method before printing userName
setUserName(username_input.getText());
here is the corrected and tested code:
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class ChangeUsername extends JFrame {
private JLabel uT1, pwT, uCh, statusBar;
private JTextField usernameInput, usernameChange;
private JPasswordField passwordInput;
public String userName, passWord;
public String getUserName() {
return this.userName;
}
public void setUserName(String givenUserName) {
this.userName = givenUserName;
System.out.println(getUserName()); /////// this correctly prints the variable
}
public ChangeUsername() {
super("Change Username");
setPreferredSize(new Dimension(400, 85));
setLayout(null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
usernameInput = new JTextField(10);
pwT = new JLabel("Password");
passwordInput = new JPasswordField(10);
uCh = new JLabel("New Username");
usernameChange = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
usernameInput.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
passwordInput.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
usernameChange.setBounds(100, 90, 100, 30);
add(uT1);
add(usernameInput);
usernameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
statusBar.setText("Enter your password");
add(pwT);
add(passwordInput);
pwT.repaint();
passwordInput.repaint();
passwordInput.requestFocus();
setUserName(usernameInput.getText());// setting the username
// statusBar.setText(statusBar.getText() + " " + getUserName());
System.out.println(getUserName()); ////// this line does not
}
});
}
public static void main(String argv[]) {
new ChangeUsername().setVisible(true);
}
}
Also I should mention that you should start using Java naming convention and use meaningful names for your classes, attributes and methods.
classes start with Upercase letter
methods and attribute start with lower case
all of identifiers are camelCase so don't use _ between them. write getUserName instead of get_user_name
Read this link for more rules on Java naming convention.
And you need to learn more about OOP. So I suggest reading book Thinking in Java. TIJ third edition is free and good.
Here, you are not setting the value for the text field.
Do something like
username_input.setText(userName);
Put the above line in setUserName(){}
OR
public change_username() {
super("Change Username");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
username_input = new JTextField(10);
pwT = new JLabel("Password");
password_input = new JPasswordField(10);
uCh = new JLabel("New Username");
username_change = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
username_input.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
password_input.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
username_change.setBounds(100, 90, 100, 30);
add(uT1);
add(username_input);
// SET THE TEXT HERE Before the Listener **************************
username_input.setText(getUserName());
// *****************************************************************
Then your code ahead.....