NullPointException error when setting attributes - java

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.");

Related

progress bar loading is not working

I am try to run the progress bar in my frame but it is not working. I am tried to display the visible in my second java class but set visible(true) displaying it as error.
Hope you guys can help me to solve my problem/error
Displaying error in my second java class:
"Exception in thread "main"
java.lang.Error: Unresolved compilation problem: The method
setvisible(boolean) is undefined for the type mgfinancewindow"
First java class: mgfinancewindow.java
package mgfinance;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class mgfinancewindow {
private JFrame frame;
public JProgressBar progressBar;
public JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mgfinancewindow window = new mgfinancewindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mgfinancewindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("MG Finances");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 1362, 705);
frame.getContentPane().add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.DARK_GRAY);
panel_1.setBounds(0, 646, 1362, 59);
panel.add(panel_1);
panel_1.setLayout(null);
lblNewLabel = new JLabel("Loading...");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(1139, 0, 114, 34);
panel_1.add(lblNewLabel);
progressBar = new JProgressBar();
progressBar.setBackground(new Color(0, 51, 51));
progressBar.setBounds(0, 34, 1362, 14);
panel_1.add(progressBar);
JLabel lblMgFinance = new JLabel("MG Finance");
lblMgFinance.setHorizontalAlignment(SwingConstants.CENTER);
lblMgFinance.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
lblMgFinance.setForeground(Color.BLUE);
lblMgFinance.setBounds(0, 11, 1362, 635);
panel.add(lblMgFinance);
}
}
second java class: progressbar.java
package mgfinance;
public class progress {
public static void main(String[] args) throws InterruptedException{
mgfinancewindow load = new mgfinancewindow();
for(int i=0; i<=100; i++){
Thread.sleep(150);
load.setvisible(true);
load.lblNewLabel.setText("Loading..."+ i);
load.progressBar.setValue(i);
}
}
}
Your mgfinancewindow class is not a JComponent to support the setVisible() method itself. The JFrame inside it has the setVisible method.
In the way you wrote the code, to solve your problem quickly you must write the frame.setVisible(true); at the end (last statement) of initialize() method in mgfinancewindow class and remove load.setvisible(true); from the main method of progress class:
public class progress {
public static void main(String[] args) throws InterruptedException {
mgfinancewindow load = new mgfinancewindow();
for (int i = 0; i <= 100; i++) {
Thread.sleep(150);
//load.setvisible(true);
load.lblNewLabel.setText("Loading..." + i);
load.progressBar.setValue(i);
}
}
}
and
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
public class mgfinancewindow {
private JFrame frame;
public JProgressBar progressBar;
public JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mgfinancewindow window = new mgfinancewindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mgfinancewindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("MG Finances");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 1362, 705);
frame.getContentPane().add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.DARK_GRAY);
panel_1.setBounds(0, 646, 1362, 59);
panel.add(panel_1);
panel_1.setLayout(null);
lblNewLabel = new JLabel("Loading...");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(1139, 0, 114, 34);
panel_1.add(lblNewLabel);
progressBar = new JProgressBar();
progressBar.setBackground(new Color(0, 51, 51));
progressBar.setBounds(0, 34, 1362, 14);
panel_1.add(progressBar);
JLabel lblMgFinance = new JLabel("MG Finance");
lblMgFinance.setHorizontalAlignment(SwingConstants.CENTER);
lblMgFinance.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
lblMgFinance.setForeground(Color.BLUE);
lblMgFinance.setBounds(0, 11, 1362, 635);
panel.add(lblMgFinance);
frame.setVisible(true);
}
}
But:
When you are creating a component like mgfinancewindow which creates a JFrame inside, most of the times it's better to extend from JFrame and then you can create an object from it and call the setVisible method on it in the main method of your program or so. It's better not to call setVisible inside that component, because in another classes sometimes you want to create and initialize the mgfinancewindow but you don't want to make it visible immediately.
Another hints:
According to Java Coding Conventions:
Your class names must follow the CamelCase style.
Variable names must follow the camelCase (first letter in lower-case) style.
You may want to take a look at other java coding conventions here.

How to open a new JPanel with a JButton?

I am trying to code a program with multiple screens, however, I do not want to use tabbed panes. I have looked at using multiple JPanels with the card layout and the methods are simply not working. What I need to be able to do is load the new JPanel when a button is clicked. Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class IA extends JFrame {
private JPanel contentPane;
private JPanel home;
private JPanel clients;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IA frame = new IA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public IA() {
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(new CardLayout(0, 0));
JPanel home = new JPanel();
contentPane.add(home, "name_714429679706141");
home.setLayout(null);
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
btnClients.setBounds(160, 108, 89, 23);
home.add(btnClients);
JPanel clients = new JPanel();
contentPane.add(clients, "name_714431450350356");
clients.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clients.setVisible(false);
home.setVisible(true);
}
});
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
}
}
The problem is that you have duplicate variables home and clients .
The folllowing is your modified code to fix that, with comments on the changed lines (five lines total) :
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class IA extends JFrame {
private final JPanel contentPane;
// private final JPanel home; // REMOVED
// private JPanel clients; // REMOVED
/**
* Launch the application.
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IA frame = new IA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public IA() {
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(new CardLayout(0, 0));
final JPanel home = new JPanel();
contentPane.add(home, "name_714429679706141");
home.setLayout(null);
final JPanel clients = new JPanel(); // MOVED UP
contentPane.add(clients, "name_714431450350356"); // MOVED UP
clients.setLayout(null); // MOVED UP
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
btnClients.setBounds(160, 108, 89, 23);
home.add(btnClients);
JButton btnHome = new JButton("Home");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
clients.setVisible(false);
home.setVisible(true);
}
});
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
}
}
I would take a look at this post, however I have a feeling you'll need to use a actionlistener to get this done...
Java Swing. Opening a new JPanel from a JButton and making the buttons pretty
I would of left this as a comment but apparently you need 50 rep for that...
This link might be more helpful.. How to open a new window by clicking a button
When the following code is invoked the clients variable equals to null.
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
Write this:
JPanel clients = new JPanel();
contentPane.add(clients, "name_714431450350356");
clients.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
before you add the Action Listener

How can activate another gui class with JButton

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);

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.

Scrollbar not getting created/ table not shown

I'm writing a program where there is a JTable to be created (Which I'm able to). But I want to add a scroll bar to it. Below is my code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
static DefaultTableModel model = new DefaultTableModel();
static JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.add(new JScrollPane(table));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
table.setBounds(10, 131, 516, 178);
contentPane.add(table);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
When I run the above program, the table frame is also not displayed. But when I remove frame.add(new JScrollPane(table));, it is displaying the table in the JTable area, but there is no scrollbar in it.
Please let me know how can I get a scrollbar in the table and display the data correctly.
Thanks
At first don't use null layout, please read here.
frame.add(new JScrollPane(table)); this scroll pane is not displaying because in null layout each component needs to have bounds. Try below code. I just changed static variables to instance variables. And added scrollpane in to the constructor.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
private DefaultTableModel model = new DefaultTableModel();
private JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(10, 131, 516, 178);
contentPane.add(scroll);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}

Categories