How can activate another gui class with JButton - java

I have two GUI classes named Menu and convert. I want to run the convert class when I click the "open" button. It looks so simple, but I couldn't figure it out.
Menu class
package com.ui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnConvert = new JButton("open");
btnConvert.setBounds(44, 52, 89, 23);
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//???
}
});
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnConvert);
}
}
convert class
package com.ui;
import java.awt.EventQueue;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class convert {
private JFrame frmTitle;
private JTextField textField;
private double value;
private ButtonGroup group;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
convert window = new convert();
window.frmTitle.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public convert() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTitle = new JFrame();
frmTitle.setTitle("TITLE");
frmTitle.setBounds(100, 100, 450, 300);
frmTitle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTitle.getContentPane().setLayout(null);
JLabel lblInputValue = new JLabel("Input value:");
lblInputValue.setBounds(29, 22, 79, 14);
frmTitle.getContentPane().add(lblInputValue);
textField = new JTextField();
textField.setBounds(22, 47, 86, 20);
frmTitle.getContentPane().add(textField);
textField.setColumns(10);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Convert", TitledBorder.LEADING, TitledBorder.TOP, null, Color.RED));
panel.setBounds(29, 118, 264, 133);
frmTitle.getContentPane().add(panel);
panel.setLayout(null);
final JRadioButton rdbtnKelvin = new JRadioButton("Kelvin");
rdbtnKelvin.setBounds(6, 30, 67, 23);
panel.add(rdbtnKelvin);
final JRadioButton rdbtnFahrenheit = new JRadioButton("Fahrenheit");
rdbtnFahrenheit.setBounds(71, 30, 77, 23);
panel.add(rdbtnFahrenheit);
final JRadioButton rdbtnCelcius = new JRadioButton("Celcius");
rdbtnCelcius.setBounds(174, 30, 67, 23);
panel.add(rdbtnCelcius);
group = new ButtonGroup();
group.add(rdbtnCelcius);
group.add(rdbtnFahrenheit);
group.add(rdbtnKelvin);
final JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Celcius", "Fahrenheit", "Kelvin"}));
comboBox.setBounds(177, 47, 116, 20);
frmTitle.getContentPane().add(comboBox);
JButton btnConvert = new JButton("CONVERT");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value = Double.parseDouble(textField.getText().toString());
if(comboBox.getSelectedItem().toString().equals("Celcius")){
if(rdbtnCelcius.isSelected()==true){
value = value;
}
else if (rdbtnFahrenheit.isSelected()==true){
value= 1.8*value +32;
}
else{
value =value+273;
}
}
else if (comboBox.getSelectedItem().toString().equals("Fahrenheit")){
if(rdbtnFahrenheit.isSelected()==true){
value = value;
}
else if (rdbtnCelcius.isSelected()==true){
value= (value-32)*1.8;
}
else{
value =(value-32)/1.8+273;
}
}
else{
if(rdbtnCelcius.isSelected()==true){
value = value-273;
}
else if (rdbtnFahrenheit.isSelected()==true){
value= value -273*1.8+32;
}
else{
value =value;
}
}
textField.setText(value +"");
textField.setEnabled(false);
}
});
btnConvert.setBounds(303, 114, 89, 23);
frmTitle.getContentPane().add(btnConvert);
JButton btnClear = new JButton("CLEAR");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField.setEnabled(true);
comboBox.setSelectedIndex(0);
rdbtnKelvin.setSelected(true);
}
});
btnClear.setBounds(303, 170, 89, 23);
frmTitle.getContentPane().add(btnClear);
}
}

First of all, class names and constructors should start with an upper case letter, like you did it for class Menu, but not for class convert.
A Java programm should have just one and only one main method for all classes. So, delete complete your main method from Convert class, put new Convert(); in the actionPerformed() method of btnConvert in Menu class:
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new Convert();
}
});
and add frmTitle.setVisible(true); to the end of the initialize() method of Convert class.

First, your class names should begin with a capital letter, so instead of "convert" it should be "Convert.
Create a public method in Convert:
public JFrame getFrame() {
return frmTitle;
}
Then in your button's actionPerformed() method, just:
Convert w = new Convert();
w.getFrame().setVisible(true);

Related

is the method to create simple login wrong

I am a newbie in Java GUI development and I am stuck in the following code.
I am open to suggestions. I am actually trying to create a simple login that gives OK if the password is matched to the number 3124, and otherwise shows the error message. Please help me.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
public class testing {
private JFrame frame;
private JTextField username;
private JTextField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testing window = new testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public testing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_1 = new JButton("cancel");
btnNewButton_1.setBounds(266, 181, 109, 56);
frame.getContentPane().add(btnNewButton_1);
username = new JTextField();
username.setBounds(227, 11, 128, 39);
frame.getContentPane().add(username);
username.setColumns(10);
password = new JTextField();
password.setBounds(227, 76, 128, 39);
frame.getContentPane().add(password);
final int num;
num=Integer.parseInt(password);
password.setColumns(10);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(num==3124)
{JOptionPane.showMessageDialog(null, "correct");}
else
{JOptionPane.showMessageDialog(null, "wrong");}
}
});
btnNewButton.setBounds(62, 181, 123, 56);
frame.getContentPane().add(btnNewButton);
}
}
You were checking the password even before the user has had the chance to enter anything into the text box. You need to get and check the value of num in the event listener code i.e. in actionPerformed. Also, don't convert the password to int (someone may enter some non-numeric string).
This code below works better.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
public class Testing {
private JFrame frame;
private JTextField username;
private JTextField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Testing window = new Testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Testing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_1 = new JButton("cancel");
btnNewButton_1.setBounds(266, 181, 109, 56);
frame.getContentPane().add(btnNewButton_1);
username = new JTextField();
username.setBounds(227, 11, 128, 39);
frame.getContentPane().add(username);
username.setColumns(10);
password = new JTextField();
password.setBounds(227, 76, 128, 39);
frame.getContentPane().add(password);
password.setColumns(10);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String num;
num = (password.getText());
if (num.equalsIgnoreCase("3124")) {
JOptionPane.showMessageDialog(null, "correct");
} else {
JOptionPane.showMessageDialog(null, "wrong");
}
}
});
btnNewButton.setBounds(62, 181, 123, 56);
frame.getContentPane().add(btnNewButton);
}
}

Write my ComboBox value to file

I've got a problem with this, I've got text from comboBox saved into text variable but now I can't make it to be saved to the file like 'num1' and 'num2' after I click a buttom. I know I am missing something simple - or everything is wrong anyways please help! Thank!
package windowbuilded.views;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class WiewWindow {
private JFrame frame;
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 {
WiewWindow window = new WiewWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public WiewWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1, num2, ans2, combo;
num1=Integer.parseInt(textField.getText());
num2=Integer.parseInt(textField_1.getText());
ans2 = num1 + num2;
textField_2.setText(Integer.toString(ans2));
try{
File dir = new File("C:\\test");
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
FileWriter writer = new FileWriter(child, true);
PrintWriter out = new PrintWriter(writer);
out.println(num1);
out.println(num2);
out.close();
}
}
} catch (IOException e) {
// do something
}
}
});
btnNewButton.setBounds(124, 206, 89, 23);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(10, 34, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(124, 34, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(124, 101, 86, 20);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Yes", "No", "Blah!"}));
String text = (String)comboBox.getSelectedItem();
System.out.println(text);
comboBox.setBounds(265, 101, 121, 20);
frame.getContentPane().add(comboBox);
}
}

How to store string or integer in java.swing JTextField?

Hello I am working on this project to store student names and record their grades. I have the entire program mapped out and all I need to do now is record the integers and strings from the user input and call it from different classes. I am having trouble with this. Do I use an array? How do I call from another class? Thank you.
package gradebook;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class Student extends JFrame {
private JFrame studentFrame;
private JPanel contentPane;
private JTextField studentNameTextField;
protected Component frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Student frame = new Student();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel lblPleaseEnterThe = new JLabel("Please enter the student name");
lblPleaseEnterThe.setBounds(130, 105, 194, 16);
contentPane.add(lblPleaseEnterThe);
studentNameTextField = new JTextField("Enter here");
String stdname = studentNameTextField.getText();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student.this.dispose();
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a) {
if(cancelButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
contentPane.setVisible(false);
contentPane.disable();
}
}
});
cancelButton.setBounds(207, 243, 117, 29);
contentPane.add(cancelButton);
}
private void initizalize() {
// TODO Auto-generated method stub
}
}
Is it something along the lines of this?
studentNameTextField = new JTextField("Enter here");
String stdname = studentNameTextField.getText();
I know this would be storing it but how do I call that in a different class so I can make it appear on a different Frame?
Update: Okay so I've done this
Student frame = new Student();
String stdname = frame.studentNameTextField.getText();
JLabel addgradesLabel = new JLabel("Add grades for" + frame.studentNameTextField);
addgradesLabel.setBounds(139, 34, 167, 29);
contentPane.add(addgradesLabel);
And it's still not working. I believe I'm not implementing this correctly. I'm trying to title the label with what the user inputs for the name. So it would but "Add grades for" + stdname But it's not calling it correctly. How can I fix this?
Here is my code from the AddStudentName class
studentNameTextField = new JTextField();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student.this.dispose();
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
What should I add here to save the input that the user is inputting into the JTextField? Thanks for the help
Here's the full code for the classes:
package gradebook;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class Student extends JFrame {
private JFrame studentFrame;
private JPanel contentPane;
public JTextField studentNameTextField;
protected Component frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Student frame = new Student();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel lblPleaseEnterThe = new JLabel("Please enter the student name");
lblPleaseEnterThe.setBounds(130, 105, 194, 16);
contentPane.add(lblPleaseEnterThe);
JTextField studentNameTextField = new JTextField();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a) {
if(cancelButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
contentPane.setVisible(false);
contentPane.disable();
}
}
});
cancelButton.setBounds(207, 243, 117, 29);
contentPane.add(cancelButton);
}
private void initizalize() {
// TODO Auto-generated method stub
}
}
and:
package gradebook;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddGrades extends JFrame {
private JPanel contentPane;
private JTextField Assignment1;
private JTextField Assignment2;
private JTextField Assignment3;
private JTextField Assignment4;
private JLabel testsLabel;
private JTextField Test1;
private JTextField Test2;
public JTextField Test3;
public JTextField Test4;
/**
* Launch the application.
*/
public JFrame frame;
public JButton continueButton;
public JButton exitButton;
public static void main(String[] args) {
AddGrades frame = new AddGrades();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddGrades frame = new AddGrades();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddGrades() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel addgradesLabel = new JLabel("Add grades for" + stdname);
addgradesLabel.setBounds(139, 34, 167, 29);
contentPane.add(addgradesLabel);
JLabel assignmentsLabel = new JLabel("Assignments:");
assignmentsLabel.setBounds(19, 75, 86, 16);
contentPane.add(assignmentsLabel);
Assignment1 = new JTextField();
Assignment1.setBounds(54, 91, 130, 26);
contentPane.add(Assignment1);
Assignment1.setColumns(10);
Assignment2 = new JTextField();
Assignment2.setBounds(54, 129, 130, 26);
contentPane.add(Assignment2);
Assignment2.setColumns(10);
Assignment3 = new JTextField();
Assignment3.setBounds(54, 167, 130, 26);
contentPane.add(Assignment3);
Assignment3.setColumns(10);
Assignment4 = new JTextField();
Assignment4.setBounds(54, 205, 130, 26);
contentPane.add(Assignment4);
Assignment4.setColumns(10);
testsLabel = new JLabel("Tests:");
testsLabel.setBounds(243, 75, 38, 16);
contentPane.add(testsLabel);
Test1 = new JTextField();
Test1.setBounds(262, 91, 130, 26);
contentPane.add(Test1);
Test1.setColumns(10);
Test2 = new JTextField();
Test2.setBounds(262, 129, 130, 26);
contentPane.add(Test2);
Test2.setColumns(10);
Test3 = new JTextField();
Test3.setBounds(262, 167, 130, 26);
contentPane.add(Test3);
Test3.setColumns(10);
Test4 = new JTextField();
Test4.setBounds(262, 205, 130, 26);
contentPane.add(Test4);
Test4.setColumns(10);
continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
if (continueButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
exitButton = new JButton("Exit");
exitButton.setBounds(208, 243, 117, 29);
contentPane.add(exitButton);
}
}
I'm trying to take the input from the JTextField
JTextField studentNameTextField = new JTextField();
and set it on the label
JLabel addgradesLabel = new JLabel("Add grades for" + stdname);
Where stdname would be the user input from the JTextField.
Now I'm getting errors from
public static void main(String[] args) {
AddGrades frame = new AddGrades();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddGrades frame = new AddGrades();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
AddGrades frame = new AddGrades(); gives me error Add argument to match AddGrades(String)
The constructor AddGrades() is undefined
Edit: The best way to do this is to pass an argument to your newly created AddGrades class. See below:
public AddGrades(String stdname) {
JLabel addgradesLabel = new JLabel("Add grades for " + stdname);
}
You will need to modify your code to pass a string to your AddGrades class wherever you create it:
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades(studentNameTextField.getText());
addGradesScreen.setVisible(true);
}
}
});
That worked for me - I downloaded your code and tested it.
JSpinner or JFormattedTextField would be my first thought, but if you can't do that then you could use Integer.parseInt to parse a String to int and a NumberFormat to format the numbers to Strings
Maybe have a look at How to Use Spinners and How to Use Formatted Text Fields for starters
I know this would be storing it but how do I call that in a different class so I can make it appear on a different JFrame?
That's a open question with little context. You might use some kind of "model" which represented one or more Student values; you might use a Observer Pattern to allow the editor to generate events to interested parties which would tell them that something has changed; you might use a Model-View-Controller; you might use a modal dialog and when it's closed, ask the editor for the values via getters.
Have a look at How to Make Dialogs for more details
One of things you want to keep in mind is "responsibility" and "encapsulation". You don't want outside parties to have uncontrolled access into your editor or model, this could allow them to modify the state in an uncontrolled way leading to inconsistencies in your data or UI.
You need to decide who is actually responsible for modifying the state of the model. There's no "right" answer, for example, you could have the editor either be capable of editing existing student objects or creating new ones based on how it's configured, equally, you could also have the editor be "dumb" and simply use setters to setup the editor and getters to get the values.
There are lots of options available to you, which you would use would be based on the context in which you want to use it. My gut feeling is start with an observer pattern and a modal dialog.

How can a Global Variable be recognize in two different window (Java Swing GUI)

I've just started Studying Java GUI on Eclipse
Well I've challenged myself to create an Address Book
So here what I Got
FRONT (Swing Application Window)
package byDavid;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.DropMode;
import java.awt.Toolkit;
import javax.swing.JList;
import javax.swing.JMenuBar;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
public class Front {
private JFrame frame;
private final ButtonGroup buttonGroup = new ButtonGroup();
protected int top = 0; //Define Top for Stack Implementation
private static final int MAXENTRIES = 100; //Define Array Size
/**
* Launch the application.
*/
public static void main(String[] args) {
final AdressBookEntry[]list; //List is declared here
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Front window = new Front();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Front() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Front.class.getResource("/com/sun/javafx/webkit/prism/resources/missingImage.png")));
frame.setBounds(100, 100, 357, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JList list = new JList();
JScrollPane scroll = new JScrollPane(list);
scroll.setBounds(24, 22, 185, 210);
frame.getContentPane().add(scroll);
JLabel lblNameEntrees = new JLabel("Name of Entrees");
lblNameEntrees.setBounds(50, 0, 134, 21);
frame.getContentPane().add(lblNameEntrees);
lblNameEntrees.setFont(new Font("Cambria Math", Font.BOLD, 17));
JButton btnAddNewEntry = new JButton("Add Entry\r\n");
btnAddNewEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddEntry nw = new AddEntry();
nw.Addentry();
}
});
buttonGroup.add(btnAddNewEntry);
btnAddNewEntry.setBounds(231, 40, 100, 23);
frame.getContentPane().add(btnAddNewEntry);
JButton btnUpdateEntry = new JButton("Update Entry");
buttonGroup.add(btnUpdateEntry);
btnUpdateEntry.setBounds(231, 74, 99, 23);
frame.getContentPane().add(btnUpdateEntry);
JButton btnNewButton = new JButton("Delete Entry");
buttonGroup.add(btnNewButton);
btnNewButton.setBounds(231, 108, 100, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Quit");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
buttonGroup.add(btnNewButton_1);
btnNewButton_1.setBounds(231, 140, 100, 23);
frame.getContentPane().add(btnNewButton_1);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
}
}
AddEntry (Swing Application Window) /Another A pop-Up Window
package byDavid;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import java.awt.Window.Type;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddEntry {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JButton btnQuit;
private JButton btnAccept;
/**
* Launch the application.
*/
public static void Addentry() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddEntry window = new AddEntry();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddEntry() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JTextField name ;
JTextField add ;
JTextField tel ;
JTextField email;
String name1 = "";
String add1 ="";
long tel1 = 0;
String email1 = "";
frame = new JFrame();
frame.setType(Type.POPUP);
frame.setBounds(100, 100, 369, 219);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblName = new JLabel("Name:");
lblName.setBounds(10, 11, 62, 32);
frame.getContentPane().add(lblName);
JLabel lblAdress = new JLabel("Adress:");
lblAdress.setBounds(10, 42, 62, 32);
frame.getContentPane().add(lblAdress);
JLabel lblPhoneNumber = new JLabel("Phone Number:");
lblPhoneNumber.setBounds(10, 77, 99, 32);
frame.getContentPane().add(lblPhoneNumber);
JLabel lblEmailAddress = new JLabel("Email Address:");
lblEmailAddress.setBounds(10, 108, 99, 32);
frame.getContentPane().add(lblEmailAddress);
name = new JTextField();
name.setBounds(119, 15, 207, 25);
frame.getContentPane().add(name);
name.setColumns(10);
add = new JTextField();
add.setColumns(10);
add.setBounds(118, 46, 208, 25);
frame.getContentPane().add(add);
tel = new JTextField();
tel.setColumns(10);
tel.setBounds(119, 81, 207, 25);
frame.getContentPane().add(tel);
email = new JTextField();
email.setColumns(10);
email.setBounds(119, 112, 207, 25);
frame.getContentPane().add(email);
btnQuit = new JButton("Close");
btnQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
btnQuit.setBounds(237, 148, 89, 23);
frame.getContentPane().add(btnQuit);
btnAccept = new JButton("Accept");
btnAccept.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
name.getText();
add.getText();
tel.getText();
email.getText();
frame.dispose();
//HERE IS THE PROBLEM
//I want the Text to be Assigned to a Variable
//So I will put these code here
/*
AddressBookEntry entry = new AddressBookEntry (name, add, tel, email);
list[top] = entry;
top++;
*/
//Yes list, top is getting the error here.. and It confuses me why?
}
});
btnAccept.setBounds(119, 148, 89, 23);
frame.getContentPane().add(btnAccept);
frame.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[] {frame.getContentPane(), lblName, lblAdress, lblPhoneNumber, lblEmailAddress, textField, textField_1, textField_2, textField_3}));
}
}
How can I declare list and top to be recognized by the Add Entry Pop-up Window?
Because It must be red by this class so I can show it in the Jlist later on ..
AdressBookEntry Class (This is where the temp of the variables go, and'll be called)
package byDavid;
import javax.swing.JTextField;
public class AdressBookEntry {
private JTextField name;
private JTextField add;
private JTextField tel;
private JTextField email;
public AdressBookEntry(JTextField name, JTextField add, JTextField tel, JTextField email){
this.name = name;
this.add = add;
this.tel = tel;
this.email = email;
}
public JTextField getName(){
return name;
}
public void changeName(JTextField name){
this.name = name;
}
public JTextField getAddress(){
return add;
}
public void changeAddress(JTextField add){
this.add = add;
}
public JTextField getTelNumber(){
return tel;
}
public void changeTelNUmbe(JTextField tel){
this.tel = tel;
}
public JTextField getEmailAdd(){
return email;
}
public void changeEmailAdd(JTextField email){
this.email = email;
}
}
I've searched many post,blog and etc. but I can't find specific answer.
Please Explain it to me clearly, because I'm quite confused in Declaring the two, and their specific errors..
One way of doing it:
public static void main(String[] args) {
final AdressBookEntry[] list; //List is declared here
EventQueue.invokeLater(new FrontRunner(list));
}
private class FrontRunner implements Runnable {
private AdressBookEntry[] list;
public FrontRunner(AdressBookEntry[] list) {
this.list = list;
}
public void run() {
try {
Front window = new Front();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

NullPointException error when setting attributes

I'm getting a NullPointerException error at line 77 lblNewLabel.setVisible(false);
which is called from line 65 runTest(); in the following code. (This is a dummy project I wrote to simulate a problem I'm having in a larger project). What I'm trying to do is change the attribute of several fields, buttons, etc based on user action at various places in the project. I would like to group all the changes in a separate method that can be called from various other methods. I'm still a Java novice, having come from some Visual Basic and Pascal experience. Seems like what I'm trying to do should be straight forward, but for now, I'm at a loss. Thanks in advance for your suggestions.
package woodruff;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class MyTest extends JFrame {
private JPanel contentPane;
private JTextField txtHasFocus;
private JLabel lblNewLabel;
/**
* Create the frame.
*/
public MyTest() {
initialize();
}
private void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 237, 161);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblNewLabel = new JLabel("This is a label.");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setHorizontalTextPosition(SwingConstants.CENTER);
lblNewLabel.setBounds(10, 25, 202, 14);
contentPane.add(lblNewLabel);
JButton btnShow = new JButton("Show");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setVisible(true);
}
});
btnShow.setBounds(10, 50, 89, 23);
contentPane.add(btnShow);
JButton btnHide = new JButton("Hide");
btnHide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewLabel.setVisible(false);
}
});
btnHide.setBounds(123, 50, 89, 23);
contentPane.add(btnHide);
txtHasFocus = new JTextField();
txtHasFocus.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
// Following results in NullPointerException error
// at woodruff.MyTest.runTest(MyTest.java:77)
runTest();
}
});
txtHasFocus.setHorizontalAlignment(SwingConstants.CENTER);
txtHasFocus.setText("Has Focus?");
txtHasFocus.setBounds(67, 92, 86, 20);
contentPane.add(txtHasFocus);
txtHasFocus.setColumns(10);
}
private void runTest() {
lblNewLabel.setVisible(false);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyTest frame = new MyTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
In the initialize() method, you have created a local variable for JLabel, and hence are not initializing the instance field, as a reason it remains initialized to null, and hence NPE.
final JLabel lblNewLabel = new JLabel("This is a label.");
change the above line to: -
lblNewLabel = new JLabel("This is a label.");

Categories