Saving the added String item to ComboBox - java

I am new to Java and Swing and I couldn't find a solution to the problem I have. I have a GUI which can add items to a combobox. I am trying to keep the added items in the combobox after the GUI is shut down and have the newly added items when it's launched again. Is there any easy way to do this?
Here is the code for the GUI:
package GUI1;
import java.awt.BorderLayout;
public class OnurComboBox extends JDialog implements
ActionListener, ItemListener {
private final JPanel contentPanel = new JPanel();
private JComboBox comboBox = null;
private int comnum;
public String combo;
// final String[] theOptions = {
// "Option 1", "Option 2",
// "Option 3", "Option 4",
// "Option 5", "Option 6"
// };
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
OnurComboBox dialog = new OnurComboBox();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public OnurComboBox() {
setTitle("Choose an Option");
setSize(325, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
JDesktopPane desktopPane = new JDesktopPane();
getContentPane().add(desktopPane, BorderLayout.CENTER);
JButton btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The item selected is: " + combo);
System.exit(0);
}
});
btnOk.setBounds(66, 153, 89, 23);
desktopPane.add(btnOk);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnCancel.setBounds(165, 153, 89, 23);
desktopPane.add(btnCancel);
// final JComboBox comboBox = new JComboBox(theOptions);
Vector comboBoxItems=new Vector();
comboBoxItems.add("A");
comboBoxItems.add("B");
comboBoxItems.add("C");
comboBoxItems.add("D");
comboBoxItems.add("E");
final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
final JComboBox comboBox = new JComboBox(model);
comboBox.setBounds(10, 34, 187, 23);
comboBox.setSelectedIndex(-1);
comboBox.addItemListener(this);
desktopPane.add(comboBox);
comboBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
combo = (String)comboBox.getSelectedItem();
comnum = comboBox.getSelectedIndex();
textField.setText(combo);
}
});
textField = new JTextField();
textField.setBounds(10, 228, 187, 23);
desktopPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(10, 103, 187, 23);
desktopPane.add(textField_1);
textField_1.setColumns(10);
JTextPane txtpnSelected = new JTextPane();
txtpnSelected.setEditable(false);
txtpnSelected.setText("Item Selected:");
txtpnSelected.setBounds(10, 202, 89, 23);
desktopPane.add(txtpnSelected);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!textField_1.getText().equals("")){
int a = 0;
for(int i = 0; i < comboBox.getItemCount(); i++){
if(comboBox.getItemAt(i).equals(textField_1.getText())){
a = 1;
break;
}
}
if (a == 1)
JOptionPane.showMessageDialog(null,"Combobox already has this item.");
else
comboBox.addItem(textField_1.getText());
JOptionPane.showMessageDialog(null,"Item added to Combobox");
}
else{
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box");
}
}
});
btnAdd.setBounds(207, 103, 92, 23);
desktopPane.add(btnAdd);
JTextPane txtpnEnterTheOption = new JTextPane();
txtpnEnterTheOption.setText("Enter the new option:");
txtpnEnterTheOption.setEditable(false);
txtpnEnterTheOption.setBounds(10, 80, 131, 23);
desktopPane.add(txtpnEnterTheOption);
JButton btnRemove = new JButton("Remove");
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (comboBox.getItemCount() > 0){
comboBox.removeItemAt(comnum);
JOptionPane.showMessageDialog(null,"Item removed");}
else
JOptionPane.showMessageDialog(null,"Item not available");
}
});
btnRemove.setBounds(207, 34, 92, 23);
desktopPane.add(btnRemove);
JTextPane txtpnSelectAnItem = new JTextPane();
txtpnSelectAnItem.setText("Select an item from the list or add a new option");
txtpnSelectAnItem.setBounds(10, 3, 289, 20);
desktopPane.add(txtpnSelectAnItem);
setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox combo = (JComboBox) e.getSource();
// int index = combo.getSelectedIndex();
// display.setIcon(new ImageIcon(
// ClassLoader.getSystemResource(images[index])));
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
The edited and working code, which does the job, with the great help of "Alya'a Gamal":
package GUI1;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JDesktopPane;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JTextField;
import javax.swing.JTextPane;
public class OnurComboBox1 extends JDialog implements
ActionListener, ItemListener {
private final JPanel contentPanel = new JPanel();
private JComboBox comboBox = null;
private int comnum;
public String combo;
private JTextField textField;
private JTextField textField_1;
static String filePath = "t.txt";/////this text file have
// private PrintWriter out;
// private BufferedReader input;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
OnurComboBox1 dialog = new OnurComboBox1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
* #throws IOException
*/
public OnurComboBox1() throws IOException {
BufferedReader input = new BufferedReader(new FileReader(filePath));
final PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("t.txt", true)));
setTitle("Choose an Option");
setSize(325, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
JDesktopPane desktopPane = new JDesktopPane();
getContentPane().add(desktopPane, BorderLayout.CENTER);
JButton btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The item selected is: " + combo);
out.close();/////to close the text file
System.exit(0);
}
});
btnOk.setBounds(66, 153, 89, 23);
desktopPane.add(btnOk);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnCancel.setBounds(165, 153, 89, 23);
desktopPane.add(btnCancel);
List<String> strings = new ArrayList<String>();
try {
String line = null;
try {
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
try {
input.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
String[] lineArray = strings.toArray(new String[]{});
final DefaultComboBoxModel model = new DefaultComboBoxModel(lineArray);
final JComboBox comboBox = new JComboBox(model);
comboBox.setBounds(10, 34, 187, 23);
comboBox.setSelectedIndex(-1);
comboBox.addItemListener(this);
desktopPane.add(comboBox);
comboBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
combo = (String)comboBox.getSelectedItem();
comnum = comboBox.getSelectedIndex();
textField.setText(combo);
}
});
textField = new JTextField();
textField.setBounds(10, 228, 187, 23);
desktopPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(10, 103, 187, 23);
desktopPane.add(textField_1);
textField_1.setColumns(10);
JTextPane txtpnSelected = new JTextPane();
txtpnSelected.setEditable(false);
txtpnSelected.setText("Item Selected:");
txtpnSelected.setBounds(10, 202, 89, 23);
desktopPane.add(txtpnSelected);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!textField_1.getText().equals("")){
int a = 0;
for(int i = 0; i < comboBox.getItemCount(); i++){
if(comboBox.getItemAt(i).equals(textField_1.getText())){
a = 1;
break;
}
}
if (a == 1)
JOptionPane.showMessageDialog(null,"Combobox already has this item.");
else
comboBox.addItem(textField_1.getText());
out.println(textField_1.getText());////this will add the new value in the text file
JOptionPane.showMessageDialog(null,"Item added to Combobox");
}
else{
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box");
}
}
});
btnAdd.setBounds(207, 103, 92, 23);
desktopPane.add(btnAdd);
JTextPane txtpnEnterTheOption = new JTextPane();
txtpnEnterTheOption.setText("Enter the new option:");
txtpnEnterTheOption.setEditable(false);
txtpnEnterTheOption.setBounds(10, 80, 131, 23);
desktopPane.add(txtpnEnterTheOption);
JButton btnRemove = new JButton("Remove");
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (comboBox.getItemCount() > 0){
comboBox.removeItemAt(comnum);
JOptionPane.showMessageDialog(null,"Item removed");}
else
JOptionPane.showMessageDialog(null,"Item not available");
}
});
btnRemove.setBounds(207, 34, 92, 23);
desktopPane.add(btnRemove);
JTextPane txtpnSelectAnItem = new JTextPane();
txtpnSelectAnItem.setText("Select an item from the list or add a new option");
txtpnSelectAnItem.setBounds(10, 3, 289, 20);
desktopPane.add(txtpnSelectAnItem);
setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox combo = (JComboBox) e.getSource();
// int index = combo.getSelectedIndex();
// display.setIcon(new ImageIcon(
// ClassLoader.getSystemResource(images[index])));
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

You can use text file to read and write from it
String filePath = "t.txt";/////this text file have
1- create text file and write your Vectot (A,B,C,D) each one in separated line on it
2-create two variables, one to read the text
BufferedReader input = new BufferedReader(new FileReader(filePath));
and the second to write on the file the value will be add :
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("t.txt", true)));
3- read this file in your comboBox , like that :
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filePath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
final DefaultComboBoxModel model = new DefaultComboBoxModel(lineArray);
final JComboBox comboBox = new JComboBox(model);
4- In btnAdd button Actionlistner add:
out.println(textField_1.getText());////this will add the new value in the text file
5- In btnOk button Actionlistner add:
out.close();/////to close the text file
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
class OnurComboBox extends JDialog implements
ActionListener, ItemListener {
private final JPanel contentPanel = new JPanel();
private JComboBox comboBox = null;
private int comnum;
public String combo;
// final String[] theOptions = {
// "Option 1", "Option 2",
// "Option 3", "Option 4",
// "Option 5", "Option 6"
// };
private JTextField textField;
private JTextField textField_1;
String filePath = "t.txt";
BufferedReader input = new BufferedReader(new FileReader(filePath));
public static PrintWriter out;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("t.txt", true)));
} catch (Exception e) {
}
try {
OnurComboBox dialog = new OnurComboBox();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public OnurComboBox() throws FileNotFoundException, IOException {
setTitle("Choose an Option");
setSize(325, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
JDesktopPane desktopPane = new JDesktopPane();
getContentPane().add(desktopPane, BorderLayout.CENTER);
JButton btnOk = new JButton("OK");
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The item selected is: " + combo);
out.close();
System.exit(0);
}
});
btnOk.setBounds(66, 153, 89, 23);
desktopPane.add(btnOk);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnCancel.setBounds(165, 153, 89, 23);
desktopPane.add(btnCancel);
// final JComboBox comboBox = new JComboBox(theOptions);
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filePath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
final DefaultComboBoxModel model = new DefaultComboBoxModel(lineArray);
final JComboBox comboBox = new JComboBox(model);
comboBox.setBounds(10, 34, 187, 23);
comboBox.setSelectedIndex(-1);
comboBox.addItemListener(this);
desktopPane.add(comboBox);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
combo = (String) comboBox.getSelectedItem();
comnum = comboBox.getSelectedIndex();
textField.setText(combo);
}
});
textField = new JTextField();
textField.setBounds(10, 228, 187, 23);
desktopPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(10, 103, 187, 23);
desktopPane.add(textField_1);
textField_1.setColumns(10);
JTextPane txtpnSelected = new JTextPane();
txtpnSelected.setEditable(false);
txtpnSelected.setText("Item Selected:");
txtpnSelected.setBounds(10, 202, 89, 23);
desktopPane.add(txtpnSelected);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!textField_1.getText().equals("")) {
int a = 0;
for (int i = 0; i < comboBox.getItemCount(); i++) {
if (comboBox.getItemAt(i).equals(textField_1.getText())) {
a = 1;
break;
}
}
if (a == 1) {
JOptionPane.showMessageDialog(null, "Combobox already has this item.");
} else {
comboBox.addItem(textField_1.getText());
}
out.println(textField_1.getText());
JOptionPane.showMessageDialog(null, "Item added to Combobox");
} else {
JOptionPane.showMessageDialog(null, "Please enter text in the Text Box");
}
}
});
btnAdd.setBounds(207, 103, 92, 23);
desktopPane.add(btnAdd);
JTextPane txtpnEnterTheOption = new JTextPane();
txtpnEnterTheOption.setText("Enter the new option:");
txtpnEnterTheOption.setEditable(false);
txtpnEnterTheOption.setBounds(10, 80, 131, 23);
desktopPane.add(txtpnEnterTheOption);
JButton btnRemove = new JButton("Remove");
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (comboBox.getItemCount() > 0) {
comboBox.removeItemAt(comnum);
JOptionPane.showMessageDialog(null, "Item removed");
} else {
JOptionPane.showMessageDialog(null, "Item not available");
}
}
});
btnRemove.setBounds(207, 34, 92, 23);
desktopPane.add(btnRemove);
JTextPane txtpnSelectAnItem = new JTextPane();
txtpnSelectAnItem.setText("Select an item from the list or add a new option");
txtpnSelectAnItem.setBounds(10, 3, 289, 20);
desktopPane.add(txtpnSelectAnItem);
setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox combo = (JComboBox) e.getSource();
// int index = combo.getSelectedIndex();
// display.setIcon(new ImageIcon(
// ClassLoader.getSystemResource(images[index])));
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

Probably the easiest in your case is to write them to a file. Have a look at Commons IO, to make file reading and writing easier. The best way is to have a sort of initialisation method which will read the file, populate it from the file contents, and then display it.
Then, whenever you add something to the list, also write it to the file. That, or you could go for a database, or serialization of the ComboBox model, but file reading/writing would be the easiest, IMO.

Related

How do you select CSV file to perform calculations on based on user input?

I'm currently making a user-input based program on Java Eclipse that is supposed perform calculations on data from a local csv file the user selects. The GUI code below is the source code that I have been using to make the GUI for the program. While I have managed to create the GUI, I am having trouble with "combining" the code listed under "CSVReader," which is a class I created, with the code for the GUI so that the user can select the CSV file. The user is supposed to select this CSV file by typing its path name into the text field box on the GUI.
Any help would be appreciated
GUI CODE
//GUI CODE
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JTextField;
public class Frame1 {
private JFrame frame;
private JTextField textField;
private JTextField txtCountryChosen;
/**
* #wbp.nonvisual location=71,14
*/
private final JTextField Program = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Program.setText("Statistics Manager");
Program.setColumns(10);
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Submit file path");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String textFieldValue = textField.getText();
}
});
btnNewButton.setBounds(145, 48, 150, 25);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(116, 13, 200, 22);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton_1 = new JButton("Mean GDP");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(0, 154, 97, 25);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Mean GDP_per_capita");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_2.setBounds(250, 154, 170, 25);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Mean pop");
btnNewButton_3.setBounds(109, 154, 120, 25);
frame.getContentPane().add(btnNewButton_3);
txtCountryChosen = new JTextField();
txtCountryChosen.setBounds(42, 104, 116, 22);
frame.getContentPane().add(txtCountryChosen);
txtCountryChosen.setColumns(10);
JButton btnNewButton_4 = new JButton("Select country");
btnNewButton_4.setBounds(270, 103, 150, 25);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Print Results in Txt File");
btnNewButton_5.setBounds(131, 201, 200, 20);
frame.getContentPane().add(btnNewButton_5);
}
}
CSVReader
//CSVREADER
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class CSVReader {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter file path name");
String file_path_name = scan.nextLine();
System.out.println(file_path_name);
String path= file_path_name;
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while((line = br.readLine()) !=null){
String[] values = line.split(",");
System.out.println("Country: " + values[0] + ", Year: " + values[2] + ", GDP: " + values[6] + ", GDP_per_capita: " + values[12] + ", Population: " + values[10]);
/*PrintStream myconsole= new PrintStream(new File("E://java.txt"));
System.setOut(myconsole);
myconsole.print(path);*/
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

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

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

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