Rename file/directory using JFileChooser() and JButton() - java

I'm trying to rename file or directory using JFileChooser() and JButton(). But it gives me a "NullPointer exeption" in line 81 where I have
action listener
// button action
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newFileName = textField.getText();
// exeption is here!!!
File oldFile = new File(fileChooser.getSelectedFile(), null);
File newFileOrDirectoryName = new File(newFileName);
if (oldFile.renameTo(newFileOrDirectoryName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
});
I have to select some file or directory from my FileChooser(), then write new name for file or directory in TextField() and then push the Button() to rename it.Can you say where I go wrong and how to solve this problem.
This is a full code:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFileChooser;
public class App {
private JFrame frame;
private JTextField textField;
private JFileChooser fileChooser;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App window = new App();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public App() {
initialize();
}
public void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Tahoma", Font.BOLD, 14));
frame.setBounds(100, 100, 539, 469);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.getContentPane().setBackground(new Color(255, 246, 143));
JLabel label = new JLabel("Rename file or package");
label.setFont(new Font("Tahoma", Font.BOLD, 14));
label.setHorizontalAlignment(SwingConstants.LEFT);
label.setBounds(10, 0, 302, 32);
frame.getContentPane().add(label);
JLabel label_1 = new JLabel("New file/package name");
label_1.setHorizontalAlignment(SwingConstants.LEFT);
label_1.setFont(new Font("Tahoma", Font.BOLD, 14));
label_1.setBounds(10, 358, 194, 25);
frame.getContentPane().add(label_1);
textField = new JTextField();
textField.setBounds(10, 387, 179, 32);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton button = new JButton("Rename");
button.setFont(new Font("Tahoma", Font.BOLD, 14));
button.setBounds(199, 384, 151, 34);
button.addActionListener(null);
frame.getContentPane().add(button);
fileChooser = new JFileChooser();
fileChooser.setBounds(10, 51, 505, 289);
frame.getContentPane().add(fileChooser);
// button action
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newFileName = textField.getText();
File oldFile = new File(fileChooser.getSelectedFile(), null);
File newFileOrDirectoryName = new File(newFileName);
if (oldFile.renameTo(newFileOrDirectoryName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
});
}
}

It's because you're passing null to the File constructor at line 81, which give a NullPointerException when passed null. This can be read in the documentation here.
I think the solution is to remove the 'new File' part and replace it by:
File oldFile = fileChooser.getSelectedFile();
The bug was actually quite easy to see by pasting the code into IntelliJ:

Related

Calculator Coding Errors. Please correct it

I have tried to code a simple calculator using GUI in java but got stuck with this code and repeatedly getting a message of 'ENTER VALID NUMBERS' .I'm open to suggestions. Suggest the possible corrections in my code.I think I have wrongly used the try and check the exception feature of the java.
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.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.SwingConstants;
public class FIRSTCALC {
private JFrame frame;
private JTextField txtfield1;
private JTextField txtfield2;
private JTextField textfieldans;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FIRSTCALC window = new FIRSTCALC();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FIRSTCALC() {
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);
txtfield1 = new JTextField();
txtfield1.setHorizontalAlignment(SwingConstants.LEFT);
txtfield1.setText("ENTER NUMBER 1 : ");
txtfield1.setBounds(28, 11, 178, 68);
frame.getContentPane().add(txtfield1);
txtfield1.setColumns(10);
txtfield2 = new JTextField();
txtfield2.setHorizontalAlignment(SwingConstants.LEFT);
txtfield2.setText("ENTER NUMBER 2 : ");
txtfield2.setBounds(228, 11, 175, 68);
frame.getContentPane().add(txtfield2);
txtfield2.setColumns(10);
JButton btnNewButton = new JButton("ADD");
btnNewButton.setToolTipText("TO ADD NUMBERS");
btnNewButton.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,sum;
try
{
num1=Integer.parseInt(txtfield1.getText());
num2=Integer.parseInt(txtfield2.getText());
sum=num1+num2;
textfieldans.setText(Integer.toString(sum));
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, "ENTER VALID NUMBER");
}
}
});
btnNewButton.setBounds(61, 121, 120, 42);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("SUBTRACT");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,sum;
try
{
num1=Integer.parseInt(txtfield1.getText());
num2=Integer.parseInt(txtfield2.getText());
sum=num1-num2;
textfieldans.setText(Integer.toString(sum));
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, "ENTER VALID NUMBER");
}
}
});
btnNewButton_1.setToolTipText("TO SUBTRACT NUMBERS");
btnNewButton_1.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton_1.setBounds(251, 121, 128, 42);
frame.getContentPane().add(btnNewButton_1);
JLabel lblNewLabel = new JLabel("THE ANSWER IS :");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Sitka Text", Font.BOLD, 18));
lblNewLabel.setBounds(28, 192, 193, 58);
frame.getContentPane().add(lblNewLabel);
textfieldans = new JTextField();
textfieldans.setBounds(251, 196, 109, 48);
frame.getContentPane().add(textfieldans);
textfieldans.setColumns(10);
}
}
You are obviously getting an exception because you are appending or adding the entered number to the text already contained within one of the JTextFields. This would generate a NumberFormatException when trying to parse the string contained within JTextField to a Integer value with the Integer.parseInt() method. If anything other than numerical digits are supplied then this exception would be thrown. You're just making the exception display a Message Box indicating to the User to "ENTER VALID NUMBER".
If you want to keep the text within you text field components then apply a Focus Listener to highlight the text currently in the component so that it gets overwritten when the User enters a number. Generally this pre-text is in a lighter gray color. Here is an example:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class FIRSTCALC {
private JFrame frame;
private JTextField txtfield1;
private JTextField txtfield2;
private JTextField textfieldans;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FIRSTCALC window = new FIRSTCALC();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FIRSTCALC() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setAlwaysOnTop(true);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtfield1 = new JTextField("Enter First Number");
txtfield1.setForeground(Color.lightGray);
// Add a Focus Listener to txtfield1
txtfield1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfield1.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
txtfield1.setForeground(Color.black);
}
});
txtfield1.setHorizontalAlignment(SwingConstants.CENTER);
txtfield1.setBounds(28, 11, 178, 68);
txtfield1.setColumns(10);
frame.getContentPane().add(txtfield1);
txtfield2 = new JTextField("Enter Second Number");
txtfield2.setForeground(Color.lightGray);
// Add a Focus Listener to txtfield2
txtfield2.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfield2.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
txtfield2.setForeground(Color.black);
}
});
txtfield2.setHorizontalAlignment(SwingConstants.CENTER);
txtfield2.setBounds(228, 11, 175, 68);
txtfield2.setColumns(10);
frame.getContentPane().add(txtfield2);
JButton btnNewButton = new JButton("ADD");
btnNewButton.setToolTipText("TO ADD NUMBERS");
btnNewButton.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int num1, num2, sum;
try {
num1 = Integer.parseInt(txtfield1.getText());
num2 = Integer.parseInt(txtfield2.getText());
sum = num1 + num2;
textfieldans.setText(Integer.toString(sum));
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "<html><center>The following formula:<br><br>"
+ "<font size='4' color=red>" + txtfield1.getText() +
"</font> + <font size='4' color=red>"+ txtfield2.getText() +
"</font><br><br>contains invalid digits!</center></html>");
}
}
});
btnNewButton.setBounds(61, 121, 120, 42);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("SUBTRACT");
btnNewButton_1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int num1, num2, sum;
try {
num1 = Integer.parseInt(txtfield1.getText());
num2 = Integer.parseInt(txtfield2.getText());
sum = num1 - num2;
textfieldans.setText(Integer.toString(sum));
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "<html><center>The following formula:<br><br>"
+ "<font size='4' color=red>" + txtfield1.getText() +
"</font> - <font size='4' color=red>"+ txtfield2.getText() +
"</font><br><br>contains invalid digits!</center></html>");
}
}
});
btnNewButton_1.setToolTipText("TO SUBTRACT NUMBERS");
btnNewButton_1.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton_1.setBounds(251, 121, 128, 42);
frame.getContentPane().add(btnNewButton_1);
JLabel lblNewLabel = new JLabel("THE ANSWER IS :");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Sitka Text", Font.BOLD, 18));
lblNewLabel.setBounds(28, 192, 193, 58);
frame.getContentPane().add(lblNewLabel);
textfieldans = new JTextField();
textfieldans.setHorizontalAlignment(SwingConstants.CENTER);
textfieldans.setBounds(251, 196, 109, 48);
textfieldans.setColumns(10);
frame.getContentPane().add(textfieldans);
frame.setLocationRelativeTo(null);
}
}

Setting a JLabel visible on JRadioButton click

I tried setting JLabel to being visible only after I select a certain JRadioButton. The program is getting an error if I set lblNewLabel_1.setVisible(true) in the action performed of a radio button. It worked with the text field, but with this not. What can I do? Is it different with the label? Is there any advice someone can offer me?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Window;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.ButtonGroup;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Fereastra extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private final ButtonGroup buttonGroup = new ButtonGroup();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Fereastra frame = new Fereastra();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Fereastra() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 751, 565);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JTextArea textArea = new JTextArea();
textArea.setBounds(12, 13, 447, 251);
contentPane.add(textArea);
JRadioButton rdbtnNewRadioButton = new JRadioButton("Cautarea pe nivel");
rdbtnNewRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnNewRadioButton.isSelected())
{
textField.setVisible(false);
textField_1.setVisible(false);
}
}
});
buttonGroup.add(rdbtnNewRadioButton);
rdbtnNewRadioButton.setBounds(488, 55, 185, 25);
contentPane.add(rdbtnNewRadioButton);
JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("Cautarea in adancime");
rdbtnNewRadioButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(rdbtnNewRadioButton_1.isSelected())
{
textField.setVisible(true);
textField_1.setVisible(true);
}
else
{
textField.setVisible(false);
textField_1.setVisible(false);
}
}
});
buttonGroup.add(rdbtnNewRadioButton_1);
rdbtnNewRadioButton_1.setBounds(488, 96, 237, 25);
contentPane.add(rdbtnNewRadioButton_1);
JRadioButton rdbtnNewRadioButton_2 = new JRadioButton("Costul uniform");
rdbtnNewRadioButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnNewRadioButton_2.isSelected())
{
textField.setVisible(false);
textField_1.setVisible(false);
}
}
});
buttonGroup.add(rdbtnNewRadioButton_2);
rdbtnNewRadioButton_2.setBounds(488, 138, 127, 25);
contentPane.add(rdbtnNewRadioButton_2);
JRadioButton rdbtnNewRadioButton_3 = new JRadioButton("Adancime iterativa");
rdbtnNewRadioButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnNewRadioButton_3.isSelected())
{
textField_1.setVisible(true);
textField.setVisible(true);
}
else
{
textField_1.setVisible(false);
textField.setVisible(false);
}
}
});
buttonGroup.add(rdbtnNewRadioButton_3);
rdbtnNewRadioButton_3.setBounds(488, 179, 237, 25);
contentPane.add(rdbtnNewRadioButton_3);
JRadioButton rdbtnNewRadioButton_4 = new JRadioButton("Greedy");
rdbtnNewRadioButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnNewRadioButton_4.isSelected())
{
textField.setVisible(false);
textField_1.setVisible(false);
}
}
});
buttonGroup.add(rdbtnNewRadioButton_4);
rdbtnNewRadioButton_4.setBounds(488, 221, 127, 25);
contentPane.add(rdbtnNewRadioButton_4);
JLabel lblNewLabel = new JLabel("Alegeti:");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblNewLabel.setBounds(488, 13, 84, 33);
contentPane.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(402, 277, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
textField.setVisible(false);
textField_1 = new JTextField();
textField_1.setBounds(246, 277, 116, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_1.setVisible(false);
JLabel lblNewLabel_1 = new JLabel("Introduceti valorile dorite:");
lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblNewLabel_1.setBounds(22, 277, 212, 21);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setVisible(false);
}
}
It's because your label is declared in function context, put the declaration next the textbox declaration and it should work fine

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.

Access JLabel from other class , Swingworker

I have 2 classes. One class is for gui and the other class doing some staff.
The second class includes Swingworker. It searches some log files and take some sentence from there. Also in the gui there is a label which writes in Searching.. Please wait.. and when the second class finish the work, it should be changed to Searching is finished.. .
This label name is searchLabeland define in first class. It is private variable.
My purpose is : In the second class there is done method. Inside in this method, I want to do searchLabel.setText("blabla");
How can I do this ? I cannot access. Also doing public JLabel is not a solution I think.
You can easily find that part in the code with searcing /* PROBLEM IS IN HERE */ this string.
Here is the code
This is my gui class :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
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.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
public class mainGui extends JFrame {
private JPanel contentPane;
private JTextField userNametextField;
public static JLabel searchLabel,userNameWarningLabel,pathWarningLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainGui frame = new mainGui();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/4;
int y = (dim.height-h)/2;
frame.setLocation(x, y);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 455);
contentPane = new JPanel();
getContentPane().setLayout(null);
setTitle("Role Finding Script");
// Border border;
JLabel lblUsername = new JLabel(" Username :");
lblUsername.setFont(new Font("LucidaSans", Font.BOLD, 13));
lblUsername.setBounds(10, 53, 113, 30);
//Border border = BorderFactory.createRaisedSoftBevelBorder();
// border = BorderFactory.createEtchedBorder();
// lblUsername.setBorder(border);
getContentPane().add(lblUsername);
userNametextField = new JTextField();
userNametextField.setBounds(146, 53, 250, 30);
userNametextField.setFont(new Font("LucidaSans", Font.PLAIN, 13));
getContentPane().add(userNametextField);
userNametextField.setColumns(20);
JLabel lblRole = new JLabel(" Roles :");
lblRole.setFont(new Font("LucidaSans", Font.BOLD, 13));
lblRole.setBounds(10, 124, 113, 30);
// border = BorderFactory.createEtchedBorder();
// lblRole.setBorder(border);
getContentPane().add(lblRole);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setBounds(146, 124, 250, 30);
comboBox.addItem("VR_ANALYST1");
comboBox.addItem("VR_ANALYST2");
comboBox.addItem("VR_ANALYST3");
comboBox.addItem("VR_ANALYST4");
comboBox.addItem("VR_ANALYST5");
comboBox.addItem("VR_ANALYST6");
comboBox.addItem("VR_ANALYST7");
comboBox.addItem("VR_ANALYST8");
comboBox.addItem("VR_ANALYST9");
comboBox.addItem("VR_ANALYST10");
comboBox.addItem("VR_ANALYST11");
comboBox.addItem("VR_ANALYST12");
comboBox.setMaximumRowCount(6);
getContentPane().add(comboBox);
this.searchLabel = new JLabel("Searching.. Please wait..");
searchLabel.setFont(new Font("LucidaSans", Font.BOLD, 13));
searchLabel.setBounds(169, 325, 195, 30);
searchLabel.setVisible(false);
getContentPane().add(searchLabel);
JButton btnNewButton = new JButton("Show Me ");
btnNewButton.setFont(new Font("LucidaSans", Font.BOLD, 13));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(userNametextField.getText() == null || userNametextField.getText().equals("")){
userNameWarningLabel.setText("Please filled in the Username part.");
}else{
searchLabel.setVisible(true);
VolvoMain task = new VolvoMain();
task.execute();
}
}
});
btnNewButton.setBounds(188, 271, 126, 30);
getContentPane().add(btnNewButton);
JLabel lblPath = new JLabel(" Path :");
lblPath.setFont(new Font("Dialog", Font.BOLD, 13));
lblPath.setBounds(10, 195, 113, 30);
getContentPane().add(lblPath);
userNameWarningLabel = new JLabel("");
userNameWarningLabel.setBounds(156, 89, 227, 14);
userNameWarningLabel.setFont(new Font("Dialog", Font.ITALIC, 10));
userNameWarningLabel.setForeground(Color.red);
getContentPane().add(userNameWarningLabel);
JButton btnNewButton_1 = new JButton("...");
btnNewButton_1.setBounds(412, 195, 30, 30);
getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("+");
btnNewButton_2.setBounds(460, 195, 44, 30);
getContentPane().add(btnNewButton_2);
JLabel headerLabel = new JLabel("Find the Role");
headerLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
headerLabel.setHorizontalAlignment(SwingConstants.CENTER);
headerLabel.setBounds(94, 11, 358, 30);
headerLabel.setForeground(Color.red);
getContentPane().add(headerLabel);
pathWarningLabel = new JLabel("");
pathWarningLabel.setForeground(Color.RED);
pathWarningLabel.setFont(new Font("Dialog", Font.ITALIC, 10));
pathWarningLabel.setBounds(156, 236, 227, 14);
getContentPane().add(pathWarningLabel);
}
}
And this is the other class :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.SwingWorker;
public class VolvoMain extends SwingWorker{
private FileInputStream fstream;
private BufferedReader br;
private String username = "HALAA";
private String role = "VR_ANALYST";
private String firstLine = "";
private Pattern regex;
private List<String> stringList = new ArrayList<String>();
private File dir;
private mainGui mg = new mainGui();
//String reg = "\\t'AUR +(" + username + ") .*? /ROLE=\"(" + role + ")\".*$";
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground() throws Exception {
String fmt = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";
String reg = String.format(fmt, username, role);
regex = Pattern.compile(reg);
dir = new File(
"C:"+File.separator+"Documents and Settings"+File.separator+"sbx1807"+File.separator+"Desktop"+File.separator
+"Batu"+File.separator+"Deneme"+File.separator
);
File[] dirs = dir.listFiles();
String[] txtArray = new String[dirs.length];
int z=0;
for (File file : dirs) {
if (file.isDirectory()) {
}else {
if(file.getAbsolutePath().endsWith(".log")){
txtArray[z] = file.getAbsolutePath();
System.out.println(file.getAbsolutePath());
z++;
}
}
int j = 0;
for(int i=0; i<txtArray.length; i++){
if(txtArray[i] != null && !txtArray[i].equals("")){
try{
fstream = new FileInputStream(txtArray[i]);
br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
/* parse strLine to obtain what you want */
if((j%2)== 0){
firstLine = strLine;
}
if(((j%2) != 0) && regex.matcher(strLine).matches()){
stringList.add(firstLine);
stringList.add(strLine);
}
publish(stringList.size());
j++;
}
publish(stringList.size());
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
for(int k=0; k<stringList.size(); k++){
System.out.println(stringList.get(k));
}
}
return null;
}
#Override
public void done() {
System.out.println("bitti");
// getSearchJLabel().setText("Searching is done..");
// mainGui m = new mainGui();
// m.searchLabel.setText("done");
}
}
Adjust your VolvoMain class so it takes a reference to the JLabel in its constructor. Store this in a private final field and you can use this in the done() method.
public class VolvoMain extends SwingWorker{
// ...
private final JLabel labelToUpdate;
public VolvoMain(JLabel labelToUpdate) {
this.labelToUpdate = labelToUpdate;
}
// ...
#Override
public void done() {
// Update labelToUpdate here
}
The done() method will be invoked on the Event Dispatch Thread, so it will be safe to adjust the label text directly.

Categories