How to Save/Open an ArrayList of objects using JFileChooser? - java

Okay so I'm kind of new to Java programming, and I don't quite understand the concepts of file reading/writing. I've tried looking at the docs.oracle webpages about Files, but I found they aren't really helpful considering what I'm trying to do is kind of different.
I have these 3 files: CVolunteer, CDialog, and TestDialog. CVolunteer creates and object of a person who can volunteer to tutor students. CDialog manages the adding/editing of the volunteer. TestDialog displays a JList of volunteers and allows the user to edit, add, remove, or clear the list. I have those 3 classes working perfectly and will display them below (sorry they're long!).
Here's what I need help with... I added two buttons to the main window, "Save" and "Open". At any time, the user should be able to save the current JList of volunteers. When "Save" is clicked, a JFileChooser window should pop up and ask the user for a filename where all the volunteer objects will be saved. When the user clicks "Open", another JFileChooser window should pop up and ask the user what file they want to open. The volunteers currently in the main window will be erased and the volunteers from the selected file will take their place. I'm not sure if I need to use Serialization or not....
If anyone could help explain how to accomplish this or help me write the code to handle the "Save"/"Open" events, I would really appreciate it! Thanks in advance:)
I believe the only file that needs changing is TestDialog, I included the others in case someone wants to try to run it
***Sorry if there are any indentation errors, I had to do it all by hand in this dialog box
CVolunteer.java
public class CVolunteer {
int volNum;
String name;
int sub, volDays, trans;
public CVolunteer(int vNum, String vName, int subj, int days, int needTrans){
volNum = vNum;
name = vName;
sub = subj;
volDays = days;
trans = needTrans;
}
private String subjectToString()
{
switch (sub){
case 0:
return "Math";
case 1:
return "Science";
case 2:
return "English";
case 3:
return "History";
}
return " ";
}
private String volDaysToString()
{
String str = "";
str +=((volDays&1)!=0)?"M":"-";
str +=((volDays&2)!=0)?"T":"-";
str +=((volDays&4)!=0)?"W":"-";
str +=((volDays&8)!=0)?"R":"-";
return str;
}
private String transToString()
{
switch(trans)
{
case 0:
return "Yes";
case 1:
return "No";
}
return " ";
}
public String getVolunteerLine()
{
return String.format("%05d %-30s%-30s%-30s%s",
volNum, name, subjectToString(), volDaysToString(), transToString());
}
}
CDialog.java
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
public class CDialog extends JDialog implements ActionListener
{
private JLabel label1;
private JLabel lNum;
private JLabel label2;
private JTextField tfName;
private JLabel label3;
private ButtonGroup subGroup;
private JRadioButton rbMath;
private JRadioButton rbScience;
private JRadioButton rbEnglish;
private JRadioButton rbHistory;
private JLabel label4;
private JCheckBox cbMonday;
private JCheckBox cbTuesday;
private JCheckBox cbWednesday;
private JCheckBox cbThursday;
private JLabel label5;
private ButtonGroup transGroup;
private JRadioButton rbYes;
private JRadioButton rbNo;
private JButton okButton = null;
private JButton cancelButton = null;
private boolean cancelled = true;
public boolean isCancelled() {return cancelled;}
private CVolunteer answer;
public CVolunteer getAnswer() {return answer;}
public CDialog(JFrame owner, String title, CVolunteer vol)
{
super(owner, title, true);
Container c = getContentPane();
c.setLayout(null);
label1 = new JLabel ("Volunteer Number:");
label1.setSize(140,20);
label1.setLocation(40,40);
c.add(label1);
lNum = new JLabel(String.format("%05d", vol.volNum));
lNum.setSize(40,20);
lNum.setLocation(150,40);
c.add(lNum);
label2 = new JLabel ("Volunteer Name: ");
label2.setSize(100,20);
label2.setLocation(40,90);
c.add(label2);
tfName = new JTextField(vol.name);
tfName.setSize(120,20);
tfName.setLocation(140,90);
c.add(tfName);
int x,y;
int w,h;
x=4;
y=150;
w=180;
h=20;
label3 = new JLabel("Subject: ");
label3.setSize(85,13);
label3.setLocation(x,y);
c.add(label3);
rbMath = new JRadioButton("Math", vol.sub==0);
rbMath.setSize(w,h);
rbMath.setLocation(x+16,y+30);
c.add(rbMath);
rbScience = new JRadioButton("Science", vol.sub==1);
rbScience.setSize(w,h);
rbScience.setLocation(x+16,y+66);
c.add(rbScience);
rbEnglish = new JRadioButton("English", vol.sub==2);
rbEnglish.setSize(w,h);
rbEnglish.setLocation(x+16,y+102);
c.add(rbEnglish);
rbHistory = new JRadioButton("History", vol.sub==3);
rbHistory.setSize(w,h);
rbHistory.setLocation(x+16,y+138);
c.add(rbHistory);
subGroup = new ButtonGroup();
subGroup.add(rbMath);
subGroup.add(rbScience);
subGroup.add(rbEnglish);
subGroup.add(rbHistory);
x=220;
y=150;
w=120;
h=20;
label4 = new JLabel("Days Available: ");
label4.setSize(w,h);
label4.setLocation(x,y);
c.add(label4);
cbMonday = new JCheckBox("Monday (M)", (vol.volDays&1)!=0);
cbMonday.setSize(w,h);
cbMonday.setLocation(x+6,y+30);
c.add(cbMonday);
cbTuesday = new JCheckBox("Tuesday (T)", (vol.volDays&2)!=0);
cbTuesday.setSize(w,h);
cbTuesday.setLocation(x+6,y+66);
c.add(cbTuesday);
cbWednesday = new JCheckBox("Wednesday (W)", (vol.volDays&4)!=0);
cbWednesday.setSize(w,h);
cbWednesday.setLocation(x+6,y+102);
c.add(cbWednesday);
cbThursday = new JCheckBox("Thursday (R)", (vol.volDays&8)!=0);
cbThursday.setSize(w,h);
cbThursday.setLocation(x+6,y+138);
c.add(cbThursday);
x=480;
y=150;
w=180;
h=20;
label5 = new JLabel("Need Transport? :");
label5.setSize(150,13);
label5.setLocation(x,y);
c.add(label5);
rbYes = new JRadioButton("Yes", vol.trans==0);
rbYes.setSize(w,h);
rbYes.setLocation(x+12,y+30);
c.add(rbYes);
rbNo = new JRadioButton("No", vol.trans==1);
rbNo.setSize(w,h);
rbNo.setLocation(x+12,y+66);
c.add(rbNo);
transGroup = new ButtonGroup();
transGroup.add(rbYes);
transGroup.add(rbNo);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
cancelButton.setSize(100,50);
cancelButton.setLocation(116,380);
c.add(cancelButton);
okButton = new JButton("OK");
okButton.addActionListener(this);
okButton.setSize(100,50);
okButton.setLocation(400,380);
c.add(okButton);
setSize(700,480);
setLocationRelativeTo(owner);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==okButton) {
int num=Integer.parseInt(lNum.getText());
String name=tfName.getText();
int subj=-1;
if (rbMath.isSelected()) subj = 0;
if (rbScience.isSelected()) subj = 1;
if (rbEnglish.isSelected()) subj = 2;
if (rbHistory.isSelected()) subj = 3;
int days=0;
if (cbMonday.isSelected()) days |= 1;
if (cbTuesday.isSelected()) days |= 2;
if (cbWednesday.isSelected()) days |= 4;
if (cbThursday.isSelected()) days |= 8;
int tran=0;
if (rbYes.isSelected()) tran = 0;
if (rbNo.isSelected()) tran = 1;
answer=new CVolunteer(num, name, subj, days, tran);
cancelled = false;
setVisible(false);
}
else if(e.getSource()==cancelButton) {
cancelled = true;
setVisible(false);
}
}
}
TestDialog.java
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
public class TestDialog extends JFrame implements ActionListener
{
JLabel myLabel1 = null;
JLabel myLabel2 = null;
JLabel myLabel3 = null;
JLabel myLabel4 = null;
JLabel myLabel5 = null;
JLabel myLabel6 = null;
File fileName = new File("Volunteers.txt");
ArrayList<CVolunteer> volArray;
private DefaultListModel volunteers;
JList volList;
JScrollPane scrollPane = null;
JButton bAdd = null;
JButton bEdit = null;
JButton bRemove = null;
JButton bClear = null;
JButton bSave = null;
JButton bOpen = null;
int volNumb;
public TestDialog()
{
super("Volunteer Info");
Container c = getContentPane();
c.setLayout(null);
myLabel1 = new JLabel("Vol Number");
myLabel1.setSize(200,50);
myLabel1.setLocation(100,10);
c.add(myLabel1);
myLabel2 = new JLabel("Vol Name");
myLabel2.setSize( 200, 50 );
myLabel2.setLocation( 200, 10 );
c.add(myLabel2);
myLabel3 = new JLabel("Subject");
myLabel3.setSize( 200, 50 );
myLabel3.setLocation( 310, 10);
c.add(myLabel3);
myLabel4 = new JLabel("Vol Days");
myLabel4.setSize( 200, 50 );
myLabel4.setLocation( 400, 10 );
c.add(myLabel4);
myLabel5 = new JLabel("Transport");
myLabel5.setSize( 200, 50 );
myLabel5.setLocation( 500, 10 );
c.add(myLabel5);
volArray = new ArrayList<CVolunteer>();
volunteers = new DefaultListModel();
volList = new JList(volunteers);
volList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane(volList);
scrollPane.setSize(500,300);
scrollPane.setLocation(100,50);
c.add(scrollPane);
bAdd = new JButton("Add");
bAdd.setSize( 100, 50 );
bAdd.setLocation( 20, 400 );
bAdd.addActionListener(this);
c.add(bAdd);
bEdit = new JButton("Edit");
bEdit.setSize( 100, 50 );
bEdit.setLocation( 150, 400 );
bEdit.addActionListener(this);
c.add(bEdit);
bRemove = new JButton("Remove");
bRemove.setSize( 100, 50 );
bRemove.setLocation( 280, 400 );
bRemove.addActionListener(this);
c.add(bRemove);
bClear = new JButton("Clear");
bClear.setSize( 100, 50 );
bClear.setLocation( 410, 400 );
bClear.addActionListener(this);
c.add(bClear);
bSave = new JButton("Save");
bSave.setSize( 100, 50 );
bSave.setLocation( 540, 400 );
bSave.addActionListener(this);
c.add(bSave);
bOpen = new JButton("Open");
bOpen.setSize( 100, 50 );
bOpen.setLocation( 670, 400 );
bOpen.addActionListener(this);
c.add(bOpen);
setSize( 800, 600 );
setLocation( 100, 100 );
setVisible(true);
volNumb = 0;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==bAdd) {
volNumb++;
CVolunteer defaultVol = new CVolunteer(volNumb, "", 1, 0, 0);
CDialog dialogWnd = new CDialog(this, "Add a Volunteer", defaultVol);
if (!dialogWnd.isCancelled()) {
volArray.add(dialogWnd.getAnswer());
volunteers.addElement(dialogWnd.getAnswer().getVolunteerLine());
volList.setSelectedIndex(volunteers.size()-1);
volList.ensureIndexIsVisible(volunteers.size()-1);
}
}
else if(e.getSource()==bEdit) {
int index=volList.getSelectedIndex();
if (index>=0) {
CDialog dialogWnd = new CDialog (this, "Edit a Volunteer", volArray.get(index));
if (!dialogWnd.isCancelled()) {
volArray.set(index, dialogWnd.getAnswer());
volunteers.set(index, dialogWnd.getAnswer().getVolunteerLine());
}
}
}
else if(e.getSource()==bRemove) {
int index=volList.getSelectedIndex();
if (index>=0) {
volArray.remove(index);
volunteers.remove(index);
if (volunteers.size()>0) {
if (index==volunteers.size()) {
index--;
}
volList.setSelectedIndex(index);
volList.ensureIndexIsVisible(index);
}
}
}
else if(e.getSource()==bClear) {
volArray.clear();
volunteers.clear();
}
else if (e.getSource()==bSave)
{
//my sorry attempt at writing a file.. ignore this!
try {
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int size = volArray.size();
for (int i = 0; i<size; i++)
{
output.write(volArray.get(i).getVolunteerLine() + "\n");
}
output.close();
}
catch (Exception e1) {
// TODO Auto-generated catch block
}
final JFileChooser fc = new JFileChooser();
}
else if (e.getSource()==bOpen)
{
}
}
public static void main(String[] args) {
TestDialog mainWnd = new TestDialog();
}
}
EDIT:
Here is some attempted code for my "Save" Button.... I still don't know if this is on the right track or not! It doesn't seem to be doing anything
else if (e.getSource()==bSave)
{
try
{
FileOutputStream fileOut = new FileOutputStream("???");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for(int i=0; i<volArray.size(); i++)
{
out.writeObject(volArray.get(i).getVolunteerLine());
}
out.close();
fileOut.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
}
final JFileChooser fc = new JFileChooser();
}

You have to use a specific format that you define to write in your file :
Add a serialize method in you volunteer class then you can iterate over them and serialize each of them.
String serialize() will encode all the members as a string then you can reconstruct at reading (on Open).
An example could be a coma separated list : member1=xxx, member2=xxx, ...
Or xml or json for more ease :)
At reading, it's the opposite, parse the content of the file and build your volunteers back !
Edit:
Saving:
Open a file in write mode
write all your n volunteers
at this point you should have n lines in your file
close the file
Reading:
Open your file in reading mode
Read it line by line
For each line
split over ','
build your volunteer
add it to volArray
close your file
Does it make sense for you ? Each of these steps are trivial with a simple google search
Edit :
Final JFileChooser fc = new JFileChooser();
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
// Here you can open the file and write to it
//
} else {
log.append("Open command cancelled by user." + newline);
}
You can do the same when on open, select the file then read from it

Related

Gui and binary files

I'm currently working on a project for a class I have, where we have to create a GUI that asks for a number, then read a binary files of 10,000 customers and return the other information on the one with the customer number entered. We also have to have an error that pops up as a JOptionPane when a number outside of 1-10,000 is entered. I'm having some problems with the error message, and my professor also said we need to have a method with this signature:
private Customer getCustomer(long custNumber) throws IOException
that searches the file and returns a customer object. I'm also not sure where exactly to do that. So I started with what I already know, and here's what I have:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class CustomerLocator extends JFrame
{
private JPanel panel;
private JLabel custNumLabel;
private JLabel custNameLabel;
private JLabel custDisLabel;
private JLabel custBalLabel;
private JLabel custPrefLabel;
private JTextField custNumField;
private JTextField custNameField;
private JTextField custDisField;
private JTextField custBalField;
private JTextField custPrefField;
private JButton findCustBut;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 500;
public CustomerLocator()
{
setTitle("Customer Locator");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
custNumLabel = new JLabel("Enter a valid Customer Number: ");
custNumField = new JTextField(10);
custNameLabel = new JLabel("Customer Name: ");
custNameField = new JTextField(10);
custNameField.setEditable(false);
custDisLabel = new JLabel("Customer Discount: ");
custDisField = new JTextField(10);
custDisField.setEditable(false);
custBalLabel = new JLabel("Customer Balance: ");
custBalField = new JTextField(10);
custBalField.setEditable(false);
custPrefLabel = new JLabel("Preferred? ");
custPrefField = new JTextField(10);
custPrefField.setEditable(false);
findCustBut = new JButton("Find this Customer!");
panel = new JPanel();
findCustBut.addActionListener(new ListenerToFindCustomer());
panel.add(custNumLabel);
panel.add(custNumField);
panel.add(findCustBut);
panel.add(custNameLabel);
panel.add(custNameField);
panel.add(custDisLabel);
panel.add(custDisField);
panel.add(custBalLabel);
panel.add(custBalField);
panel.add(custPrefLabel);
panel.add(custPrefField);
}
private class ListenerToFindCustomer implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String numEnteredStr;
long custNumEntered;
String custName;
boolean preferred;
String preferredDisplay;
double acctBal;
String acctBalDisplay;
double discount;
String discountDisplay;
numEnteredStr = custNumField.getText();
custNumEntered = Long.parseLong(numEnteredStr);
int ct=0;
try
{
FileInputStream inStream =
new FileInputStream("c:\\cps\\CustomerObjects.dat");
// DataInputStream inputFile = new DataInputStream(inStream);
ObjectInputStream objectInputFile =
new ObjectInputStream(inStream);
while(true)
{
ct++;
Customer obj = (Customer)objectInputFile.readObject();
//System.out.println(obj.getCustName());
if (custNumEntered == obj.getCustNum())
{
custName = obj.getCustName();
acctBal = obj.getBalance();
acctBalDisplay = Double.toString(acctBal);
discount = obj.getDiscount();
discountDisplay = Double.toString(discount);
preferred = obj.getPreferred();
preferredDisplay = Boolean.toString(preferred);
custNameField.setText(custName);
custBalField.setText(acctBalDisplay);
custPrefField.setText(preferredDisplay);
custDisField.setText(discountDisplay);
if (custNameField == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
}
}
}
catch (Exception ex)
{
System.out.println(ex.toString());
}
}
}
public static void main(String[] args)
{
new CustomerLocator();
}
}
So, with this, the JOptionPane doesn't show up, so my questions are
1. How do I get the error message to pop up?
2. How do I incorporate the method my professor requested?
Your code
if (custNameField == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
should read
if (custName == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
It should also be moved outside of the while loop.
You also need a way to break the loop once you reach the end of the file.
Everything inside and including your try { ... } catch (Exception ex) { ... } can be moved to the method that your instructor suggests.
You should also change the try-catch to have another catch (IOException ioEx) { throw ioEx; }

Java applet freezes whenever I go back to intro screen of my game

I'm trying to create a java applet which lets a user play the 20 questions game, however when a game has ended and I click on replay the game, it freezes when it's supposed to go back to the intro screen. I've presented my code below:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import java.util.ArrayList;
//json classes
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
//google classes
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
public class Interface extends JPanel implements ActionListener, PropertyChangeListener{
//removes serialization warning
private static final long serialVersionUID = 1L;
/**Instances for the Buttons**/
private JButton noButton;
private JButton yesButton;
private JButton unsureButton;
private JButton replayButton;
private JButton newGame;
private JButton addQuestion;
/**Instances for the text used**/
private JLabel questionLabel;
/**Instances for the dialog boxes**/
private JDialog addQuestionDialog;
private JOptionPane addQuestionPane;
private JDialog nameDialog;
private JOptionPane namePane;
/**Instances for the textfields**/
private TextField questionTextField;
private TextField mqlYesTextField;
private TextField mqlNoTextField;
private TextField nameTextField;
/**Instance for keeping track of game state**/
private boolean isGameOver = false;
/**keeps track of the current and previous questions**/
private int currentQuestionId = 1, previousQuestionId = 1;
/**Instances of Arraylist**/
private ArrayList<Integer> alreadyAskedQuestions;
private ArrayList<Integer> columnValues;
/**number of questions asked to the user so far**/;
private int questionsAsked = 1;
private JSONArray mqlResults = null;
private Model sqlModel;
private String mqlQuery = "[{\"name\":null, \"limit\":5";
/**Constructor**/
public Interface(){
super();
sqlModel = new Model();
questionTextField = new TextField(50);
mqlYesTextField = new TextField(100);
mqlNoTextField = new TextField(100);
alreadyAskedQuestions = new ArrayList<Integer>(21);
columnValues = new ArrayList<Integer>(21);
initGUI();
}
public void initGUI() {
setLayout(new GridBagLayout());
removeAll();
JLabel introLabel = createIntroLabel();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
add(introLabel,c);
GridBagConstraints d = new GridBagConstraints();
d.fill = GridBagConstraints.BOTH;
d.ipady = 200;
d.gridx = 0;
d.gridy = 1;
d.weighty = 0.5;
add(createMainPanel(),d);
}
public JPanel createMainPanel() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(1,3));
JPanel recentSearchesPanel = new JPanel();
recentSearchesPanel.setLayout(new GridLayout(6,1));
recentSearchesPanel.setBackground(Color.BLACK);
//create Recent searches text
JLabel recentSearchText = new JLabel("Recent searches:");
recentSearchText.setForeground(Color.WHITE);
recentSearchText.setFont(new Font("Gabriola",Font.BOLD,30));
//add text into Panel
recentSearchesPanel.add(recentSearchText);
ArrayList<String> recentSearches = sqlModel.getRecentSearches();
for(int i=0; i<recentSearches.size(); i++) {
JLabel label = new JLabel(recentSearches.get(i));
label.setForeground(Color.WHITE);
label.setFont(new Font("Gabriola",Font.BOLD,30));
label.setHorizontalAlignment(SwingConstants.CENTER);
recentSearchesPanel.add(label);
}
//add recent searches in the leftmost column of the main panel
mainPanel.add(recentSearchesPanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
buttonPanel.setBackground(Color.BLACK);
newGame = new JButton(new ImageIcon("src\\Icons\\icon_play_en.png"));
newGame.setBackground(Color.BLACK);
newGame.setOpaque(true);
newGame.addActionListener(this);
buttonPanel.add(newGame);
GridBagConstraints d = new GridBagConstraints();
d.fill = GridBagConstraints.HORIZONTAL;
d.gridy = 1;
addQuestion = new JButton(new ImageIcon("src\\Icons\\icon_addQuestion.png"));
addQuestion.setBackground(Color.BLACK);
addQuestion.setOpaque(true);
addQuestion.addActionListener(this);
buttonPanel.add(addQuestion,d);
mainPanel.add(buttonPanel);
JPanel popularSearchesPanel = new JPanel();
popularSearchesPanel.setLayout(new GridLayout(6,1));
popularSearchesPanel.setBackground(Color.BLACK);
JLabel popularSeachText = new JLabel("Popular searches:");
popularSeachText.setFont(new Font("Gabriola",Font.BOLD,30));
popularSeachText.setForeground(Color.WHITE);
popularSearchesPanel.add(popularSeachText);
ArrayList<String> popularSearches = sqlModel.getPopularSearches();
for(int i=0; i<popularSearches.size(); i++) {
JLabel label = new JLabel(popularSearches.get(i));
label.setForeground(Color.WHITE);
label.setFont(new Font("Gabriola",Font.BOLD,30));
label.setHorizontalAlignment(SwingConstants.CENTER);
recentSearchesPanel.add(label);
}
mainPanel.add(popularSearchesPanel);
return mainPanel;
}
/**The initGUI method will create the GUI and hold all its components**/
public void gameGUI(){
//the layout is a new BorderLayout
setLayout(new GridLayout(4,1));
//clear all components currently in panel
removeAll();
add(createIntroLabel());
mqlResults = getMQLData(mqlQuery + "}]");
//are we in game over state
isGameOver = ((mqlResults != null) && ( (mqlResults.size() <= 1) || (questionsAsked == 20) ));
add(createQuestionsPanel(isGameOver));
add(createGuessedPanel());
add(createAnswerButtonPanel());
//calling revalidate, avoids an error of the programme freezing
revalidate();
}
/**Create a panel which holds the labels and the button that will change the labels color **/
private JLabel createIntroLabel()
{
JLabel introLabel = new JLabel("Twenty Questions");
introLabel.setBackground(Color.BLACK);
introLabel.setForeground(Color.WHITE);
introLabel.setFont(new Font("Forte",Font.BOLD,108));
introLabel.setOpaque(true);
return introLabel;
}
/**The createQuestions method will display the current question at the time**/
private JPanel createQuestionsPanel(boolean gameOver){
//Create a new panel
JPanel questionPanel = new JPanel();
questionPanel.setBackground(Color.BLACK);
questionPanel.setLayout(new BorderLayout());
if(gameOver) {
if(mqlResults.size() > 0)
questionLabel = new JLabel("is your Character: "+((JSONObject)mqlResults.get(0)).get("name") );
else //noone was found
questionLabel = new JLabel("couldn't find any matches :(");
//addQuestion();
}
else
questionLabel = new JLabel("Q"+questionsAsked+": "+sqlModel.getData("questionid","questionid = "+currentQuestionId, 2));
//make the label centred
questionLabel.setHorizontalAlignment(SwingConstants.CENTER);
//the Foreground is white
questionLabel.setForeground(Color.WHITE);
questionLabel.setFont(new Font("Comic Sans MS",Font.PLAIN,30));
//add Label to the panel
questionPanel.add(questionLabel);
//return questionPanel
return questionPanel;
}
private JPanel createGuessedPanel() {
JPanel guessedPanel = new JPanel();
guessedPanel.setLayout(new GridLayout(5,1));
guessedPanel.setBackground(Color.BLACK);
System.out.println(mqlQuery);
if((questionsAsked > 1) && (mqlResults.size() > 0)) {
for (Object result : mqlResults) {
JLabel resultLabel = new JLabel((String)((JSONObject)result).get("name"));
resultLabel.setHorizontalAlignment(SwingConstants.CENTER);
resultLabel.setForeground(Color.WHITE);
resultLabel.setFont(new Font("Comic Sans MS",Font.PLAIN,30));
guessedPanel.add(resultLabel);
}
}
return guessedPanel;
}
private JPanel createAnswerButtonPanel()
{
JPanel answerPanel = new JPanel();
answerPanel.setLayout(new GridLayout(1,3));
//MQL query couldn't find any results
if ( (mqlResults != null) && (mqlResults.size() == 0) ) {
replayButton = new JButton(new ImageIcon(getClass().getResource("/Icons/replay_icon.png")));
replayButton.setBackground(Color.ORANGE);
replayButton.setOpaque(true);
replayButton.addActionListener(this);
answerPanel.add(replayButton);
}
else {
//the no button will be added to the panel
noButton = new JButton("NO");
noButton.setBackground(Color.RED);
noButton.setOpaque(true);
Font noFont = new Font("Bauhaus 93",Font.BOLD,30);
noButton.setFont(noFont);
noButton.addActionListener(this);
answerPanel.add(noButton);
//if the initial question has already been asked, create an unsure button
if( (questionsAsked > 1) && !isGameOver )
{
unsureButton = new JButton("UNSURE");
unsureButton.setBackground(Color.ORANGE);
unsureButton.setOpaque(true);
Font maybeFont = new Font("Bauhaus 93",Font.BOLD,30);
unsureButton.setFont(maybeFont);
unsureButton.addActionListener(this);
answerPanel.add(unsureButton);
}
//the yes button will be added to the panel
yesButton = new JButton("YES");
Font yesFont = new Font("Bauhaus 93",Font.BOLD,30);
yesButton.setFont(yesFont);
yesButton.setBackground(Color.GREEN);
yesButton.setOpaque(true);
yesButton.addActionListener(this);
answerPanel.add(yesButton);
//return answerPanel
}
return answerPanel;
}
private int getNextQuestionId(int previousQuestionId) {
int result;
while(true) {
double random = Math.random();
result = sqlModel.chooseQuestion(previousQuestionId, random);
//if question selected has already been asked in this game session
System.out.println(alreadyAskedQuestions);
if(alreadyAskedQuestions.contains(result)) {
/*int value = Integer.parseInt(sqlModel.getData("questionvalues", "questionid = "+result, previousQuestionId + 1));
if(value>=5) {
value = value - 5;
//change value in (result, previousQuestionId) cell
sqlModel.updateEntry("questionvalues", "`"+previousQuestionId+"` = "+value, "questionid = "+result);
int previousTotal = Integer.parseInt(sqlModel.getData("questionvalues", "questionid = 5000", previousQuestionId+1));
int newTotal = previousTotal - 5;
//decrement total value by 5, in the previousQuestionId column
sqlModel.updateEntry("questionvalues", "`"+previousQuestionId+"` = "+newTotal, "questionid = 5000");
}*/
}
else
return result;
}
}
private JSONArray getMQLData(String query) {
JSONArray results = null;
try {
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
url.put("query", query);
url.put("key", "AIzaSyAA0uodQOasgTIaGRHUeoKwnfS-FVoDxJc");
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse httpResponse = request.execute();
JSONObject response = (JSONObject)parser.parse(httpResponse.parseAsString());
results = (JSONArray)response.get("result");
} catch (Exception ex) {
ex.printStackTrace();
}
return results;
}
private void addQuestion() {
questionTextField = new TextField(50);
Object[] componentsArray = {"Question:", questionTextField, "MQLYes:", mqlYesTextField, "MQLNo:", mqlNoTextField};
Object[] options = {"Enter", "Cancel"};
addQuestionDialog = new JDialog(new JFrame(),"Add question");
addQuestionPane = new JOptionPane(componentsArray, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
int x = getX() + getWidth()/2, y = getY() + getHeight()/2;
addQuestionDialog.setContentPane(addQuestionPane);
addQuestionDialog.setResizable(false);
addQuestionDialog.setSize(300,210);
addQuestionDialog.setVisible(true);
addQuestionDialog.setLocation(x, y);
addQuestionDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
addQuestionPane.addPropertyChangeListener(this);
}
/** This method reacts to state changes in the option pane. */
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (addQuestionDialog.isVisible() && (e.getSource() == addQuestionPane) && (JOptionPane.VALUE_PROPERTY.equals(prop) || JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
Object value = addQuestionPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
//ignore reset
return;
}
//Reset the JOptionPane's value.
//If you don't do this, then if the user
//presses the same button next time, no
//property change event will be fired.
addQuestionPane.setValue(
JOptionPane.UNINITIALIZED_VALUE);
if (value.equals("Enter")) {
String questionTypedText = questionTextField.getText();
String mqlYesTypedText = mqlYesTextField.getText();
String mqlNoTypedText = mqlNoTextField.getText();
sqlModel.addQuestion(questionTypedText, mqlYesTypedText, mqlNoTypedText);
questionTextField.setText("");
mqlYesTextField.setText("");
mqlNoTextField.setText("");
} else { //user closed dialog or clicked cancel
addQuestionDialog.setVisible(false);
}
}
else if (nameDialog.isVisible() && (e.getSource() == namePane) && (JOptionPane.VALUE_PROPERTY.equals(prop) || JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
Object value = namePane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
//ignore reset
return;
}
namePane.setValue(
JOptionPane.UNINITIALIZED_VALUE);
if (value.equals("Enter")) {
sqlModel.addCelebrity(alreadyAskedQuestions, columnValues, nameTextField.getText());
}
//else, user clicked cancel, in either case, close the Dialog box
nameDialog.setVisible(false);
mqlQuery = "[{\"name\":null, \"limit\":5";
isGameOver = false;
initGUI();
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(newGame)) {
gameGUI();
}
else if(e.getSource().equals(addQuestion)) {
addQuestion();
}
//if you press the no button
else if (e.getSource().equals(noButton)) {
if(!isGameOver) {
//don't update questionvalues for this case
alreadyAskedQuestions.add(currentQuestionId);
columnValues.add(-1);
//update MQLQuery
String s = sqlModel.getData("questionid", "questionid = "+currentQuestionId, 4);
if( (questionsAsked > 1) && !s.equals("") )
mqlQuery = mqlQuery + ", \"ms"+questionsAsked+":"+s;
else
mqlQuery = mqlQuery + s;
currentQuestionId = getNextQuestionId(previousQuestionId);
questionsAsked++;
gameGUI();
}
else {
//create new JOptionPane asking for celebrity name
nameTextField = new TextField(50);
Object[] componentsArray = {"Please enter your characters name:", questionTextField};
Object[] options = {"Enter", "Cancel"};
nameDialog = new JDialog();
namePane = new JOptionPane(componentsArray, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
int x = getX() + getWidth()/2, y = getY() + getHeight()/2;
nameDialog.setContentPane(namePane);
nameDialog.setResizable(false);
nameDialog.setSize(300,210);
nameDialog.setVisible(true);
nameDialog.setLocation(x, y);
nameDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
addQuestionPane.addPropertyChangeListener(this);
}
}
//if you pressed the yes button
else if (e.getSource().equals(yesButton)) {
if(isGameOver) {
String name = ""+((JSONObject)mqlResults.get(0)).get("name");
sqlModel.addCelebrity(alreadyAskedQuestions, columnValues, name);
mqlQuery = "[{\"name\":null, \"limit\":5";
isGameOver = false;
initGUI();
}
else {
//update the value in the questionValues table
if(previousQuestionId != currentQuestionId) {
int value = Integer.parseInt(sqlModel.getData("questionvalues", "questionid = "+currentQuestionId, previousQuestionId + 1));
value += 5;
//back ticks around previousQuestionId, so SQL compiler knows it's a column name
//change value in (currentQuestionId, previousQuestionId) cell
sqlModel.updateEntry("questionvalues", "`"+previousQuestionId+"` = "+value, "questionid = "+currentQuestionId);
int previousTotal = Integer.parseInt(sqlModel.getData("questionvalues", "questionid = 5000", previousQuestionId+1));
int newTotal = previousTotal + 5;
//decrement total value by 5, in the previousQuestionId column
sqlModel.updateEntry("questionvalues", "`"+previousQuestionId+"` = "+newTotal, "questionid = 5000");
}
alreadyAskedQuestions.add(currentQuestionId);
columnValues.add(1);
//update MQLQuery
String s = sqlModel.getData("questionid", "questionid = "+currentQuestionId, 3);
if(questionsAsked > 1)
mqlQuery = mqlQuery + ", \"ms"+questionsAsked+":"+s;
else
mqlQuery = mqlQuery + s;
if (questionsAsked > 1)
previousQuestionId = currentQuestionId;
currentQuestionId = getNextQuestionId(previousQuestionId);
questionsAsked++;
gameGUI();
}
}
//if you pressed the unsure button
else if (e.getSource().equals(unsureButton)) {
//update the value in the questionValues table
if(previousQuestionId != currentQuestionId) {
int value = Integer.parseInt(sqlModel.getData("questionvalues", "questionid = "+currentQuestionId, previousQuestionId + 1));
if(value >= 5) {
value -= 5;
//back ticks around previousQuestionId, so SQL compiler knows it's a column name
sqlModel.updateEntry("questionvalues", "`"+previousQuestionId+"` = "+value, "questionid = "+currentQuestionId);
//change value in (result, previousQuestionId) cell
sqlModel.updateEntry("questionvalues", "`"+previousQuestionId+"` = "+value, "questionid = "+currentQuestionId);
int previousTotal = Integer.parseInt(sqlModel.getData("questionvalues", "questionid = 5000", previousQuestionId+1));
int newTotal = previousTotal - 5;
//decrement total value by 5, in the previousQuestionId column
sqlModel.updateEntry("questionvalues", "`"+previousQuestionId+"` = "+newTotal, "questionid = 5000");
}
}
alreadyAskedQuestions.add(currentQuestionId);
columnValues.add(0);
if (questionsAsked > 1)
previousQuestionId = currentQuestionId;
currentQuestionId = getNextQuestionId(previousQuestionId);
questionsAsked++;
gameGUI();
}
else if(e.getSource().equals(replayButton)) {
mqlQuery = "[{\"name\":null, \"limit\":5";
isGameOver = false;
initGUI();
}
}
}
When it's game over, the user is presented with the following screen, however clicking replay freezes the applet, when all it really does is call the initGUI method, which runs perfectly fine when the applet first starts. I've added a print statement at the end of the initGUI method and it shows up in my console when I click on replay, so the code successfully goes through the initGUI method, however it doesn't change the appearance of the applet.
I managed to resolve my problem, apparently calling revalidate() at the end of my GUI methods is a must, else the screen doesn't update, even though the JFrame is successfully adding new components.

Need to make Prev and Next JButton Java

Hello everyone I need to make Prev and next Jbutton to read lines from a csv file to JTextField I managed to make Load button but now I am stuck. This is for my homework. So if anyone could help it would be nice :D. This is the question in homework:
The Next and Previous buttons display the next or previous order from the file.
Use the String’s split method. Separate methods are needed for next, previous.
Do not duplicate any significant amount of code. Guideline is 3 lines or less is OK
to duplicate.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class OrderSystem extends JFrame implements ActionListener
{
private JButton exit, cal, save, clear, load, prev, next;
private JTextField text, text1, text2, text3;
private int counter;
//ArrayList<String> splitLine = new ArrayList<String>();
String[] textLine = new String[3];
public OrderSystem()
{
JFrame myFrame = new JFrame("{Your Name} Item Orders Calculator");
myFrame.setLayout(new BorderLayout(2, 2));
JPanel panel = new JPanel();
panel.setLayout( new GridLayout(0, 2));
panel.add( new JLabel("Item name: ", SwingConstants.RIGHT));
text = new JTextField("", 25);
panel.add( text );
panel.add( new JLabel("Number of: ", SwingConstants.RIGHT));
text1 = new JTextField("", 20);
panel.add( text1 );
panel.add( new JLabel("Cost: ", SwingConstants.RIGHT));
text2 = new JTextField("", 20);
panel.add( text2 );
panel.add( new JLabel("Amount owed: ", SwingConstants.RIGHT));
text3 = new JTextField("", 20);
text3.setEnabled(false);
panel.add( text3 );
add(panel,BorderLayout.CENTER);
JPanel panelS = new JPanel( new FlowLayout(FlowLayout.CENTER, 20,3) );
// Create some buttons to place in the south area
cal = new JButton("Calculate");
save = new JButton("Save");
clear = new JButton("Clear");
exit = new JButton("Exit");
load = new JButton("Load");
prev = new JButton("<prev");
next = new JButton("next>");
exit.addActionListener(this);
clear.addActionListener(this);
cal.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
prev.addActionListener(this);
next.addActionListener(this);
panelS.add(cal);
panelS.add(save);
panelS.add(clear);
panelS.add(exit);
panelS.add(load);
panelS.add(prev);
panelS.add(next);
add(panelS, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == exit)
{
System.exit(0);
}
else if(e.getSource() == cal)
{
double amount = Double.parseDouble(text1.getText()) * Double.parseDouble(text2.getText());
text3.setText(String.format(Locale.ENGLISH, "%.2f", amount));
}
else if(e.getSource() == save)
{
boolean append = true;
try
{
BufferedWriter out = new BufferedWriter(new FileWriter("121Lab1.csv", append));
out.write(String.format("%s,%s,%s,%s", text.getText(), text1.getText(), text2.getText(), text3.getText()));
out.newLine();
out.flush();
out.close();
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Error");
}
counter++;
}
else if(e.getSource() == clear)
{
text.setText("");
text1.setText("");
text2.setText("");
text3.setText("");
}
else if(e.getSource() == load)
{
try {
String splitLine;
BufferedReader br = new BufferedReader( new FileReader("121Lab1.csv"));
while ((splitLine = br.readLine()) != null)
{
textLine = splitLine.split(",");
text.setText(textLine[0]);
text1.setText(textLine[1]);
text2.setText(textLine[2]);
text3.setText(textLine[3]);
}
}
catch (IOException exp)
{
JOptionPane.showMessageDialog(null, "Error no file found.");
}
}
else if(e.getSource() == prev)
{
//Prev line
}
else if(e.getSource() == next)
{
//Read next line
}
}
public static void main(String[] args)
{
OrderSystem main = new OrderSystem();
main.setTitle("Item Orders Calculator");
main.setSize(450, 150);
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
}
}
Load the csv data upon clicking the load button. I recommend using OpenCSV for reading the whole csv file in one go. CSVReader's readAll() will give you a list of String array.
else if (e.getSource() == load) {
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader("csv.csv"));
myEntries = reader.readAll();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
ptr = 1;
navigate(ptr);
}
myEntries should be instance level
private List<String[]> myEntries;
Define an instance level int variable that will decrement when prev button is pressed otherwise increment when next button is pressed.
private int ptr;
Define a private method that will retrieve data from the myEntries list based on the index that it will receive.
private void navigate(int index){
String[] data = myEntries.get(index);
text.setText(data[0]);
text1.setText(data[1]);
text2.setText(data[2]);
text3.setText(data[3]);
}
In your prev and next button, increment/decrement ptr then happily use the navigate method passing the resultant value.
else if (e.getSource() == prev) {
if(ptr > 1){
ptr--;
navigate(ptr);
}
} else if (e.getSource() == next) {
if(ptr < (myEntries.size()-1)){ //lists are 0 based
ptr++;
navigate(ptr);
}
}

Java GUI Programming Only Restarts once

I have a program here that changes an avatars hat and earrings
the problem is that it only restarts once (the load button only works once)
This is what I have:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.JTextArea;
public class Lab14_Navarro extends JFrame {
private int x,y,z;
private Container game;
private JComboBox Head;
private JComboBox Ear;
private JLabel Avatar;
private JTextArea details;
private String []Hat = {"No Hat", "Captain Hat", "Black Leather Hat"};
private JButton load;
private String []Earrings = {"No Earrings", "Silver Dangling Earrings", "Gold Dangling Earrings"};
private ImageIcon [] Accessories =
{ new ImageIcon("blackleather.PNG"),//0
new ImageIcon("blackleather_goldear.PNG"),//1
new ImageIcon("blackleather_silverear.PNG"),//2
new ImageIcon("captainhat.PNG"),//3
new ImageIcon("captainhat_goldear.PNG"),//4
new ImageIcon("captainhat_silverear.PNG"),//5
new ImageIcon("goldear.PNG"),//6
new ImageIcon("noaccessories.PNG"),//7
new ImageIcon("silverear.PNG")};//8
/**
* Creates a new instance of <code>Lab14_Navarro</code>.
*/
public Lab14_Navarro() {
getContentPane().removeAll();
setTitle("Avatar!");
setSize(250,450);
setLocationRelativeTo(null);
game = getContentPane();
game.setLayout(new FlowLayout());
Head = new JComboBox(Hat);
Ear = new JComboBox(Earrings);
Avatar = new JLabel(Accessories[7]);
load = new JButton("Load Image");
details = new JTextArea("AVATAR DETAILS: "+"\n"+" Hat: "+Hat[Head.getSelectedIndex()]+"\n"+" Earrings: "+Earrings[Ear.getSelectedIndex()]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);
Head.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox temphead = (JComboBox) e.getSource();
int temphat = (int) temphead.getSelectedIndex();
x = temphat;
}
});
Ear.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox tempear = (JComboBox) e.getSource();
int tempearrings = (int) tempear.getSelectedIndex();
y = tempearrings;
}
});
load.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
getContentPane().removeAll();
if(x==0&&y==0){
z = 7;
}
if(x==0&&y==1){
z = 8;
}
if(x==0&&y==2){
z = 6;
}
if(x==1&&y==0){
z = 3;
}
if(x==1&&y==1){
z = 5;
}
if(x==1&&y==2){
z = 4;
}
if(x==2&&y==0){
z = 0;
}
if(x==2&&y==1){
z = 2;
}
if(x==2&&y==2){
z = 1;
}
setTitle("Avatar");
setSize(250,450);
setLocationRelativeTo(null);
game = getContentPane();
game.setLayout(new FlowLayout());
Head = new JComboBox(Hat);
Ear = new JComboBox(Earrings);
Avatar = new JLabel(Accessories[z]);
load = new JButton("Load Image");
details = new JTextArea("AVATAR DETAILS: "+"\n"+" Hat: "+Hat[x]+"\n"+" Earrings: "+Earrings[y]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);
}
});
}
public static void main(String[] args) {
Lab14_Navarro fs = new Lab14_Navarro();
fs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Any help is accepted thanks
I just started Java so I'm not that good... yet
When you write, for the second time:
load = new JButton("Load Image");
you're creating a new button, however, you are not giving it a new ActionListener
On another note, you don't need to create a new Button, your original load button is still there, you need only to add it to the contentPane again.

DocumentListener Java, How do I prevent empty string in JTextBox?

I have been working on a personal project to get better with programming. My goal is to make it much more robust, I am just starting. I am a current computer science student. Anyway, I am working on making a portion of the program as shown. I calculates the hourly wage and provides some outputs I havent implemented yet. I'm using DocumentListener so it it will automatically calculate. I am getting an error when the the text is removed completely from a box.I tried to fix it with the if statement:
if (tipMon.equals("") || tipMon == null) {
tipMon.setText("0");
}
Here is what I have so far. It's not done yet and I apologize for the noob code. I started 2 months ago with actual coding.
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.FieldView;
public class deliveryDocListener extends JFrame implements ActionListener,
DocumentListener{
private JLabel mon, tues, wed, thurs, fri, sat, sun, hourlyWage, blank, row2, monWage,
tuesWage,wedWage,thursWage, friWage, satWage, sunWage, total, totalTips, totalHours,
totalHourlyEarnings, totalPay, weekPay;
private JTextField hourlyWageInput, tipMon, tipTues, tipWed, tipThurs, tipFri, tipSat, tipSun,
hourMon, hourTues, hourWed, hourThurs, hourFri, hourSat, hourSun;
public deliveryDocListener(){
super("Delivery Helper v0.1 Alpha");
setLayout(new GridLayout(0,4));
hourlyWage = new JLabel("Hourly Wage: ");
add(hourlyWage);
hourlyWageInput = new JTextField("7.25", 5);
add(hourlyWageInput);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
row2 = new JLabel("Day of the Week");
add(row2);
row2 = new JLabel("Tips");
add(row2);
row2 = new JLabel("Hours Worked");
add(row2);
row2 = new JLabel("Hourly Earnings");
add(row2);
mon = new JLabel("Monday");
add(mon);
tipMon = new JTextField("0");
Document tipMonListener = tipMon.getDocument();
//Document class doc variable stores what happens in the getDocument()
//method, getDocument() i think is what checked it real time we shall see
tipMonListener.addDocumentListener(this);
//add listener to he text field, this refers to most recent object (tipMon = new JTextField("0");"
//notice how its purple is the same as new where the object got made?
add(tipMon);
hourMon = new JTextField("0");
Document hourMonListener = hourMon.getDocument();
hourMonListener.addDocumentListener(this);
add(hourMon);
monWage = new JLabel("0");
add(monWage);
tues = new JLabel("Tuesday");
add(tues);
tipTues = new JTextField("0");
add(tipTues);
hourTues = new JTextField("0");
add(hourTues);
tuesWage = new JLabel("0");
add(tuesWage);
wed = new JLabel("Wednesday");
add(wed);
tipWed = new JTextField("0");
add(tipWed);
hourWed = new JTextField("0");
add(hourWed);
wedWage = new JLabel("0");
add(wedWage);
thurs = new JLabel("Thursday");
add(thurs);
tipThurs = new JTextField("0");
add(tipThurs);
hourThurs = new JTextField("0");
add(hourThurs);
thursWage = new JLabel("0");
add(thursWage);
fri = new JLabel("Friday");
add(fri);
tipFri = new JTextField("0");
add(tipFri);
hourFri = new JTextField("0");
add(hourFri);
friWage = new JLabel("0");
add(friWage);
sat = new JLabel("Saturday");
add(sat);
tipSat = new JTextField("0");
add(tipSat);
hourSat = new JTextField("0");
add(hourSat);
satWage = new JLabel("0");
add(satWage);
sun = new JLabel("Sunday");
add(sun);
tipSun = new JTextField("0");
add(tipSun);
hourSun = new JTextField("0");
add(hourSun);
sunWage = new JLabel("0");
add(sunWage);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
total = new JLabel("Total: ");
add(total);
totalTips = new JLabel("totalTipsOutput");
add(totalTips);
totalHours = new JLabel("totalHoursOutput");
add(totalHours);
totalHourlyEarnings = new JLabel("totalHourlyEarningsOutput");
add(totalHourlyEarnings);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
totalPay = new JLabel("Gross Income: ");
add(totalPay);
weekPay = new JLabel("totalPayOutput");
add(weekPay);
}
#Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
#Override
public void insertUpdate(DocumentEvent e) {
//executes when someone enters text into input
String tipMonStr = tipMon.getText();
//monWage.setText(tipMonStr);
String hourMonStr = hourMon.getText();
double x = Double.parseDouble(tipMonStr);
double y = Double.parseDouble(hourMonStr);
double z = Double.parseDouble(hourlyWageInput.getText());
if (tipMonStr.length() == 0) {
tipMon.setText("0");
}
if (hourMonStr.length() == 0) {
y = 0;
hourMonStr = "0";
}
if (hourlyWageInput.getText().length() == 0) {
z = 0;
//String z = "0";
}
monWage.setText(Double.toString((z*y+x)/y));
//bug when nothing in cell because no number (0) to use in math
}
#Override
public void removeUpdate(DocumentEvent e) {
//executes when someone enters text into input
String tipMonStr = tipMon.getText();
//monWage.setText(tipMonStr);
String hourMonStr = hourMon.getText();
double x = Double.parseDouble(tipMonStr);
double y = Double.parseDouble(hourMonStr);
double z = Double.parseDouble(hourlyWageInput.getText());
monWage.setText(Double.toString((z*y+x)/y));
if (tipMon.equals("") || tipMon == null) {
tipMon.setText("0");
}
}
public void updateLog(DocumentEvent e, String action) {
monWage.setText(Double.toString(5));
}
#Override
public void actionPerformed(ActionEvent arg0) {
monWage.setText(Double.toString(5));
}
}
As #HFOE suggests, InputVerifier is the right choice, but verify() "should have no side effects." Instead, invoke calcProduct() in shouldYieldFocus().
/**
* #see http://stackoverflow.com/a/11818946/230513
*/
private class MyInputVerifier extends InputVerifier {
private JTextField field;
private double value;
public MyInputVerifier(JTextField field) {
this.field = field;
}
#Override
public boolean shouldYieldFocus(JComponent input) {
if (verify(input)) {
field.setText(String.valueOf(value));
calcProduct();
return true;
} else {
field.setText(ZERO);
field.selectAll();
return false;
}
}
#Override
public boolean verify(JComponent input) {
try {
value = Double.parseDouble(field.getText());
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
I'll make this an answer: I wouldn't use a DocumentListener for this purpose as it seems to me the wrong tool for the job. For one, it is continually listening and updating the results while the user is still entering data, data that is as yet incomplete, into the JTextField. Much better would be to use an ActionListener added to a JButton or to your JTextFields.
I suppose you could use a FocusListener, but even that concerns me since it is quite low-level.
Also: consider using an InputVerifier to validate your input.
Also: consider displaying your tabular data in a JTable where the 1st and 2nd columns are editable but the others are not.
Edit
I'm not sure if this is kosher, but it could work if you do your calculation from within the verifier. For example, updated for generality:
import javax.swing.*;
/**
* #see http://stackoverflow.com/a/11818183/522444
*/
public class VerifierEg {
private static final String ZERO = "0.0";
private JTextField field1 = new JTextField(ZERO, 5);
private JTextField field2 = new JTextField(ZERO, 5);
private JTextField resultField = new JTextField(ZERO, 10);
private void createAndShowGui() {
resultField.setEditable(false);
resultField.setFocusable(false);
JPanel mainPanel = new JPanel();
final JTextField[] fields = {field1, field2};
mainPanel.add(field1);
mainPanel.add(new JLabel(" x "));
mainPanel.add(field2);
mainPanel.add(new JLabel(" = "));
mainPanel.add(resultField);
for (JTextField field : fields) {
field.setInputVerifier(new MyInputVerifier(field));
}
JFrame frame = new JFrame("VerifierEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void calcProduct() {
double d1 = Double.parseDouble(field1.getText());
double d2 = Double.parseDouble(field2.getText());
double prod = d1 * d2;
resultField.setText(String.valueOf(prod));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
VerifierEg eg = new VerifierEg();
eg.createAndShowGui();
}
});
}
/**
* #see http://stackoverflow.com/a/11818946/230513
*/
private class MyInputVerifier extends InputVerifier {
private JTextField field;
private double value;
public MyInputVerifier(JTextField field) {
this.field = field;
}
#Override
public boolean shouldYieldFocus(JComponent input) {
if (verify(input)) {
field.setText(String.valueOf(value));
calcProduct();
return true;
} else {
field.setText(ZERO);
field.selectAll();
return false;
}
}
#Override
public boolean verify(JComponent input) {
try {
value = Double.parseDouble(field.getText());
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
}
use JSpinner or JFormattedTextField with Number instance, then DocumentListener should be works correctly, no needed to parse String to Number instance
otherwise you have to use DocumentFilter for JTextField for filtering non numeric chars, rest (counting) stays unchanged, stil required robust parsing String to the Number instance

Categories