If and startswith error - java

I'm having trouble with my code. the logic of my code is, when it doesn't find the username I entered a confirmation box will appear, what really happen is when a entered username is found in a line
it doesn't launched the confirmation box "that's alright" but it continue searching throughout every line and initialize else {statement} btw, my else statement is the confirmation box.
a sample data.dat that my code writes
shawn | qwerty1234
cloe | password1234
jones | shittybrix
When I entered "shawn" it launches my if statement "that's alright"
but it continues searching throughout the string and the entered Username "shawn" became not equal to cloe and jones, it launches the else statement giving me two confirmation box respectively.
I want to avoid that error but I don't know how.
THE ERROR OCCURS IN REGISTER.JAVA
this is my code for login:
package login;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JOptionPane;
public class Login extends javax.swing.JFrame {
public Login() {
initComponents0();
}
#SuppressWarnings("unchecked")
private void initComponents0() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
uname = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
login = new javax.swing.JButton();
reset = new javax.swing.JButton();
pwd = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Login Pane");
jLabel2.setText("User Name:");
jLabel3.setText("Password:");
login.setText("Login");
login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String un = uname.getText();
try {
try (BufferedReader br = new BufferedReader(new Filereader("data.dat"))) {
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.startsWith(un)) {
JOptionPane.showMessageDialog(null, "Hello: " + un, "Registration", JOptionPane.INFORMATION_MESSAGE);
} else {
int sel = JOptionPane.showConfirmDialog(null, "It seems that you haven't registered yet? \n Lunch Registration Pane?", "Admin", JOptionPane.INFORMATION_MESSAGE);
if (sel == JOptionPane.YES_OPTION) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Register().setVisible(true);
}
});
}
}
}
}
} catch (IOException | HeadlessException ez) {
JOptionPane.showMessageDialog(null, "A null file was created in order to \n avoid File Catch errors", "Admin", JOptionPane.INFORMATION_MESSAGE);
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = "null";
String data1 = "null";
writer.write(data0 + " | " + data1 + "\n");
}
} catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
}
});
reset.setText("Reset Field");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(uname, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(reset, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(pwd))))
.addContainerGap(30, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(uname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(pwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(login)
.addComponent(reset))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton login;
private javax.swing.JPasswordField pwd;
private javax.swing.JButton reset;
private javax.swing.JTextField uname;
// End of variables declaration
}
this it the registration code it launches when I clicked yes in the confirmation box
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package login;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
*
* #author Jfetizanan
*/
class Register extends javax.swing.JFrame {
/**
* Creates new form GUIREG
*/
public Register() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
unamereg = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
pwdreg = new javax.swing.JTextField();
submit = new javax.swing.JButton();
resetreg = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Registration Pane");
jLabel2.setText("User Name:");
jLabel3.setText("Password:");
submit.setText("Submit");
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Runned");
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = unamereg.getText();
String data1 = pwdreg.getText();
writer.write(data0 + " | " + data1 + "\n");
}
JOptionPane.showMessageDialog(null, "Registered", "Registration", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
});
resetreg.setText("Reset Field");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(unamereg))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pwdreg)
.addGroup(layout.createSequentialGroup()
.addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(resetreg, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap(42, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(unamereg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(pwdreg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(submit)
.addComponent(resetreg))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField pwdreg;
private javax.swing.JButton resetreg;
private javax.swing.JButton submit;
private javax.swing.JTextField unamereg;
// End of variables declaration
}

Managed to find the issue through that big mess. In your if statement that pops up saying hello 'blah', you need to make it break out of the while loop, and move the else statement. Copy whats in the else statement just out of the while loop (just because it doesnt match the first guy, doesnt mean that it wont match a later one, so dont yell at them til the end). so have it like this:
BufferedReader br = new BufferedReader(
new InputStreamReader(fstream));
String strLine;
boolean registered = false;
while ((strLine = br.readLine()) != null) {
if (strLine.startsWith(un)) {
registered = true;
break;
}
}
if(registered) {
//blah
} else {
//blah
}
Also, you should change Lunch registration to Launch registration ;)
In response to your comment, it's due to this line:
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
You have that in both of your frames, it says to stop the JVM as soon as you close it. You want this for your login frame (if they close the login window, stop the program), but not for the registration window. For that, you just want javax.swing.WindowConstants.DISPOSE_ON_CLOSE, which says it will dispose of the frame upon closing it (good cleanup). If all frames are disposed, the JVM will end (assuming no other threads are running that is), so as long as Login stays open, it shouldn't exit.

Related

GUI Program freezes once inside action performed method in java [duplicate]

This question already has answers here:
GUI Freezes During While Loop in Java
(1 answer)
The program freezes when i put a while loop in a action listener
(1 answer)
Closed 2 years ago.
I am attempting to redirect my system.out.println to dislpay to the JTextArea element of the GUI (hence it being public and static so that the methods that print something can print to it.
But once it gets to the line:
System.out.println("sdsdsdsdsa");
the program just does not go any further. The next two lines are:
System.setOut(printStream);
System.setErr(printStream);
which it does not seem to print out and when I exit the program this error appears:
"Exception: java.lang.NullPointerException thrown from the UncaughtExceptionHandler in thread "main""
and I am unable to verify whether printStream is null or not because the debugger does not seem to following into the action performed method once the start button (JButton1) is pressed.
Below is the main class in the GUI:
public class TrainingProgramme {
static PrintStream printStream = new PrintStream(new GUITextOutputStream(TrainingProgrammeGUI.jTextArea1));
public static void main(String[] args) {
TrainingProgrammeGUI gui = new TrainingProgrammeGUI();
gui.setVisible(true);
System.setOut(printStream);
System.setErr(printStream);
System.out.println("==================================\n"+
"* WELCOME TO CATCH ME IF YOU CAN *\n"+
"==================================\n");
}
GUI class:
package javaapplication2;
import java.awt.event.ActionEvent;
import java.io.PrintStream;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author viljo
*/
public class TrainingProgrammeGUI extends javax.swing.JFrame {
static PrintStream printStream = new PrintStream(new GUITextOutputStream(TrainingProgrammeGUI.jTextArea1));
double startTimer = System.nanoTime();
double stopTimer = 0;
Scanner scan = new Scanner(System.in);
Player gameCharacter = null;
Teacher teacher = null;
int finishedProgram = 0;
int userChoice = -1;
/**
* Creates new form TrainingProgrammeGUI
*/
public TrainingProgrammeGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767));
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel1.setText("CIA Training Programme");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel2.setText("Game: ");
jButton1.setText("Start Game");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton3.setText("What is this game?");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel3.setText("Type Here: ");
jButton4.setText("Exit");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(159, 159, 159))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(261, 261, 261)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(170, 170, 170)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(175, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(70, 70, 70)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(20, 20, 20))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
TrainingProgrammeGUI programme = new TrainingProgrammeGUI();
programme.setVisible(true);
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.print("\nThank you for using our training programme!");
System.exit(0);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("sdsdsdsdsa");
System.setOut(printStream);
System.setErr(printStream);
System.out.println("==================================\n"+
"* WELCOME TO CATCH ME IF YOU CAN *\n"+
"==================================\n");
userChoice = TrainingProgramme.checkInputWithPhrase("1.) Start Game\n2.) What is this game?\n3.) Quit", 1, 3);
teacher = new Teacher("John Doe", "Teacher");
gameCharacter = teacher.introductionLines(); // teacher reads a few lines and asks questions then returns Player class
boolean userFinished = false;
gameCharacter.getHotelRoom().setPlayerHere(true);
do { // Checks which room player is in then reads instructions for room. Loop finishes when player wants to chooses suspect
if (gameCharacter.getHotelKitchen().isPlayerHere()) {
if ("HotelRoom".equals((gameCharacter.getHotelKitchen().instructions(teacher)))) {
System.out.println("\nRoom chosen!\n");
gameCharacter.getHotelKitchen().setPlayerHere(false); // Takes player out of current room
gameCharacter.getHotelRoom().setPlayerHere(true); // Puts players into chosen room
}
} else {
if ("Choose".equals((gameCharacter.getHotelRoom().instructions(teacher)))) {
stopTimer = System.nanoTime();
Player.timeTaken = (stopTimer - startTimer) / 10000000; //time taken to finish inspecting items (in seconds)
teacher.chooseWhoDidIt(gameCharacter);
finishedProgram = 1; //Stop the curret loop
userFinished = true; //Stop the main menu loop
} else {
System.out.println("\nKitchen chosen!\n");
gameCharacter.getHotelRoom().setPlayerHere(false);// Takes player out of current room
gameCharacter.getHotelKitchen().setPlayerHere(true);// Puts players into chosen room
}
}
} while (userFinished == false);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("\n+===========================================================+");
System.out.println("|This game was created to help train our new junior recruits|");
System.out.println("+===========================================================+\n\n");
System.out.println("Objective: Gather evidence by looking for clues\n"+
"and once you are done go back to the room to guess \n"+
"which suspect did it. Suspects are provided once you have\n"+
"went back to the room and decided to guess who did the crime!\n");
}
// Variables declaration - do not modify
private javax.swing.Box.Filler filler1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
PrintStream class:
package net.codejava.swing;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
/**
* This class extends from OutputStream to redirect output to a JTextArrea
* #author www.codejava.net
*
*/
public class CustomOutputStream extends OutputStream {
private JTextArea textArea;
public CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}
#Override
public void write(int b) throws IOException {
// redirects data to the text area
textArea.append(String.valueOf((char)b));
// scrolls the text area to the end of data
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}

Junit Testing for GUI

I have following Simple Utility Calculator
Now i want to apply some Junit Testing here.
I don't know how to perform a Junit testing on Gui.
So kindly help me out.
Code is:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package calculator;
import java.io.*;
import java.text.DecimalFormat;
/**
*
* #author owner
*/
public class Calculator_Utility extends javax.swing.JFrame {
/**
* Creates new form Calculator_Utility
*/
public Calculator_Utility() {
initComponents();UsePowerKw.setText("4.0");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void setComponentsName(){
AddButton.setName("Add");
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
CostPerKW = new javax.swing.JLabel();
SelectAppliance = new javax.swing.JLabel();
PowerUsage = new javax.swing.JLabel();
NumberHoursUse = new javax.swing.JLabel();
TotalCostApp = new javax.swing.JLabel();
AddButton = new javax.swing.JButton();
CostPerKwTextField = new javax.swing.JTextField();
UsePowerKw = new javax.swing.JTextField();
HourUse = new javax.swing.JTextField();
CostApp = new javax.swing.JTextField();
AllTotal = new javax.swing.JLabel();
AllTotalApp = new javax.swing.JTextField();
SelectApp = new javax.swing.JComboBox<>();
Showfield = new javax.swing.JTextField();
GallonWater = new javax.swing.JLabel();
GallonWat = new javax.swing.JTextField();
Export = new javax.swing.JButton();
CostGallon = new javax.swing.JLabel();
CostGall = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
CostPerKW.setText("Cost Per KW Hour:");
SelectAppliance.setText("Select Appliance:");
PowerUsage.setText("Power Usage In KW Hours:");
NumberHoursUse.setText("Number of Hours use per day:");
TotalCostApp.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
TotalCostApp.setText("Total Cost For Appliance");
AddButton.setText("ADD");
AddButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddButtonActionPerformed(evt);
}
});
CostPerKwTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CostPerKwTextFieldActionPerformed(evt);
}
});
UsePowerKw.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UsePowerKwActionPerformed(evt);
}
});
AllTotal.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
AllTotal.setText("Total of All Appliances");
SelectApp.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Refrigerator", "Washer", "Dryer", "Freezer", "Air Conditioner" }));
SelectApp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SelectAppActionPerformed(evt);
}
});
GallonWater.setText("Gallon of Water:");
Export.setText("Export");
Export.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExportActionPerformed(evt);
}
});
CostGallon.setText("Cost Per Gallon:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(NumberHoursUse)
.addComponent(SelectAppliance)
.addComponent(PowerUsage)
.addComponent(CostPerKW))
.addComponent(CostGallon, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(GallonWater, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(4, 4, 4))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(AllTotal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CostPerKwTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(UsePowerKw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(HourUse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SelectApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AllTotalApp, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(GallonWat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CostGall, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(Showfield, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(Export)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(TotalCostApp)
.addGap(4, 4, 4)
.addComponent(CostApp, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(AddButton)
.addGap(24, 24, 24))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {AllTotalApp, CostApp, CostGall, CostPerKwTextField, GallonWat, HourUse, SelectApp, UsePowerKw});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostPerKW)
.addComponent(CostPerKwTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SelectAppliance)
.addComponent(SelectApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PowerUsage)
.addComponent(UsePowerKw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(NumberHoursUse)
.addComponent(HourUse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(GallonWat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(GallonWater)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostGallon)
.addComponent(CostGall, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(TotalCostApp))
.addComponent(AddButton))
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AllTotalApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AllTotal))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Showfield, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Export))
.addContainerGap())
);
pack();
}// </editor-fold>
//Declare Variables and intialize the variables
private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {
double answer;
double total = 0;
String s = SelectApp.getSelectedItem().toString();
//Check if user select "Washer" from drop down box, calculate usage with Gallon
if (s=="Washer") {
//DecimalFormat df= new DecimalFormat("#.##");
number1 = (int)((Double.parseDouble(CostPerKwTextField.getText())));
number2 = (int)((Double.parseDouble(UsePowerKw.getText())));
number3 = (int)((Double.parseDouble(HourUse.getText())));
number4 = (int)((Double.parseDouble(GallonWat.getText())));
answer = number1*number2*number3;
total =+ answer;
CostApp.setText(String.valueOf(answer + "\n"));
Showfield.setText(String.valueOf("The appliance run a total of " + answer + "\n"));
}
//if user select any appliances other than washer calculate usage
else
number1 = (int)((Double.parseDouble(CostPerKwTextField.getText())));
number2 = (int)((Double.parseDouble(UsePowerKw.getText())));
number3 = (int)((Double.parseDouble(HourUse.getText())));
answer = number1*number2*number3;
total =+ answer;
//Calculated amount is put into field
CostApp.setText(String.valueOf(answer + "\n"));
Showfield.setText(String.valueOf("The appliance run a total of " + answer + "\n"));
// TODO add your handling code here:
}
//Action listener/Events for JCombo. Pre-defined Power Usage for Each Appliacnes
private void SelectAppActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String s=SelectApp.getSelectedItem().toString();
double r=4;
double w=7;
double x=12;
double y=16;
double z=24;
if (s=="Refrigerator"){
UsePowerKw.setText(String.valueOf(r));
}
else if (s=="Washer") {UsePowerKw.setText(String.valueOf(w));}
else if (s=="Dryer") {UsePowerKw.setText(String.valueOf(x));}
else if (s=="Freezer") {UsePowerKw.setText(String.valueOf(y));}
else UsePowerKw.setText(String.valueOf(z));
}
private void UsePowerKwActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//If jComboBox1 = "Refrigerator" then set jTextField4 = 22
}
//Action Listener/Event creates Data.txt with output
private void ExportActionPerformed(java.awt.event.ActionEvent evt) {
File file = new File("Data.txt");
try (Writer writer = new BufferedWriter(new FileWriter(file))) {
String contents = Showfield.getText();
//"The quick brown fox" +
//System.getProperty("line.separator") +
//"jumps over the lazy dog.";
writer.write(contents);
} catch (IOException e) {
e.printStackTrace();
}
}
private void CostPerKwTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Calculator_Utility().setVisible(true);
}
});
}
public double number1, number2, number3, number4;
// Variables declaration - do not modify
private javax.swing.JButton AddButton;
private javax.swing.JLabel AllTotal;
private javax.swing.JTextField AllTotalApp;
private javax.swing.JTextField CostApp;
private javax.swing.JTextField CostGall;
private javax.swing.JLabel CostGallon;
private javax.swing.JLabel CostPerKW;
private javax.swing.JTextField CostPerKwTextField;
private javax.swing.JButton Export;
private javax.swing.JTextField GallonWat;
private javax.swing.JLabel GallonWater;
private javax.swing.JTextField HourUse;
private javax.swing.JLabel NumberHoursUse;
private javax.swing.JLabel PowerUsage;
private javax.swing.JComboBox<String> SelectApp;
private javax.swing.JLabel SelectAppliance;
private javax.swing.JTextField Showfield;
private javax.swing.JLabel TotalCostApp;
private javax.swing.JTextField UsePowerKw;
// End of variables declaration
}
Any testCase you can apply like proper working , (actual== expected Result) etc.
You can't test the GUI with JUnit. You can only test the methods.
For example you have a JButton with an actionListener witch calls the method calculate(1, 1):
JButton showDialogButton = new JButton("Text Button");
showDialogButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
calculate(1, 1);
}
});
private int calculate(int n1, int n2){
return n1 + n2;
}
Now, You cant test the JButton but you can test the method "calculate". We know that calculate(1, 1) will return us 2 so we test it:
assertEquals(2, calculate(1, 1));
This means, that you cannot "press the button with JUnit" but you can test the action the button does.

How to set jLabel's ImageIcon from File instance's absolutePath

I want to add a photo from a chosen image File to a jPanel but, the following code doesn't seem to work :
private void browsePhotoButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
String[] fileSuffixes = ImageIO.getReaderFileSuffixes();
for(String fileSuffix:fileSuffixes){
FileFilter filter = new FileNameExtensionFilter(fileSuffix + " files", fileSuffix);
fileChooser.addChoosableFileFilter(filter);
}
int selection = fileChooser.showOpenDialog(EmployeeInternalFrame.this);
if(selection == JFileChooser.APPROVE_OPTION){
File fileBeingOpened = fileChooser.getSelectedFile();
setPhotoFile(fileBeingOpened);
setImageURL(getPhotoFile().getAbsolutePath());
photoPanel.removeAll();
Icon icon = new ImageIcon(getImageURL());
JLabel label = new JLabel(icon, SwingConstants.LEFT);
photoPanel.add(label);
photoPanel.repaint();
}
}
Which part am I missing ? Thank you for all of your help.
[EDIT]
This is the Class where the above code implemented :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package forms;
import dataobjects.Employee;
import datamodels.EmployeeTableModel;
import datacontrollers.EmployeeController;
import java.io.File;
import java.awt.Image;
import java.awt.Label;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.filechooser.FileFilter;
import javax.swing.SwingConstants;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.Icon;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
/**
*
* #author Benignus
*/
public class EmployeeInternalFrame extends javax.swing.JInternalFrame{
private EmployeeTableModel employeeTableModel;
private String imageURL;
private EmployeeController employeeController;
private File photoFile;
private Image photoImage;
/**
* Creates new form EmployeeInternalFrame
*/
public EmployeeInternalFrame() {
initComponents();
employeeTableModel = new EmployeeTableModel();
employeeTable.setModel(employeeTableModel);
employeeController = new EmployeeController(this);
employeeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
#Override
public void valueChanged(ListSelectionEvent e) {
int row = employeeTable.getSelectedRow();
if(row != -1){
Employee employee = employeeTableModel.getAtIndex(row);
ssnText.setText(employee.getSsn());
nameText.setText(employee.getName());
positionComboBox.setSelectedItem(employee.getPosition());
basePayText.setText(String.valueOf(employee.getBasePay()));
banText.setText(employee.getBan());
imageURL = employee.getPhoto();
}
}
});
refreshTable();
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL){
this.imageURL = imageURL;
}
public EmployeeTableModel getEmployeeTableModel() {
return employeeTableModel;
}
public JButton getBackButton() {
return backButton;
}
public JTextField getBanText() {
return banText;
}
public JTextField getBasePayText() {
return basePayText;
}
public JButton getBrowsePhotoButton() {
return browsePhotoButton;
}
public JTable getEmployeeTable() {
return employeeTable;
}
public JButton getInputButton() {
return inputButton;
}
public JTextField getNameText() {
return nameText;
}
public JPanel getPhotoPanel() {
return photoPanel;
}
public JComboBox getPositionComboBox() {
return positionComboBox;
}
public JComboBox getSearchByComboBox() {
return searchByComboBox;
}
public JTextField getSearchText() {
return searchText;
}
public JTextField getSsnText() {
return ssnText;
}
private void refreshTable(){
employeeController.selectAll();
}
public File getPhotoFile() {
return photoFile;
}
public void setPhotoFile(File photoFile) {
this.photoFile = photoFile;
}
public Image getPhotoImage() {
return photoImage;
}
public void setPhotoImage(Image photoImage) {
this.photoImage = photoImage;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
photoPanel = new javax.swing.JPanel();
browsePhotoButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
employeeTable = new javax.swing.JTable();
positionComboBox = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
ssnText = new javax.swing.JTextField();
nameText = new javax.swing.JTextField();
inputButton = new javax.swing.JButton();
backButton = new javax.swing.JButton();
basePayText = new javax.swing.JTextField();
banText = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
searchText = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
searchByComboBox = new javax.swing.JComboBox();
photoPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout photoPanelLayout = new javax.swing.GroupLayout(photoPanel);
photoPanel.setLayout(photoPanelLayout);
photoPanelLayout.setHorizontalGroup(
photoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 111, Short.MAX_VALUE)
);
photoPanelLayout.setVerticalGroup(
photoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 149, Short.MAX_VALUE)
);
browsePhotoButton.setText("Browse Photo");
browsePhotoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browsePhotoButtonActionPerformed(evt);
}
});
employeeTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(employeeTable);
positionComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel1.setText("SSN");
jLabel2.setText("Name");
jLabel3.setText("Position");
jLabel4.setText("Base Pay");
inputButton.setText("Input");
inputButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inputButtonActionPerformed(evt);
}
});
backButton.setText("Back");
jLabel5.setText("BAN");
jLabel7.setText("Search By :");
searchByComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(banText, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel4))
.addGap(6, 6, 6))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(basePayText)
.addComponent(ssnText, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
.addComponent(nameText, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
.addComponent(positionComboBox, 0, 170, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(photoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(browsePhotoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(inputButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(5, 5, 5)
.addComponent(searchByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(photoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(9, 9, 9)
.addComponent(browsePhotoButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(26, 26, 26)
.addComponent(jLabel2)
.addGap(63, 63, 63)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(basePayText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(ssnText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addComponent(nameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(positionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(banText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(17, 17, 17)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(inputButton)
.addComponent(backButton))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(searchByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(15, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void browsePhotoButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
String[] fileSuffixes = ImageIO.getReaderFileSuffixes();
for(String fileSuffix:fileSuffixes){
FileFilter filter = new FileNameExtensionFilter(fileSuffix + " files", fileSuffix);
fileChooser.addChoosableFileFilter(filter);
}
int selection = fileChooser.showOpenDialog(EmployeeInternalFrame.this);
if(selection == JFileChooser.APPROVE_OPTION){
File fileBeingOpened = fileChooser.getSelectedFile();
setPhotoFile(fileBeingOpened);
setImageURL(getPhotoFile().getAbsolutePath());
photoPanel.removeAll();
Icon icon = new ImageIcon(getImageURL());
JLabel label = new JLabel(icon, SwingConstants.LEFT);
photoPanel.add(label);
photoPanel.repaint();
JOptionPane.showMessageDialog(this, getImageURL());
}
}
private void inputButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(inputButton.getText().equalsIgnoreCase("Input")){
}
else if(inputButton.getText().equalsIgnoreCase("Save")){
}
else if(inputButton.getText().equalsIgnoreCase("Update")){
}
}
// Variables declaration - do not modify
private javax.swing.JButton backButton;
private javax.swing.JTextField banText;
private javax.swing.JTextField basePayText;
private javax.swing.JButton browsePhotoButton;
private javax.swing.JTable employeeTable;
private javax.swing.JButton inputButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField nameText;
private javax.swing.JPanel photoPanel;
private javax.swing.JComboBox positionComboBox;
private javax.swing.JComboBox searchByComboBox;
private javax.swing.JTextField searchText;
private javax.swing.JTextField ssnText;
// End of variables declaration
}
The documentation of ImageIcon(String filename) states that:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:
new ImageIcon("images/myImage.gif")
The description is initialized to the filename string.
So, what I think your problem is with the path that you have given as parameters which has \ in the path.
I "think" the problem is with the use of GroupLayout, it's generally a
pain in the ... Code ... Personally, I'd use a different layout, even
with the form editor and add a place holder label for the phot, which
you can use to set the icon – MadProgrammer yesterday
I changed the panel's layout into Card Layout, and it's fine now, thank you everyone :)

Should I use substring to avoid a certain string in java database or is there another way to bypass it?

I am building a product database and when I'm using the update database function my program crashes.
The issue is one string the program itself throws in.
I retrieve the data from the database text file and because I'm using numberformat.getCurrencyInstance and it throws in a dollar sign. So I threw in an exception String price = updatePriceTextField.getText().substring(1); so it would bypass the dollar sign in the beginning of the text field and send the information back to the textfile and save.
Now it brought up my current problem which is: when I enter a number bigger than 999 and I get to thousands, it brings in a comma: example: $3000.00 is now $3,000.00 and when i try to send that information back to the database it throws in an error and crashes.
Now I know I could just simply add in another substring to avoid, and solve the problem like that, but what if the price of the object lets say is: $300000000.00 the the program throws in 2 commas $300,000,000.00 and would crash again. So what sort of exception or command should I throw in to bypass these commas except substring.
Sorry for the long post, but I tried to explain the issue as well as I could.
import java.util.ArrayList;
/**
*
* #author 0103425014
*/
public class EditProduct extends javax.swing.JFrame {
ProductTextFile txtfile = new ProductTextFile();
ArrayList<Product> products = txtfile.getProducts();
/**
* Creates new form UpdateProduct
*/
public EditProduct() {
initComponents();
for (Product p : products)
updateComboBox.addItem(p.getCode() + " " + p.getDescription());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
updateComboBox = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
updateCodeTextField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
updateDesTextField = new javax.swing.JTextField();
updatePriceTextField = new javax.swing.JTextField();
buttonUpdate = new javax.swing.JButton();
buttonExit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
updateComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateComboBoxActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Select Product to edit:");
jLabel2.setText("Product Code:");
jLabel3.setText("Product Description:");
jLabel4.setText("Product Price:");
buttonUpdate.setText("UPDATE");
buttonUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonUpdateActionPerformed(evt);
}
});
buttonExit.setText("EXIT");
buttonExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonExitActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(buttonUpdate)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonExit)
.addGap(104, 104, 104))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(updateCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(updateDesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(updatePriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(updateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jLabel1)))
.addGap(0, 126, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1)
.addGap(33, 33, 33)
.addComponent(updateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(updateCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(updateDesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(updatePriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonUpdate)
.addComponent(buttonExit))
.addContainerGap(73, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void buttonExitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void buttonUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Product p = new Product();
p.setCode(updateCodeTextField.getText());
p.setDescription(updateDesTextField.getText());
String price = updatePriceTextField.getText().substring(1);
p.setPrice(Double.parseDouble(price));
txtfile.updateProduct(p);
UpdatedConfirm confirmed = new UpdatedConfirm();
confirmed.setVisible(true);
this.setVisible(false);
// txtfile.updateProduct();
}
private void updateComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int si = updateComboBox.getSelectedIndex();
Product sp = products.get(si);
updateCodeTextField.setText(sp.getCode());
updateDesTextField.setText(sp.getDescription());
updatePriceTextField.setText(sp.getFormattedPrice());
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new EditProduct().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonExit;
private javax.swing.JButton buttonUpdate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField updateCodeTextField;
private javax.swing.JComboBox updateComboBox;
private javax.swing.JTextField updateDesTextField;
private javax.swing.JTextField updatePriceTextField;
// End of variables declaration
}
Use a JFormattedTextField instead, this way you just use getValue and it will return you the unformatted value for the field.
See How to Use Formatted Text Fields for more details

How can I set certain text to be read into a textfield in GUI?

I'm working on an assignment using Binary IO and Event Handling. It looks like this, I think I have most of the basic code down, and now its down to the hard stuff. How can I read text from my .bin file into the seperate text fields?
My fields currently are blank, but when read in they should look something like that and I should be able to parse through seperate sets of information with my two buttons on the bottom.
Here is what I have so far.
I have a RecordViewerUI JFrame form, a RecordViewerPanel JFrame panel, and a SalesAgent java class which holds all of my getters and setters/ constructor for my four variables.
Here is my panel. Sorry for the generated code.
Thanks in advance for any help anyone can offer.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RecordViewerPanel extends javax.swing.JPanel {
String filename = "sales.bin";
ArrayList<SalesAgent> customer = new ArrayList<>();
int curIndex = 0;
/**
* Creates new form RecordViewerPanel
*/
public RecordViewerPanel() throws IOException, ClassNotFoundException {
initComponents();
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(filename)));
ArrayList<SalesAgent> salesForce = new ArrayList<SalesAgent>();
String first = in.readUTF();
String last = in.readUTF();
double sales = in.readDouble();
Date date = (Date) (in.readObject());
} catch (FileNotFoundException ex) {
Logger.getLogger(RecordViewerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void refreshUI() {
SalesAgent sale = (customer.get(curIndex));
firstTextField.setText(sale.getFirst());
lastTextField.setText(sale.getLast());
salesTextField.setText("$" + String.valueOf(sale.getSales()));
dateTextField.setText(String.valueOf(sale.getDate()));
recordPanel.repaint();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
filePanel = new javax.swing.JPanel();
fileLabel = new javax.swing.JLabel();
fileLabel1 = new javax.swing.JLabel();
recordPanel = new javax.swing.JPanel();
firstTextField = new javax.swing.JTextField();
lastTextField = new javax.swing.JTextField();
salesTextField = new javax.swing.JTextField();
dateTextField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
previousButton = new javax.swing.JButton();
nextButton = new javax.swing.JButton();
filePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
fileLabel.setBackground(new java.awt.Color(204, 204, 204));
fileLabel.setText("sales.bin");
fileLabel1.setBackground(new java.awt.Color(204, 204, 204));
fileLabel1.setText("Current file:");
javax.swing.GroupLayout filePanelLayout = new javax.swing.GroupLayout(filePanel);
filePanel.setLayout(filePanelLayout);
filePanelLayout.setHorizontalGroup(
filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(fileLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(fileLabel1)
.addContainerGap(562, Short.MAX_VALUE)))
);
filePanelLayout.setVerticalGroup(
filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(fileLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addContainerGap())
.addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(fileLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addContainerGap()))
);
recordPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
firstTextField.setText("jTextField1");
lastTextField.setText("jTextField1");
salesTextField.setText("jTextField1");
dateTextField.setText("jTextField1");
jLabel1.setText("First Last Sales Date");
previousButton.setText("<<");
previousButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousButtonActionPerformed(evt);
}
});
nextButton.setText(">>");
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout recordPanelLayout = new javax.swing.GroupLayout(recordPanel);
recordPanel.setLayout(recordPanelLayout);
recordPanelLayout.setHorizontalGroup(
recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 203, Short.MAX_VALUE))
.addGroup(recordPanelLayout.createSequentialGroup()
.addComponent(firstTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lastTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(salesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(dateTextField)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, recordPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(previousButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31))
);
recordPanelLayout.setVerticalGroup(
recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lastTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(salesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(previousButton)
.addComponent(nextButton))
.addGap(27, 27, 27))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(filePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(recordPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(filePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(recordPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>
private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (curIndex > 0) {
curIndex--;
} else if (curIndex == 0) {
curIndex = 4;
}
customer.get(curIndex);
}
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (curIndex < 4) {
curIndex++;
} else if (curIndex == 4) {
curIndex = 0;
}
customer.get(curIndex);
}
// Variables declaration - do not modify
private javax.swing.JTextField dateTextField;
private javax.swing.JLabel fileLabel;
private javax.swing.JLabel fileLabel1;
private javax.swing.JPanel filePanel;
private javax.swing.JTextField firstTextField;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField lastTextField;
private javax.swing.JButton nextButton;
private javax.swing.JButton previousButton;
private javax.swing.JPanel recordPanel;
private javax.swing.JTextField salesTextField;
// End of variables declaration
}
This is rather difficult to answer, as I have no understanding of the file format or the Customer class, but basically, you need to create a new Customer from the values you've read from the file, add it to the customer List and call refreshUI
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(filename)));
String first = in.readUTF();
String last = in.readUTF();
double sales = in.readDouble();
Date date = (Date) (in.readObject());
Customer cust = ...;
customer.add(cust);
} catch (FileNotFoundException ex) {
Logger.getLogger(RecordViewerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
refreshUI();

Categories

Resources