InvokeLater not outputting updating value - java

I'm using invokelater to update a value on button click, but the value is only changing when I run another instance of the GUI. I'm running the invokelater method outside the main method so I'm not sure why the value won't update. Any help is appreciated.
private void threadStart() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
testLabel.setText(CN);
}
});
}
I'm using the created method here:
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadStart();
String line;
BufferedWriter bw = null;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
etc...
You can view the full class here:
import java.awt.EventQueue;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
import javax.naming.ldap.LdapName;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Color;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTextArea;
import javax.swing.JTable;
public class MISControlPanel {
JFrame frame;
static JTextField textField;
private JTextField textField_1;
final JTextArea textArea = new JTextArea();
JLabel selectedComputerFromAD = new JLabel("testing");
String sCurrentLine = null;
String CN = null;
JLabel testLabel = new JLabel("test");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MISControlPanel window = new MISControlPanel();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* #throws IOException
*
* #wbp.parser.entryPoint
*/
public MISControlPanel() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
*
* #throws IOException
*/
private void initialize() throws IOException {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.getContentPane().setForeground(Color.RED);
frame.setBounds(100, 100, 658, 618);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setTitle("MIS Advanced Computerers");
frame.setResizable(false);
FileWriter fw = new FileWriter("C:\\Users\\anoc5f\\Desktop\\Output.txt");
File tempFile = new File("myTempFile.txt");
JButton searchComputerButton = new JButton("Search");
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadStart();
String line;
BufferedWriter bw = null;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String s = null;
Process p = null;
/*
* try { // p = Runtime.getRuntime().exec(
* "cmd /c start c:\\computerQuery.bat computerName"); } catch
* (IOException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); }
*/
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
// textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(
ldapName.size() - 1).getValue();
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
}
});
try (BufferedReader br = new BufferedReader(new FileReader(
"resultofbatch.txt"))) {
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
String[] tokens = PATTERN.split(","); // This will return
// you a array,
// containing the
// string array
// splitted by what
// you write inside
// it.
// should be in your case the split, since they are
// seperated by ","
// System.out.println(sCurrentLine);
CN = sCurrentLine.split("CN=", -1)[1].split(",", -1)[0];
System.out.println(CN);
testLabel.setText(CN);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// SwingUtilities.invokeLater(updateCN());
searchComputerButton.setBounds(419, 19, 89, 20);
frame.getContentPane().add(searchComputerButton);
textField = new JTextField();
textField.setBounds(285, 19, 124, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblComputerName = new JLabel("Computer Name:");
lblComputerName.setForeground(Color.BLACK);
lblComputerName.setFont(new Font("Tahoma", Font.BOLD, 14));
lblComputerName.setBounds(159, 13, 124, 29);
frame.getContentPane().add(lblComputerName);
JLabel lblSelectedComputer = new JLabel("Selected Computer:");
lblSelectedComputer.setFont(new Font("Tahoma", Font.BOLD, 14));
lblSelectedComputer.setBounds(205, 78, 143, 30);
frame.getContentPane().add(lblSelectedComputer);
java.net.InetAddress localMachine = null;
try {
localMachine = java.net.InetAddress.getLocalHost();
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
textArea.setBackground(Color.GRAY);
textArea.setForeground(Color.WHITE);
textArea.setFont(textArea.getFont().deriveFont(Font.BOLD));
textArea.setBounds(10, 387, 632, 191);
textArea.setEditable(false); // might cause design view not to come up
frame.getContentPane().add(textArea);
JButton btnNewButton = new JButton("SSO REPAIR");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton.setBounds(36, 183, 132, 23);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("Batch File Fixes");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
lblNewLabel.setBounds(53, 158, 115, 14);
frame.getContentPane().add(lblNewLabel);
JLabel lblIpAddress = new JLabel("IP Address:");
lblIpAddress.setFont(new Font("Tahoma", Font.BOLD, 14));
lblIpAddress.setBounds(261, 104, 102, 22);
frame.getContentPane().add(lblIpAddress);
JLabel label = null;
try {
label = new JLabel(Inet4Address.getLocalHost().getHostAddress()); // Get
// User
// ID
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
label.setFont(new Font("Tahoma", Font.BOLD, 14));
label.setForeground(Color.RED);
label.setBounds(349, 105, 99, 21);
frame.getContentPane().add(label);
JLabel lblPcCommunication = new JLabel("PC Communication");
lblPcCommunication.setFont(new Font("Tahoma", Font.BOLD, 12));
lblPcCommunication.setBounds(279, 158, 115, 14);
frame.getContentPane().add(lblPcCommunication);
JButton btnPingComputer = new JButton("PING");
btnPingComputer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnPingComputer.setBounds(306, 183, 64, 23);
frame.getContentPane().add(btnPingComputer);
JButton remoteAssistanceButton = new JButton(
"Remote Assistance by PC Name");
remoteAssistanceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
remoteAssistanceButton.setBounds(215, 251, 246, 23);
frame.getContentPane().add(remoteAssistanceButton);
JButton btnPingIndefinetely = new JButton("PING INDEFINETELY");
btnPingIndefinetely.setBounds(260, 217, 156, 23);
frame.getContentPane().add(btnPingIndefinetely);
JButton btnRdcByIp = new JButton("RDC by IP Address");
btnRdcByIp.setBounds(261, 353, 156, 23);
frame.getContentPane().add(btnRdcByIp);
JButton btnRdcByName = new JButton("RDC by PC Name");
btnRdcByName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnRdcByName.setBounds(248, 319, 180, 23);
frame.getContentPane().add(btnRdcByName);
JLabel lblLoggedInOpid = new JLabel("Logged in OPID:");
lblLoggedInOpid.setFont(new Font("Tahoma", Font.BOLD, 14));
lblLoggedInOpid.setBounds(228, 127, 135, 20);
frame.getContentPane().add(lblLoggedInOpid);
JLabel lblNewLabel_1 = new JLabel(System.getProperty("user.name")
.toUpperCase());
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 14));
lblNewLabel_1.setForeground(Color.RED);
lblNewLabel_1.setBounds(348, 130, 86, 14);
frame.getContentPane().add(lblNewLabel_1);
JButton btnHiddenShare = new JButton("HIDDEN SHARE");
btnHiddenShare.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnHiddenShare.setBounds(484, 183, 132, 23);
frame.getContentPane().add(btnHiddenShare);
JLabel lblAdditionalTools = new JLabel("Tools");
lblAdditionalTools.setFont(new Font("Tahoma", Font.BOLD, 12));
lblAdditionalTools.setBounds(526, 157, 126, 20);
frame.getContentPane().add(lblAdditionalTools);
JButton btnNewButton_1 = new JButton("Remote Assistance by IP Address");
btnNewButton_1.setBounds(215, 285, 246, 23);
frame.getContentPane().add(btnNewButton_1);
JButton gpUpdate = new JButton("GP UPDATE");
gpUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
gpUpdate.setBounds(36, 217, 132, 23);
frame.getContentPane().add(gpUpdate);
JButton btnForced = new JButton("NURMED REG FIX");
btnForced.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnForced.setBounds(36, 251, 132, 23);
frame.getContentPane().add(btnForced);
JButton btnCleaConsoler = new JButton("CLEAR");
btnCleaConsoler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textArea.setText("");
}
});
btnCleaConsoler.setBounds(563, 353, 79, 23);
frame.getContentPane().add(btnCleaConsoler);
JLabel lblOpid = new JLabel("Find Computer by OPID:");
lblOpid.setFont(new Font("Tahoma", Font.BOLD, 14));
lblOpid.setBounds(104, 53, 180, 14);
frame.getContentPane().add(lblOpid);
textField_1 = new JTextField();
textField_1.setBounds(285, 50, 124, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnNewButton_2 = new JButton("Search");
btnNewButton_2.setBounds(419, 50, 89, 23);
frame.getContentPane().add(btnNewButton_2);
testLabel.setForeground(Color.RED);
testLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
testLabel.setBounds(358, 78, 150, 24);
frame.getContentPane().add(testLabel);
}
private void threadStart() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
testLabel.setText(CN);
}
});
}
}

Related

How to show the Oracle table list in a JTable?

So I am trying to build a CRUD app, I am able to perform all the operations in a console app and now I want to use the same methods in my GUI application. I have setup all the necessary fields and a table, the add button works and I can implement the others too! my question is how to work with the JTable?
Here is the code for my window builder. You can see that I have set columns for the tables too.
this is what the GUI looks like
package clientGUI;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import bus.Student;
import data.ConnectionDB;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class DbTester1 {
private JFrame frame;
private JTextField textID;
private JTextField textFN;
private JTextField txtLN;
private JTable table;
private JTable table_1;
ArrayList<Student> studentList= null;
String query = "" ;
Statement stmt = null;
ResultSet rs = null;
Student aStudent = null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
DbTester1 window = new DbTester1();
window.frame.setVisible(true);
}
});
}
public DbTester1() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 732, 695);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblID = new JLabel("ID");
lblID.setBounds(10, 11, 46, 14);
frame.getContentPane().add(lblID);
JLabel lblFN = new JLabel("FN");
lblFN.setBounds(11, 42, 57, 14);
frame.getContentPane().add(lblFN);
JLabel lblLN = new JLabel("LN");
lblLN.setBounds(10, 79, 46, 14);
frame.getContentPane().add(lblLN);
textID = new JTextField();
textID.setBounds(78, 8, 86, 20);
frame.getContentPane().add(textID);
textID.setColumns(10);
textFN = new JTextField();
textFN.setBounds(78, 39, 86, 20);
frame.getContentPane().add(textFN);
textFN.setColumns(10);
txtLN = new JTextField();
txtLN.setBounds(78, 76, 86, 20);
frame.getContentPane().add(txtLN);
txtLN.setColumns(10);
ArrayList<Student> studList = new ArrayList<Student>();
JButton btnAdd = new JButton("Add");
btnAdd.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Student aStudent = new Student(Integer.parseInt(textID.getText()) ,
textFN.getText(), txtLN.getText());
studList.add(aStudent);
}
});
btnAdd.setBounds(0, 103, 89, 23);
frame.getContentPane().add(btnAdd);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(174, 11, 250, 292);
frame.getContentPane().add(scrollPane);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"ID", "FN", "LN"
}
));
scrollPane.setViewportView(table);
table_1 = new JTable();
scrollPane.setColumnHeaderView(table_1);
JButton btnConnect = new JButton("Connect");
btnConnect.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
con = ConnectionDB.getConnection();
JOptionPane.showMessageDialog(null, "Connection
Established!");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "Connection failed!");
}
}
});
btnConnect.setBounds(0, 128, 89, 23);
frame.getContentPane().add(btnConnect);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnSearch.setBounds(0, 153, 89, 23);
frame.getContentPane().add(btnSearch);
JButton btnUpdate = new JButton("Update");
btnUpdate.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnUpdate.setBounds(0, 178, 89, 23);
frame.getContentPane().add(btnUpdate);
JButton btnRefresh = new JButton("Refresh");
btnRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
con = ConnectionDB.getConnection();
String id, fn, ln;
query = "select * from student";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
studentList = new ArrayList<Student> ();
while(rs.next())
{
id = rs.getString(1);
fn = rs.getString(2);
ln = rs.getString(3);
aStudent = new Student(Integer.parseInt(id) , fn, ln);
studentList.add(aStudent);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "Connection read
data!!!!!");
}
}
});
btnRefresh.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnRefresh.setBounds(0, 205, 89, 23);
frame.getContentPane().add(btnRefresh);
}
}

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

Cannot create JAR file-Main method not found

I'm trying to create a JAR of the given class.
I am using a tool called JARBuilder as Eclipse was of no help in creating JAR files.
When I try to create the JAR, it says that main method could be found, despite the fact that the main method is clearly defined.
Can someone please advise?
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Login extends JFrame {
private JPanel contentPane;
private JTextField textField_1;
private JTextField textField_2;
private String name;
private String address;
private int port;
private JTextField textField;
public Login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 348);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(158, 44, 72, 16);
contentPane.add(lblUsername);
textField_1 = new JTextField();
textField_1.setEditable(false);
textField_1.setBounds(135, 111, 116, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblServerIp = new JLabel("Server IP");
lblServerIp.setBounds(158, 96, 56, 16);
contentPane.add(lblServerIp);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_1.setText("122.15.200.115");
textField_2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent key) {
}
});
textField_2.setBounds(135, 162, 116, 22);
textField_2.setText("8000");
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblPort = new JLabel("Port");
lblPort.setBounds(174, 146, 56, 16);
contentPane.add(lblPort);
JButton btnLogin = new JButton("Login");
btnLogin.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
newWindow();
}
});
btnLogin.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
newWindow();
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnLogin.setBounds(145, 197, 97, 43);
contentPane.add(btnLogin);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent key) {
if(key.getKeyCode()==KeyEvent.VK_ENTER)
{
if(!(textField.getText().equals("")))
{
name=textField.getText();
address=textField_1.getText();
port=Integer.parseInt(textField_2.getText());
try {
Chat_window window=new Chat_window(name, address, port);
dispose();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
textField.setColumns(10);
textField.setBounds(135, 60, 116, 22);
contentPane.add(textField);
JLabel lblAuthorprashantPandey = new JLabel("Author:Prashant Pandey");
lblAuthorprashantPandey.setBounds(125, 253, 186, 16);
contentPane.add(lblAuthorprashantPandey);
}
public void newWindow(){
name=textField.getText();
address=textField_1.getText();
port=Integer.parseInt(textField_2.getText());
try {
Chat_window window=new Chat_window(name, address, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dispose();
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

How to connect two frames in Java?

I have three different frames:
welcome.java
Register.java
LoginForm.java
If I click on Login button login page must open(i.e LoginForm.java) and if I click on Register button register page must open
//welcome.java
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class welcome extends JFrame
{
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
welcome window = new welcome();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public welcome() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnLogIn = new JButton("LOG IN");
btnLogIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnLogIn.setBounds(200, 69, 117, 25);
frame.getContentPane().add(btnLogIn);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnRegister.setBounds(200, 138, 117, 25);
frame.getContentPane().add(btnRegister);
JLabel lblNewToSvk = new JLabel("New to SVK Polytechnic ?");
lblNewToSvk.setBounds(12, 143, 191, 15);
frame.getContentPane().add(lblNewToSvk);
}
}
.
`//LoginForm.java
import java.awt.EventQueue;
import javax.swing.JScrollPane;
public class LoginForm extends JPanel implements ItemListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField textField;
private JPasswordField pwdJjh;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginForm window = new LoginForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public LoginForm() {
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);
JLabel lblStudentLogin = new JLabel("Login ");
lblStudentLogin.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 30));
lblStudentLogin.setHorizontalAlignment(SwingConstants.CENTER);
lblStudentLogin.setBounds(94, 12, 265, 36);
frame.getContentPane().add(lblStudentLogin);
JLabel lblUserName = new JLabel("USER NAME");
lblUserName.setFont(new Font("Dialog", Font.BOLD, 15));
lblUserName.setBounds(12, 74, 111, 15);
frame.getContentPane().add(lblUserName);
textField = new JTextField();
textField.setFont(new Font("Dialog", Font.PLAIN, 15));
textField.setBounds(141, 70, 160, 22);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblPassword = new JLabel("PASSWORD");
lblPassword.setFont(new Font("Dialog", Font.BOLD, 15));
lblPassword.setBounds(12, 116, 111, 15);
frame.getContentPane().add(lblPassword);
pwdJjh = new JPasswordField();
pwdJjh.setFont(new Font("Dialog", Font.PLAIN, 15));
pwdJjh.setBounds(141, 114, 160, 22);
frame.getContentPane().add(pwdJjh);
JLabel lblUserType = new JLabel("USER TYPE");
lblUserType.setFont(new Font("Dialog", Font.BOLD, 15));
lblUserType.setBounds(12, 154, 111, 15);
frame.getContentPane().add(lblUserType);
JComboBox<String> cm = new JComboBox<String>();
cm.setBounds(141, 148, 160, 24);
cm.addItem("User");
cm.addItem("Admin");
cm.addItemListener(this);
setLayout(null);
frame.getContentPane().add(cm);
JButton btnLogin = new JButton("Login ");
btnLogin.setBounds(41, 199, 117, 25);
frame.getContentPane().add(btnLogin);
JButton btnCancle = new JButton("Cancel");
btnCancle.setBounds(209, 199, 117, 25);
frame.getContentPane().add(btnCancle);
}
#Override
public void itemStateChanged(ItemEvent arg0) {
// TODO Auto-generated method stub
}
}
.
//Register.java
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class Register {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register window = new Register();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Register() {
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);
JLabel lblRegisterForm = new JLabel("Register Form");
lblRegisterForm.setForeground(Color.BLUE);
lblRegisterForm.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 25));
lblRegisterForm.setBounds(119, 12, 209, 25);
frame.getContentPane().add(lblRegisterForm);
JLabel lblSelectTheUser = new JLabel("Select the user type");
lblSelectTheUser.setFont(new Font("Dialog", Font.BOLD, 15));
lblSelectTheUser.setBounds(22, 83, 192, 25);
frame.getContentPane().add(lblSelectTheUser);
JComboBox cb1 = new JComboBox();
cb1.setModel(new DefaultComboBoxModel(new String[] {"Student", "Lecturer", "Office staff", "HOD"}));
cb1.setBounds(213, 83, 151, 24);
frame.getContentPane().add(cb1);
}
public void setVisible(boolean b) {
// TODO Auto-generated method stub
}
public void setTitle(String string) {
// TODO Auto-generated method stub
}
public void setSize(int i, int j) {
// TODO Auto-generated method stub
}
public void setLocationRelativeTo(Object object) {
// TODO Auto-generated method stub
}
public void setDefaultCloseOperation(int exitOnClose) {
// TODO Auto-generated method stub
}
}
You can use
frame.setVisible(true);
to make a JFrame (form) visible.

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