Access JLabel from other class , Swingworker - java

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.

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

Open and Display File Data in JTextArea

I have run into a problem with what I thought was a pretty simple program. I simply want to use a GUI, click and button to display data in a text file. I seem to be close but am running into a problem I do not understand. If I leave the code the way it is here I get the error that highScores is not declared (symbol not found) for line 72. But if I try to declare highSchores the I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown" for line 69. Any idea what I am doing wrong and how I can fix it?
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class tetrisScores extends JFrame{
private JPanel contentPanel;
private JButton btnSearch;
private JButton btnLoad;
private JButton btnSort;
private JRadioButton firstSort;
private JRadioButton secondSort;
private JTextField searchInput;
private JTextArea output;
private String[] highScores;
private void add (Container con, Component widget, int left, int top, int width, int height) //creates variables for bounds
{
widget.setBounds(left, top, width, height); //sets setBounds to created variables
con.add(widget); //tells program container to use widget's bounds
}
tetrisScores()
{
contentPanel=(JPanel)getContentPane();
contentPanel.setLayout(null);
btnLoad = new JButton("Load File");
add(contentPanel, btnLoad, 10, 10, 360, 40);
searchInput = new JTextField("");
add(contentPanel, searchInput, 10, 60, 240, 40);
btnSearch = new JButton("Search");
add(contentPanel, btnSearch, 260, 60, 110, 40);
firstSort = new JRadioButton("Bubble Sort");
add(contentPanel, firstSort, 20, 110, 110, 40);
firstSort = new JRadioButton("Linear Sort");
add(contentPanel, firstSort, 140, 110, 110, 40);
btnSearch = new JButton("Sort");
add(contentPanel, btnSearch, 260, 110, 110, 40);
output = new JTextArea("");
add(contentPanel, output, 10, 160, 360, 150);
output.setEditable(false);
setTitle("High Scores");
setSize(500,500);
setLocation(new Point (150,150));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
btnLoad.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent add)
{
OpenFile();
for (int j = 0; j<10;j++)
{
output.append(highScores[j] + "/n");
}
}
});
}
public String [] OpenFile() throws IOException
{
FileReader fr = new FileReader("tetrishighscore.txt");
BufferedReader scoreReader = new BufferedReader (fr);
int numbLines = 10;
String[] textData = new String [numbLines];
int i;
for (i=0; i < numbLines; i++)
{
textData[i] = scoreReader.readLine();
}
scoreReader.close();
return textData;
}
public static void main (String [] args)
{
new tetrisScores();
}
}
The OpenFile() method throws an IOException, but it is never caught.
I have made some modifications:
highScores could be declared as a List (so you don't have to give the number of lines in advance)
the Exception is caught
the line break character is "\n", not "/n"
Some more modifications could be made, but this should work:
import java.awt.Component;
import java.awt.Container;
import java.util.List;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class TetrisScores extends JFrame {
private JPanel contentPanel;
private JButton btnSearch;
private JButton btnLoad;
private JButton btnSort;
private JRadioButton firstSort;
private JRadioButton secondSort;
private JTextField searchInput;
private JTextArea output;
private List<String> highScores = new ArrayList<>();
private void add(Container con, Component widget, int left, int top, int width, int height) // creates variables for
// bounds
{
widget.setBounds(left, top, width, height); // sets setBounds to created variables
con.add(widget); // tells program container to use widget's bounds
}
TetrisScores() {
contentPanel = (JPanel) getContentPane();
contentPanel.setLayout(null);
btnLoad = new JButton("Load File");
add(contentPanel, btnLoad, 10, 10, 360, 40);
searchInput = new JTextField("");
add(contentPanel, searchInput, 10, 60, 240, 40);
btnSearch = new JButton("Search");
add(contentPanel, btnSearch, 260, 60, 110, 40);
firstSort = new JRadioButton("Bubble Sort");
add(contentPanel, firstSort, 20, 110, 110, 40);
firstSort = new JRadioButton("Linear Sort");
add(contentPanel, firstSort, 140, 110, 110, 40);
btnSearch = new JButton("Sort");
add(contentPanel, btnSearch, 260, 110, 110, 40);
output = new JTextArea("");
add(contentPanel, output, 10, 160, 360, 150);
output.setEditable(false);
setTitle("High Scores");
setSize(500, 500);
setLocation(new Point(150, 150));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent add) {
try {
OpenFile();
for (int j = 0; j < highScores.size(); j++) {
output.append(highScores.get(j) + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void OpenFile() throws IOException {
FileReader fr = new FileReader("tetrishighscore.txt");
BufferedReader scoreReader = new BufferedReader(fr);
String line;
while((line = scoreReader.readLine()) != null) {
highScores.add(line);
}
scoreReader.close();
}
public static void main(String[] args) {
new TetrisScores();
}
}

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

Actionlistener in JComboBox not working properly

So i got this Actionlistener (Check code below)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import java.awt.TextArea;
import javax.swing.JTextPane;
import java.awt.Component;
import java.awt.TextField;
import java.awt.Label;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.util.Arrays;
import javax.swing.JComboBox;
import java.awt.event.ActionEvent;
public class Frame extends Register {
private int TempInt;
JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run() {
try {
Frame window = new Frame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void windowClosing (WindowEvent e) {
JOptionPane.showMessageDialog(frame, "Programmet sparas och kommer nu stängas av");
System.exit(1);
}
/**
* Create the application.
*/
public Frame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 424);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final TextArea textArea = new TextArea();
textArea.setEditable(false);
textArea.setBounds(0, 105, 440, 243);
frame.getContentPane().add(textArea);
// Använd k.setBelopp beroende på vilken man väljer
String s = "";
int il = beraknaSaldo();
s = Integer.toString(il);
JTextPane saldoText = new JTextPane();
saldoText.setText(s);
saldoText.setEditable(false);
saldoText.setBounds(208, 354, 42, 22);
frame.getContentPane().add(saldoText);
final TextField beloppField = new TextField();
beloppField.setEditable(false);
beloppField.setBounds(120, 10, 102, 22);
frame.getContentPane().add(beloppField);
final TextField tidField = new TextField();
tidField.setEditable(false);
tidField.setBounds(255, 10, 102, 22);
frame.getContentPane().add(tidField);
Label saldoLabel = new Label("Saldo:");
saldoLabel.setBounds(162, 354, 40, 22);
frame.getContentPane().add(saldoLabel);
Label beloppLabel = new Label("Belopp:");
beloppLabel.setBounds(72, 10, 50, 22);
frame.getContentPane().add(beloppLabel);
Label tidLabel = new Label("Tid:");
tidLabel.setBounds(228, 10, 22, 22);
frame.getContentPane().add(tidLabel);
Label besökartypLabel = new Label("Bes\u00F6kartyp");
besökartypLabel.setBounds(0, 77, 62, 22);
frame.getContentPane().add(besökartypLabel);
Label beloppLabel_1 = new Label("Belopp");
beloppLabel_1.setBounds(122, 77, 62, 22);
frame.getContentPane().add(beloppLabel_1);
Label tidLabel_1 = new Label("Tid");
tidLabel_1.setBounds(246, 77, 22, 22);
frame.getContentPane().add(tidLabel_1);
Label lopnrLabel = new Label("L\u00F6pnummer");
lopnrLabel.setBounds(345, 77, 79, 22);
frame.getContentPane().add(lopnrLabel);
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Företag");
comboBox.addItem("Normal");
comboBox.addItem("Student");
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int kb = 0;
JComboBox<?> comboBox = (JComboBox<?>) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("Normal")) {
Register r = new Register();
Kund k = new Normal();
k.setBelopp(100);
k.setDatum("20:15");
r.regKund(k);
int tempbelopp = k.getBelopp();
String b = Integer.toString(tempbelopp);
beloppField.setText(b);
kb = kb + 100;
tidField.setText("20:15");
textArea.append(r.getLista());
}
else if(selected.toString().equals("Student")) {
Register r = new Register();
Kund k = new Normal();
k=new Student();
k.setBelopp(50);
k.setDatum("20:16");
beloppField.setText("100");
tidField.setText("20:15");
if( kb >=50)
r.regKund(k);
kb = kb - 50;
textArea.append("Det finns inga cash, student reggades ej!" + "\n");
}
else if(selected.toString().equals("Företag")) {
Register r = new Register();
Kund k = new Normal();
k.setBelopp(0);
k.setDatum("20:17");
k.setLopnummer(r.getLopnummer());
r.regKund(k);
// Den skriver ut samma skit ändra det
textArea.append(r.getLista());
textArea.append("Kassan har nu "+kb+" kr" + "\n");
}
}
});
comboBox.setToolTipText("Välj vilken typ av Kund du är");
comboBox.setRenderer(new MyComboBoxRenderer("Välj..."));
comboBox.setSelectedIndex(-1);
comboBox.setBounds(171, 46, 97, 22);
frame.getContentPane().add(comboBox);
}
}
class MyComboBoxRenderer extends JLabel implements ListCellRenderer<Object> {
private String title;
public MyComboBoxRenderer(String newTitle) {
title = newTitle;
}
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean hasFocus) {
if (index == -1 && value == null) setText(title );
else setText(value.toString());
return this;
}
}
And it gives me error cause of this line comboBox.setSelectedIndex(-1);is there any way to change it. Since what it does it sets the comboBox defult text to "Välj..." (Which means choose in swedish) i would like to keep this without removing it. When i remove that line the program works perfectly.
When setSelectedIndex is called this statement should throw an NPE (not tested)
Object selected = comboBox.getSelectedItem();
since nothing is selected. You could simply move the setSelectedIndex statement before the ActionListener is registered with the combobox

Saving the added String item to ComboBox

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.

Categories