I am looking for a way to save the users input from a jlist into a txt file. It's for a homework project. I have the program set up to take user input from a textfield, then it goes into the jlist once they hit the add button. The jlist has a defaultlistmodel on it, and I'm wondering if there is a way to create a save button and allow it to save the complete jlist into a .txt file.
Also, here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
public class i extends JFrame {
private JPanel contentPane;
private JTextField jTextField;
DefaultListModel ListModel = new DefaultListModel();
ArrayList<String> arr = new ArrayList <String>();
String str;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
i frame = new i();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public i() {
super("List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
jTextField = new JTextField();
jTextField.setBounds(15, 80, 168, 20);
contentPane.add(jTextField);
jTextField.setColumns(10);
final JList jList = new JList(ListModel);
jList.setBorder(new LineBorder(new Color(0, 0, 0)));
jList.setBounds(289, 54, 135, 197);
contentPane.add(jList);
JButton jButton = new JButton("Add");
jButton.setBounds(190, 79, 89, 23);
contentPane.add(jButton);
jButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String str=jTextField.getText();
ListModel.addElement(str);
jTextField.setText("");
arr.add(str);
System.out.println(arr);
}
});
JButton delete = new JButton("DELETE");
delete.setBounds(190, 162, 89, 23);
contentPane.add(delete);
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent k){
ListModel.removeElement(jList.getSelectedValue());
}
});
JButton btnUp = new JButton("UP");
btnUp.setBounds(190, 125, 89, 23);
contentPane.add(btnUp);
btnUp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int index = jList.getSelectedIndex();
if(index == -1){
JOptionPane.showMessageDialog(null, "Select something to move.");
} else if(index > 0) {
String temp = (String)ListModel.remove(index);
ListModel.add(index - 1, temp);
jList.setSelectedIndex(index -1);
}
}
});
JButton btnDown = new JButton("DOWN");
btnDown.setBounds(190, 196, 89, 23);
contentPane.add(btnDown);
btnDown.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e ){
int index = jList.getSelectedIndex();
if( index == -1 )
JOptionPane.showMessageDialog(null, "Select something to move.");
else if( index < ListModel.size() - 1 ){
String temp = (String)ListModel.remove( index );
ListModel.add( index + 1, temp );
jList.setSelectedIndex( index + 1 );
}
}
});
JLabel lblItems = new JLabel("Items:");
lblItems.setBounds(290, 37, 46, 14);
contentPane.add(lblItems);
JButton btnPrint = new JButton("PRINT");
btnPrint.setBounds(190, 228, 89, 23);
contentPane.add(btnPrint);
btnPrint.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
}
}
you need use File class to save your list in that
File file = new File("c:/test/myfile.txt");
now file's created and opened!
and for write some output to file
use Formatter Class:
public class CreateFile
{
private Formatter x;
void openFile()
{
try
{
x = new Formatter("c:/myfile.txt");
System.out.println("you created a file");
}
catch(Exception e)
{
System.err.println("error in opening file");
}
}
void addFile()
{
x.format("%s %s %s\n","20","Start","Today");
}
void closeFile()
{
x.close();
}
}
as you see,addFile method accept 3 String passed to write in the file
i passed "20" , "Start" , "Today"
you can use more/less than %s , and pass user input or a list in String to write in the file.
good luck
Related
package com.tools;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.AbstractListModel;
import java.awt.Color;
import javax.swing.JTextArea;
import java.awt.List;
import javax.swing.JScrollPane;
public class CleaningToolV2 {
private JFrame frame;
private JTextField folderName;
private JTextField date_from;
private JTextField date_to;
JRadioButton radio_max = new JRadioButton("max");
JRadioButton radio_png = new JRadioButton("png");
JRadioButton radio_psd = new JRadioButton("psd");
JRadioButton radio_tiff = new JRadioButton("tiff");
JComboBox<String> comboBox = new JComboBox<String>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
JTextArea textArea = new JTextArea();
ArrayList<File> selectedFiles = new ArrayList<File>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CleaningToolV2 window = new CleaningToolV2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public CleaningToolV2() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
CleaningToolV2 thisObj = this;
frame = new JFrame();
frame.setBounds(100, 100, 450, 539);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
String toDayDate = simpleDateFormat.format(new Date());
DefaultComboBoxModel<String> comboModel1 = new DefaultComboBoxModel<String>(new String[] {"Furn", "Unfurn"});
DefaultComboBoxModel<String> comboModel2 = new DefaultComboBoxModel<String>(new String[] {"Temp"});
comboBox.setModel(comboModel1);
comboBox.setBounds(20, 174, 145, 27);
frame.getContentPane().add(comboBox);
folderName = new JTextField();
folderName.setBounds(20, 53, 283, 26);
frame.getContentPane().add(folderName);
folderName.setColumns(10);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc=new JFileChooser(folderName.getText());
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int i=fc.showOpenDialog(frame);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
folderName.setText(filepath);
}
}
});
btnBrowse.setBounds(315, 53, 117, 29);
frame.getContentPane().add(btnBrowse);
JLabel label_ext = new JLabel("Extensions and File name token");
label_ext.setBounds(20, 111, 250, 16);
frame.getContentPane().add(label_ext);
radio_png.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
comboBox.setModel(comboModel1);
}
});
radio_png.setBounds(20, 139, 78, 23);
frame.getContentPane().add(radio_png);
radio_max.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
comboBox.setModel(comboModel2);
}
});
radio_max.setBounds(130, 139, 71, 23);
frame.getContentPane().add(radio_max);
JLabel label_folder = new JLabel("Select folder");
label_folder.setBounds(20, 25, 107, 16);
frame.getContentPane().add(label_folder);
JLabel lblSelectTimeFrame = new JLabel("Enter time frame (DD/MM/YYYY)");
lblSelectTimeFrame.setBounds(20, 235, 267, 16);
frame.getContentPane().add(lblSelectTimeFrame);
date_from = new JTextField();
date_from.setBounds(71, 263, 130, 26);
frame.getContentPane().add(date_from);
date_from.setColumns(10);
date_from.setText(toDayDate);
date_to = new JTextField();
date_to.setColumns(10);
date_to.setBounds(286, 263, 130, 26);
date_to.setText(toDayDate);
frame.getContentPane().add(date_to);
JLabel label_time_from = new JLabel("From :");
label_time_from.setBounds(20, 268, 57, 16);
frame.getContentPane().add(label_time_from);
JLabel label_time_to = new JLabel("To :");
label_time_to.setBounds(243, 268, 44, 16);
frame.getContentPane().add(label_time_to);
JButton btnClearAllFiles = new JButton("Clear All Files");
btnClearAllFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(File f:selectedFiles) {
f.delete();
}
thisObj.refreshList();
}
});
btnClearAllFiles.setBounds(184, 482, 117, 29);
frame.getContentPane().add(btnClearAllFiles);
radio_psd.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
comboBox.setModel(comboModel1);
}
});
radio_psd.setBounds(232, 139, 71, 23);
frame.getContentPane().add(radio_psd);
radio_tiff.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
comboBox.setModel(comboModel1);
}
});
radio_tiff.setBounds(333, 139, 71, 23);
frame.getContentPane().add(radio_tiff);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(radio_png);
bgroup.add(radio_max);
bgroup.add(radio_psd);
bgroup.add(radio_tiff);
radio_png.setSelected(true);
JLabel label_selected_files = new JLabel("Selected Files");
label_selected_files.setBounds(20, 318, 127, 16);
frame.getContentPane().add(label_selected_files);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(20, 346, 396, 124);
frame.getContentPane().add(scrollPane);
textArea.setEditable(false);
scrollPane.setViewportView(textArea);
JButton btnFilterFiles = new JButton("Filter Files");
btnFilterFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
thisObj.refreshList();
}
});
btnFilterFiles.setBounds(130, 313, 117, 29);
frame.getContentPane().add(btnFilterFiles);
}
public void refreshList() {
File folder = new File(folderName.getText());
File[] listOfFiles = folder.listFiles();
selectedFiles = new ArrayList<File>();
String fileNames = "";
String selectedItem = comboBox.getSelectedItem().toString().toLowerCase();
for (int i = 0; i < listOfFiles.length; i++) {
Date modified = new Date(listOfFiles[i].lastModified());
String modiDateString = simpleDateFormat.format(modified);
String from_text = date_from.getText();
String to_text = date_to.getText();
if (listOfFiles[i].isFile() && modiDateString.compareTo(from_text) >= 0 && modiDateString.compareTo(to_text) <= 0) {
String fileName = listOfFiles[i].getAbsoluteFile().getAbsolutePath();
String ext = this.getSelectedFileExt();
if(fileName.toLowerCase().endsWith("."+ext) && fileName.toLowerCase().indexOf("_"+selectedItem) > -1) {
fileNames += listOfFiles[i].getAbsoluteFile().getAbsolutePath() + "\n";
selectedFiles.add(listOfFiles[i]);
}
}
}
textArea.setText(fileNames);
}
private String getSelectedFileExt() {
String ext;
if(radio_max.isSelected()) {
ext = "max";
} else if(radio_psd.isSelected()) {
ext = "psd";
} else if(radio_tiff.isSelected()) {
ext = "tiff";
} else {
ext = "png";
}
return ext;
}
}
here it was deleting the files if i give exact folder location.
but what i am trying to get it is it has to search the directory which conrtains subfolders also
it has to search along the sub folders and delete the specified files (eg- file name will be
borrry_furn) which was specified in the dropdown
plz help me thanks in advance.
it has to search the directory which conrtains subfolders also it has to search along the sub folders
Your method to search a directory needs to be recursive.
Here is an example of a recursive method that lists the files in all the sub directories:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFile extends JFrame
implements ActionListener, Runnable
{
JTable table;
DefaultTableModel model;
JTextField path;
JLabel currentFile;
JButton getFiles;
int totalFiles;
int totalDirectories;
public TableFile()
{
path = new JTextField("C:\\java");
add(path, BorderLayout.PAGE_START );
getFiles = new JButton( "Get Files" );
getFiles.addActionListener( this );
add(getFiles, BorderLayout.LINE_START );
String[] columnNames = {"IsFile", "Name"};
model = new DefaultTableModel(columnNames, 0);
table = new JTable( model );
JScrollPane scrollPane = new JScrollPane( table );
add(scrollPane, BorderLayout.PAGE_END);
currentFile = new JLabel(" ");
// add(currentFile, BorderLayout.PAGE_END); // displays filename in label
}
public void actionPerformed(ActionEvent e)
{
model.setNumRows(0);
new Thread( this ).start();
table.requestFocusInWindow();
}
public void run()
{
totalFiles = 0;
totalDirectories = 0;
listFiles( new File( path.getText() ) );
System.out.println("Directories: " + totalDirectories);
System.out.println("Files : " + totalFiles);
}
private void listFiles(File dir)
{
updateTable( dir );
totalDirectories++;
System.out.println("Processing directory: " + dir);
// add a delay to demonstrate processing one directory at a time
try { Thread.sleep(500); }
catch(Exception e) {}
File[ ] entries = dir.listFiles( );
int size = entries == null ? 0 : entries.length;
for(int j = 0; j < size; j++)
{
if (entries[j].isDirectory( ))
{
listFiles( entries[j] );
}
else
{
updateTable( entries[j] );
currentFile.setText( entries[j].toString() );
totalFiles++;
}
}
}
private void updateTable(final File file)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
Vector<Object> row = new Vector<Object>(2);
row.addElement( new Boolean( file.isFile() ) );
row.addElement( file.toString() );
model.addRow( row );
int rowCount = table.getRowCount() - 1;
table.changeSelection(rowCount, rowCount, false, false);
}
});
}
public static void main(String[] args)
{
TableFile frame = new TableFile();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* 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() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.
At the moment, i have a table that has no row values when it is built, rows are added in after i click the add button. when i click the add button, it will add a row to the table and there are cells for the user to key in values. And then when i click the save button it will store each of the col value into an object. I just wanted to know if there is a more efficient way to do it instead of my if else.
package UI;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
public class TableManage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 4353951253754938210L;
private JPanel contentPane;
private JTable tablemanage;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TableManage frame = new TableManage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TableManage() {
#SuppressWarnings("unused")
DefaultTableModel manageModel;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
DefaultTableModel model=new DefaultTableModel(
new Object[][] {
},
new String[] {
"NAME", "AGE", "GENDER"
}
);
tablemanage = new JTable(model);
JScrollPane managementpane=new JScrollPane(tablemanage);
managementpane.setBounds(40, 11, 355, 118);
contentPane.add(managementpane);
JButton btnAdd = new JButton("ADD");
btnAdd.setBounds(40, 164, 89, 23);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.addRow(new Object [][] {{null, null,null}});
model.setValueAt(null,tablemanage.getRowCount()-1,0);
}
});
contentPane.add(btnAdd);
JButton btnRemove = new JButton("REMOVE");
btnRemove.setBounds(172, 164, 89, 23);
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(tablemanage.getSelectedRow()<0)
{
JOptionPane.showMessageDialog(null,"Select value To Remove");
}
else
{
model.removeRow(tablemanage.getSelectedRow());
}
}
});
contentPane.add(btnRemove);
JButton btnSave = new JButton("SAVE");
btnSave.setBounds(306, 164, 89, 23);
contentPane.add(btnSave);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int nu=tablemanage.getRowCount();
int co=tablemanage.getColumnCount();
tablemanage.getSelectionModel().clearSelection();
int i;
int j;
ArrayList<TestingObject> testList=new ArrayList<TestingObject>();
TestingObject test=new TestingObject();
for( i=0;i<nu;i++)
{
test=new TestingObject();
for( j=0;j<co;j++)
{
System.out.println(j);
if(j==0){
test.setName((String) tablemanage.getModel().getValueAt(i,j));
}
else if(j==1){
test.setAge((String) tablemanage.getModel().getValueAt(i,j));
}
else{
test.setGender((String) tablemanage.getModel().getValueAt(i,j));
}
}
testList.add(test);
System.out.println ();
}
for(int k=0;k<testList.size();k++){
testList.get(k).print();
}
}
});
}
}
just remove inner for-loop inside btnSave action lister and put this codes
because your column count is always 3
test=new TestingObject();
test.setName((String) tablemanage.getModel().getValueAt(i,0));
test.setAge((String) tablemanage.getModel().getValueAt(i,1));
test.setGender((String) tablemanage.getModel().getValueAt(i,2));
testList.add(test);
and use this standard code it can be used with jdk 1.8 to print array list values
testList.stream().forEach((var) -> {
System.out.println(var);
});
So for class I'm suppose to make a Celsius to Fahrenheit converter GUI. With that said, it's a pretty simple and easy program to create. I want to do more with it though. What I want to do is have one window that changes depending on which radio button is selected in a buttongroup. I want the selected radiobutton for "To Fahrenheit" or "To Celsius" to update the labels for the input and output. I have tried using an actionlistener for when one is selected, but it doesn't change the labels. Am I using the wrong listener? What's the correct way to do this?
Here's my code:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class Converter extends JFrame {
private JPanel contentPane;
private JTextField tfNumber;
private JLabel lblCelsius;
private JLabel lblFahrenheit;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Converter frame = new Converter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Converter() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle("Celsius Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 308, 145);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
tfNumber = new JTextField();
tfNumber.setText("0");
tfNumber.setBounds(10, 11, 123, 20);
contentPane.add(tfNumber);
tfNumber.setColumns(10);
lblCelsius = new JLabel("Celsius");
lblCelsius.setFont(new Font("Tahoma", Font.BOLD, 15));
lblCelsius.setBounds(143, 12, 127, 14);
contentPane.add(lblCelsius);
lblFahrenheit = new JLabel("Fahrenheit");
lblFahrenheit.setBounds(187, 46, 95, 14);
contentPane.add(lblFahrenheit);
final JLabel lblNum = new JLabel("32.0");
lblNum.setBounds(143, 46, 43, 14);
contentPane.add(lblNum);
final JRadioButton rdbtnF = new JRadioButton("to Fahrenheit");
rdbtnF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
lblCelsius.setText("Celsius");
lblFahrenheit.setText("Fahrenheit");
}
}
});
rdbtnF.setSelected(true);
rdbtnF.setBounds(10, 72, 109, 23);
contentPane.add(rdbtnF);
final JRadioButton rdbtnC = new JRadioButton("to Celsius");
rdbtnC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
lblCelsius.setText("Fahrenheit");
lblFahrenheit.setText("Celsius");
}
}
});
rdbtnC.setBounds(121, 72, 109, 23);
contentPane.add(rdbtnC);
ButtonGroup bg = new ButtonGroup();
bg.add(rdbtnF);
bg.add(rdbtnC);
JButton btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
String num = String.valueOf(convertToF(tfNumber.getText()));
lblNum.setText(num);
}
if(rdbtnC.isSelected()) {
String num = String.valueOf(convertToC(tfNumber.getText()));
lblNum.setText(num);
}
}
});
btnConvert.setBounds(10, 42, 123, 23);
contentPane.add(btnConvert);
}
private double convertToF(String celsius) {
double c = Double.parseDouble(celsius);
double fahren = c * (9/5) + 32;
return fahren;
}
private double convertToC(String fahren) {
double f = Double.parseDouble(fahren);
double celsius = (f - 32) * 5 / 9;
return celsius;
}
}
I'm just making a small application on window builder and need some help with it. I've made 2 frames individually and I don't know how to specify the action of the button in such a way that when I click on the 'next' botton in the first frame, I want it to move to the second frame.
Here's the source code for each file.
first.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.JTextArea;
import java.awt.Font;
import java.awt.event.ActionListener;
public class first extends JFrame {
private JPanel contentPane;
private final Action action = new SwingAction();
private final Action action_1 = new SwingAction();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
first frame = new first();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public first() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNext.setAction(action_1);
btnNext.setBounds(257, 228, 55, 23);
contentPane.add(btnNext);
JButton btnExit = new JButton("Exit");
btnExit.setBounds(344, 228, 51, 23);
contentPane.add(btnExit);
JRadioButton rdbtnAdd = new JRadioButton("Add");
rdbtnAdd.setBounds(27, 80, 109, 23);
contentPane.add(rdbtnAdd);
JRadioButton rdbtnDelete = new JRadioButton("Delete");
rdbtnDelete.setBounds(27, 130, 109, 23);
contentPane.add(rdbtnDelete);
JRadioButton rdbtnEdit = new JRadioButton("Edit");
rdbtnEdit.setBounds(27, 180, 109, 23);
contentPane.add(rdbtnEdit);
JLabel lblSelectAnOption = new JLabel("Select an Option");
lblSelectAnOption.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblSelectAnOption.setBounds(27, 36, 121, 23);
contentPane.add(lblSelectAnOption);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Next");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
new second_add();
}
}
}
second.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import java.awt.event.ActionListener;
public class second_add extends JFrame {
private JPanel contentPane;
private JTextField txtTypeYourQuestion;
private JTextField txtQuestionWeight;
private JTextField txtEnter;
private JTextField txtEnter_1;
private JTextField txtValue;
private JTextField txtValue_1;
private final Action action = new SwingAction();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
second_add frame = new second_add();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public second_add() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtTypeYourQuestion = new JTextField();
txtTypeYourQuestion.setBounds(22, 11, 177, 20);
txtTypeYourQuestion.setText("Type your Question Here");
contentPane.add(txtTypeYourQuestion);
txtTypeYourQuestion.setColumns(10);
txtQuestionWeight = new JTextField();
txtQuestionWeight.setBounds(209, 11, 86, 20);
txtQuestionWeight.setText("Question weight");
contentPane.add(txtQuestionWeight);
txtQuestionWeight.setColumns(10);
txtEnter = new JTextField();
txtEnter.setBounds(22, 55, 86, 20);
txtEnter.setText("Enter . . .");
contentPane.add(txtEnter);
txtEnter.setColumns(10);
txtEnter_1 = new JTextField();
txtEnter_1.setText("Enter . . . ");
txtEnter_1.setBounds(22, 104, 86, 20);
contentPane.add(txtEnter_1);
txtEnter_1.setColumns(10);
txtValue = new JTextField();
txtValue.setText("Value . .");
txtValue.setBounds(118, 55, 51, 20);
contentPane.add(txtValue);
txtValue.setColumns(10);
txtValue_1 = new JTextField();
txtValue_1.setText("Value . .");
txtValue_1.setBounds(118, 104, 51, 20);
contentPane.add(txtValue_1);
txtValue_1.setColumns(10);
JButton btnFinish = new JButton("Finish");
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnFinish.setAction(action);
btnFinish.setBounds(335, 228, 89, 23);
contentPane.add(btnFinish);
JButton btnAddChoice = new JButton("Add choice");
btnAddChoice.setBounds(236, 228, 89, 23);
contentPane.add(btnAddChoice);
JButton btnAddQuestion = new JButton("Add question");
btnAddQuestion.setBounds(136, 228, 89, 23);
contentPane.add(btnAddQuestion);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}
Having multiple JFrame instances in one application is bad usability
Consider using something like a CardLayout instead.
Modify like this-
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
second_add second = new second_add();
setVisible(false); // Hide current frame
second.setVisible(true);
}
});
You can navigate to a frame by creating its object and using setVisible method to display it. If you want to do it on a button click, write it inside its event handler.
JFrame o = new JFrame();
o.setVisible(true);
dispose(); // This will close the current frame
The quick and dirty solution would to set the first frame's visibility to false and the second frames visibility to true in your buttonclick action. (see Sajal Dutta's answer)
But to have a consistent behaviour even for more than 2 frames, let each frame be stored in a HashTable in your main class (class holding the main method and not extending JFrame) with the ID being the order of the frame (first frame D 1, second: ID 2, etc.).
Then create a static method
public void switchFrame(JFrame originatingFrame, int NextFrame){
originatingFrame.this.setVisible(false);
((JFrame) myHashTable.get(NextFrame)).setVisible(true);
}
in your main class which can be called from each frame using
mainClass.switchFrame(this, IdOfFrameYouWantToGoTo);
that way you can also implement "Back"- and "Skip"-Buttons should you want to create something like a wizard.
NOTE: I did not test this code. This should just be seen as a general overview of how to do this.
The below piece of code will show to navigate from one page to another page in a menu format.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class AddressBookDemo implements ActionListener, Runnable {
ArrayList personsList;
PersonDAO pDAO;
Panel panel;
JFrame appFrame;
JLabel jlbName, jblPassword, jlbAddress;
JPasswordField jPassword;
JTextField jtfName, jtfAddress;
JButton jbbSave, jbnClear, jbnExit, btnNext, button;
String name, address, password;
final int CARDS = 4;
CardLayout cl = new CardLayout();
JPanel cardPanel = new JPanel(cl);
CardLayout c2 = new CardLayout();
JPanel cardPanel2 = new JPanel(c2);
int currentlyShowing = 0;
Thread errorThrower;
// int phone;
// int recordNumber; // used to naviagate using >> and buttons
Container cPane;
Container cPane2;
private JFrame frame;
private TextArea textArea;
private Thread reader;
private Thread reader2;
private boolean quit;
private final PipedInputStream pin = new PipedInputStream();
private final PipedInputStream pin2 = new PipedInputStream();
public static void main(String args[]) {
new AddressBookDemo();
}
public AddressBookDemo() {
name = "";
password = "";
address = "";
// phone = -1; //Stores 0 to indicate no Phone Number
// recordNumber = -1;
createGUI();
personsList = new ArrayList();
// creating PersonDAO object
pDAO = new PersonDAO();
}
public void createGUI() {
/* Create a frame, get its contentpane and set layout */
appFrame = new JFrame("ManualDeploy ");
cPane = appFrame.getContentPane();
cPane.setLayout(new GridBagLayout());
// frame=new JFrame("Java Console");
textArea=new TextArea();
textArea.setEditable(false);
Button button=new Button("clear");
panel=new Panel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
panel.add(textArea,gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
panel.add(button,gridBagConstraintsx03);
// frame.add(panel);
// frame.setVisible(true);
// cPane2 = frame.getContentPane();
// cPane2.setLayout(new GridBagLayout());
button.addActionListener(this);
try
{
PipedOutputStream pout=new PipedOutputStream(this.pin);
System.setOut(new PrintStream(pout,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
}
try
{
PipedOutputStream pout2=new PipedOutputStream(this.pin2);
System.setErr(new PrintStream(pout2,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
}
quit=false; // signals the Threads that they should exit
// Starting two seperate threads to read from the PipedInputStreams
//
reader=new Thread(this);
reader.setDaemon(true);
reader.start();
//
reader2=new Thread(this);
reader2.setDaemon(true);
reader2.start();
// testing part
// you may omit this part for your application
//
System.out.println("Hello World 2");
System.out.println("All fonts available to Graphic2D:\n");
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames=ge.getAvailableFontFamilyNames();
for(int n=0;n<fontNames.length;n++) System.out.println(fontNames[n]);
// Testing part: simple an error thrown anywhere in this JVM will be printed on the Console
// We do it with a seperate Thread becasue we don't wan't to break a Thread used by the Console.
System.out.println("\nLets throw an error on this console");
errorThrower=new Thread(this);
errorThrower.setDaemon(true);
errorThrower.start();
arrangeComponents();
// arrangeComponents2();
final int CARDS = 2;
final CardLayout cl = new CardLayout();
final JPanel cardPanel = new JPanel(cl);
JMenu menu = new JMenu("M");
for (int x = 0; x < CARDS; x++) {
final int SELECTION = x;
JPanel jp = new JPanel();
if (x == 0) {
jp.add(cPane);
} else if (x == 1) {
jp.add(panel);
} else if (x == 2)
jp.add(new JButton("Panel 2"));
else
jp.add(new JComboBox(new String[] { "Panel 3" }));
cardPanel.add("" + SELECTION, jp);
JMenuItem menuItem = new JMenuItem("Show Panel " + x);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
currentlyShowing = SELECTION;
cl.show(cardPanel, "" + SELECTION);
}
});
menu.add(menuItem);
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
btnNext = new JButton("Next >>");
JButton btnPrev = new JButton("<< Previous");
JPanel p = new JPanel(new GridLayout(1, 2));
p.add(btnPrev);
p.add(btnNext);
btnNext.setVisible(false);
JFrame f = new JFrame();
f.getContentPane().add(cardPanel);
f.getContentPane().add(p, BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setJMenuBar(menuBar);
f.setVisible(true);
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (currentlyShowing < CARDS - 1) {
cl.next(cardPanel);
currentlyShowing++;
}
}
});
btnPrev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (currentlyShowing > 0) {
cl.previous(cardPanel);
currentlyShowing--;
}
}
});
}
public void arrangeComponents() {
jlbName = new JLabel("Username");
jblPassword = new JLabel("Password");
jlbAddress = new JLabel("Sftpserver");
jtfName = new JTextField(20);
jPassword = new JPasswordField(20);
jtfAddress = new JTextField(20);
jbbSave = new JButton("move sftp");
jbnClear = new JButton("Clear");
jbnExit = new JButton("Exit");
/* add all initialized components to the container */
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
cPane.add(jlbName, gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
gridBagConstraintsx02.gridx = 1;
gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx02.gridy = 0;
gridBagConstraintsx02.gridwidth = 2;
gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
cPane.add(jtfName, gridBagConstraintsx02);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
cPane.add(jblPassword, gridBagConstraintsx03);
GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
gridBagConstraintsx04.gridx = 1;
gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx04.gridy = 1;
gridBagConstraintsx04.gridwidth = 2;
gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
cPane.add(jPassword, gridBagConstraintsx04);
GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints();
gridBagConstraintsx05.gridx = 0;
gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx05.gridy = 2;
cPane.add(jlbAddress, gridBagConstraintsx05);
GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints();
gridBagConstraintsx06.gridx = 1;
gridBagConstraintsx06.gridy = 2;
gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx06.gridwidth = 2;
gridBagConstraintsx06.fill = GridBagConstraints.BOTH;
cPane.add(jtfAddress, gridBagConstraintsx06);
GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
gridBagConstraintsx09.gridx = 0;
gridBagConstraintsx09.gridy = 4;
gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5);
cPane.add(jbbSave, gridBagConstraintsx09);
GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
gridBagConstraintsx10.gridx = 1;
gridBagConstraintsx10.gridy = 4;
gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnClear, gridBagConstraintsx10);
GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
gridBagConstraintsx11.gridx = 2;
gridBagConstraintsx11.gridy = 4;
gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnExit, gridBagConstraintsx11);
jbbSave.addActionListener(this);
// jbnDelete.addActionListener(this);
jbnClear.addActionListener(this);
jbnExit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("inside button123");
if (e.getSource() == jbbSave) {
savePerson();
} else if (e.getSource() == jbnClear) {
clear();
} else if (e.getSource() == jbnExit) {
System.exit(0);
}
else if (e.getSource() == button)
{
System.out.println("inside button");
textArea.setText(" ");
}
}
// Save the Person into the Address Book
public void savePerson() {
name = jtfName.getText();
password = jPassword.getText();
address = jtfAddress.getText();
if (name.equals("")) {
JOptionPane.showMessageDialog(null, "Please enter password",
"ERROR", JOptionPane.ERROR_MESSAGE);
} else if (password != null && password.isEmpty()) {
JOptionPane.showMessageDialog(null, "Please enter password",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
else {
btnNext.setVisible(true);
JOptionPane.showMessageDialog(null, "Person Saved");
}
}
public void clear() {
jtfName.setText("");
jPassword.setText("");
jtfAddress.setText("");
personsList.clear();
}
public synchronized void run()
{
try
{
while (Thread.currentThread()==reader)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin.available()!=0)
{
String input=this.readLine(pin);
textArea.append(input);
}
if (quit) return;
}
while (Thread.currentThread()==reader2)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin2.available()!=0)
{
String input=this.readLine(pin2);
textArea.append(input);
}
if (quit) return;
}
} catch (Exception e)
{
textArea.append("\nConsole reports an Internal error.");
textArea.append("The error is: "+e);
}
// just for testing (Throw a Nullpointer after 1 second)
// if (Thread.currentThread()==errorThrower)
// {
// try { this.wait(1000); }catch(InterruptedException ie){}
// throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
// }
}
public synchronized String readLine(PipedInputStream in) throws IOException
{
String input="";
do
{
int available=in.available();
if (available==0) break;
byte b[]=new byte[available];
in.read(b);
input=input+new String(b,0,b.length);
}while( !input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
return input;
}
public synchronized void windowClosed(WindowEvent evt)
{
quit=true;
this.notifyAll(); // stop all threads
try { reader.join(1000);pin.close(); } catch (Exception e){}
try { reader2.join(1000);pin2.close(); } catch (Exception e){}
System.exit(0);
}
}