Java: Getting a different result in runnable jar compared to eclipse - java

So I've been making a game for someone's birthday, I finally finished, but I'm having issues exporting it into a runnable jar file. What the game is is similar to "Who wants to be a millionaire", so it opens a window asking the contestant their name, then it goes on to ask the questions. At the end, it opens a letter that I wrote to them.
Now for the actual issue. I run the project in Eclipse and it works like a charm. However when I run it as a jar, I get the name prompt, then it all closes down. I don't get any error messages that I can see. I've tried running it through command prompt to see if anything would happen but no dice. Any help would be greatly appreciated with this!
EDIT: Below is my Start class and my JGame class:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class start {
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy/MM/dd");
Date bday = sdformat.parse("2020/02/01");
LocalDate now = LocalDate.now();
String toda = dtf.format(now);
Date today = sdformat.parse(toda);
if (today.after(bday)) {
new JWelcome();
} else {
new JWrongDate();
}
}
}
JGame:
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.text.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class JGame extends JWin {
private static final long serialVersionUID = 1L;
private JLabel jlabel;
private JWelcome jwelcome;
private JGWindowListener jgwl;
private JGMBar jgmb;
private JPanel northpanel;
private JPanel centerpanel;
private JPanel eastpanel;
private JPanel jsouthpanel;
private JButton jbutton_A;
private JButton jbutton_B;
private JButton jbutton_C;
private JButton jbutton_D;
private JButton jbfifty_fifty;
private JTArea jtarea;
private JGameListener jgml;
private JFile jfile;
private JFile jfile_A;
private JFile jfile_B;
private JFile jfile_C;
private JFile jfile_D;
private JFile jsolution;
private String answer_A;
private String answer_B;
private String answer_C;
private String answer_D;
private String solution;
// private JLabel jwon;
private int index;
public JGame(JWelcome jwelcome) throws ParseException {
super();
this.jwelcome = jwelcome;
jgwl = new JGWindowListener(this);
jgml = new JGameListener(this);
jgmb = new JGMBar(this);
setTitle("Brigit's Birthday Game");
setSize(800, 300);
jlabel = new JLabel("Hello " + jwelcome.getJTArea().getText() + "! Welcome to your birthday game!");
jtarea = new JTArea("Question");
jfile = new JFile();
jfile_A = new JFile();
jfile_B = new JFile();
jfile_C = new JFile();
jfile_D = new JFile();
jsolution = new JFile();
index = 0;
jtarea.setText(jfile.loadQuestions("Questions.txt", index));
Rectangle r = new Rectangle();
jtarea.scrollRectToVisible(r);
getContentPane().setLayout(new BorderLayout());
// jwon = new JLabel("Select the correct answer");
northpanel = new JPanel();
northpanel.setLayout(new FlowLayout());
northpanel.add(jlabel);
northpanel.setBackground(Color.magenta);
getContentPane().add((BorderLayout.NORTH), northpanel);
addWindowListener(jgwl);
setJMenuBar(jgmb);
centerpanel = new JPanel();
centerpanel.setLayout(new FlowLayout());
centerpanel.add(jtarea);
centerpanel.setBackground(Color.magenta);
getContentPane().add(BorderLayout.CENTER, centerpanel);
jbfifty_fifty = new JButton("50:50");
jbfifty_fifty.addActionListener(jgml);
eastpanel = new JPanel();
eastpanel.setLayout(new FlowLayout());
eastpanel.add(jbfifty_fifty);
eastpanel.setBackground(Color.magenta);
getContentPane().add(BorderLayout.EAST, eastpanel);
// jfile_A.loadQuestions("Answers_A.txt", 0
answer_A = (String) jfile_A.loadQuestions("Answers_A.txt", index);
answer_B = (String) jfile_B.loadQuestions("Answers_B.txt", index);
answer_C = (String) jfile_C.loadQuestions("Answers_C.txt", index);
answer_D = (String) jfile_D.loadQuestions("Answers_D.txt", index);
solution = (String) jsolution.loadQuestions("Solutions.txt", index);
jbutton_A = new JButton("A: ");
jbutton_B = new JButton("B: ");
jbutton_C = new JButton("C: ");
jbutton_D = new JButton("D: ");
jbutton_A.setText("A: " + answer_A);
jbutton_B.setText("B: " + answer_B);
jbutton_C.setText("C: " + answer_C);
jbutton_D.setText("D: " + answer_D);
jsouthpanel = new JPanel();
jsouthpanel.setLayout(new FlowLayout());
jbutton_A.addActionListener(jgml);
jbutton_B.addActionListener(jgml);
jbutton_C.addActionListener(jgml);
jbutton_D.addActionListener(jgml);
jsouthpanel.add(jbutton_A);
jsouthpanel.add(jbutton_B);
jsouthpanel.add(jbutton_C);
jsouthpanel.add(jbutton_D);
jsouthpanel.setBackground(Color.BLACK);
jsouthpanel.setForeground(Color.BLACK);
getContentPane().add(BorderLayout.SOUTH, jsouthpanel);
setVisible(true);
}
public JButton getJButton_A() {
return jbutton_A;
}
public JButton getJButton_B() {
return jbutton_B;
}
public JButton getJButton_C() {
return jbutton_C;
}
public JButton getJButton_D() {
return jbutton_D;
}
public JFile getFile_A() {
return jfile_A;
}
public JFile getFile_B() {
return jfile_B;
}
public JFile getFile_C() {
return jfile_C;
}
public JFile getFile_D() {
return jfile_D;
}
public String getAnswer_A() {
return answer_A;
}
public String getAnswer_B() {
return answer_B;
}
public String getAnswer_C() {
return answer_C;
}
public String getAnswer_D() {
return answer_D;
}
public String getSolution() {
return solution;
}
public JPanel getSouthPanel() {
return jsouthpanel;
}
public JFile getJFile() {
return jfile;
}
public JTArea getJTArea() {
return jtarea;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public JLabel getJLabel() {
return jlabel;
}
public void setJLabel(JLabel jl) {
jlabel = jl;
}
public JButton getFifty() {
return jbfifty_fifty;
}
int nextQuestion() throws IOException {
try {
index = index + 1;
if (index >= 20) {
File file = new File("letter.docx");
Desktop desktop = Desktop.getDesktop();
if (file.exists())
desktop.open(file);
setIndex(0);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: " + e);
}
jtarea.setText(jfile.loadQuestions("Questions.txt", index));
answer_A = (String) jfile_A.loadQuestions("Answers_A.txt", index);
answer_B = (String) jfile_B.loadQuestions("Answers_B.txt", index);
answer_C = (String) jfile_C.loadQuestions("Answers_C.txt", index);
answer_D = (String) jfile_D.loadQuestions("Answers_D.txt", index);
solution = (String) jsolution.loadQuestions("Solutions.txt", index);
jbutton_A.setText("A: " + answer_A);
jbutton_B.setText("B: " + answer_B);
jbutton_C.setText("C: " + answer_C);
jbutton_D.setText("D: " + answer_D);
return index;
}
void play() {
jlabel.setText("Select one of the four answers");
jbutton_A.addActionListener(jgml);
jbutton_B.addActionListener(jgml);
jbutton_C.addActionListener(jgml);
jbutton_D.addActionListener(jgml);
}
void pause() {
jlabel.setText("pause");
jbutton_A.removeActionListener(jgml);
jbutton_B.removeActionListener(jgml);
jbutton_C.removeActionListener(jgml);
jbutton_D.removeActionListener(jgml);
jsouthpanel.setBackground(Color.BLACK);
}
public void paintComponent(Graphics g) {
Image img = Toolkit.getDefaultToolkit().getImage(JGame.class.getResource("baloons.jpeg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
void close() {
dispose();
setVisible(false);
System.exit(0);
}
}
EDIT 2:
Here is the command used to run my game:
C:\Program Files\Java\jdk-13.0.2\bin\javaw.exe -Dfile.encoding=Cp1252 -classpath "C:\Users\neilp\eclipse-workspace\Brigit Birthday Quiz\bin" start

Related

String won't display using drawString()

I'm writing a simple Trivia game and I ran into a problem where the question string won't display
In my frame I'm using border layout with "new game" and "end game" on the bottom (South) and my Trivia panel in the center.
The Trivia panel is made of grid layout with 2 rows and 1 column with the 4 answers on the bottom half and on the upper half I used another panel with border layout with the question string in the center and the score in the east.
It should look like this:
However all of the components display except for the question string.
My paintComponent is:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
g.drawString(tf,0,0);
}
where tf is my string and my Trivia panel code is:
public TriviaPanel(){
score = 0;
scoreString = new JTextField();
scoreString.setFont(font);
questionPanel = new JPanel();
questionPanel.setLayout(new BorderLayout());
questionPanel.add(scoreString,BorderLayout.EAST);
this.setLayout(new GridLayout(2,1));
pool = null;
try {
pool = new Pool();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
question = pool.getQuestion();
String[] answers = question.shuffle();
tf = question.getQuestion();
this.add(questionPanel);
answersPanel = new JPanel();
answersPanel.setLayout(new GridLayout(2,2));
buttons = new JButton[NUM_OF_ANSWERS];
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
buttons[i] = new JButton(answers[i]);
answersPanel.add(buttons[i]);
buttons[i].addActionListener(lis);
}
this.add(answersPanel);
scoreString.setText("Score: "+score+"/"+pool.getIterator()*CORRECT);
}
where pool is used to hold my pool of questions.
When I debugged the code I see the tf string being updated to the question string but it won't display.
Is it because of the coordinates?
Any insights would be greatly appreciated.
[Edit] Although not finished but full code below:
import java.util.Arrays;
import java.util.Collections;
public class Question {
private final int NUM_OF_ANSWERS = 4;
private String question;
private String[] answers = new String[NUM_OF_ANSWERS];
private final int CORRECT_ANSWER = 0;
public Question(String qu, String an, String dm1, String dm2, String
dm3){
question = qu;
answers[0] = an;
answers[1] = dm1;
answers[2] = dm2;
answers[3] = dm3;
}
public String getCorrectAnswer() {
return answers[CORRECT_ANSWER];
}
public String getQuestion(){
return question;
}
public String[] getAnswers(){
return answers;
}
public String toString(){
String str = question;
for (int i = 0; i<4; i++)
str+=" "+answers[i];
str+="\n";
return str;
}
public String[] shuffle(){
String[] shuffled = new String[NUM_OF_ANSWERS];
for (int i=0;i<NUM_OF_ANSWERS;i++)
shuffled[i]=answers[i];
Collections.shuffle(Arrays.asList(shuffled));
return shuffled;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
public class Pool {
private ArrayList<Question> questions = new ArrayList<>();
private Scanner input = new Scanner(new File("src/trivia.txt"));
private static int iterator = 0;
public Pool() throws FileNotFoundException {
while (input.hasNext()){
String q = input.nextLine();
String a = input.nextLine();
String d1 = input.nextLine();
String d2 = input.nextLine();
String d3 = input.nextLine();
Question question = new Question(q,a,d1,d2,d3);
questions.add(question);
}
Collections.shuffle(questions);
//System.out.println(questions);
}
public Question getQuestion(){
Question q = questions.get(iterator);
iterator++;
return q;
}
public int getSize(){
return questions.size();
}
public static int getIterator() {
return iterator;
}
}
import javax.swing.*;
import java.awt.*;
public class GameFrame extends JFrame {
private JButton restart, finish;
private JPanel buttons;
public GameFrame(){
super("Trivia");
TriviaPanel tp = new TriviaPanel();
this.setLayout(new BorderLayout());
this.add(tp,BorderLayout.CENTER);
restart = new JButton("New game");
finish = new JButton("End game");
buttons = new JPanel();
buttons.add(restart);
buttons.add(finish);
this.add(buttons,BorderLayout.SOUTH);
this.setSize(1000,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
GameFrame gf = new GameFrame();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.util.concurrent.TimeUnit;
public class TriviaPanel extends JPanel {
private TimerListener tl = new TimerListener();
private Timer timer = new Timer(10000,tl);
private static int score;
private JTextField scoreString;
private final int CORRECT = 10, INCORRECT = 5;
private JButton[] buttons;
private Pool pool;
private Question question;
private JButton pressed;
private final int NUM_OF_ANSWERS = 4;
private Listener lis = new Listener();
//private JPanel questionPanel;
private JPanel answersPanel;
private String tf;
private Font font = new Font("Serif",Font.BOLD,24);
private JTextField tf2 = new JTextField();
private QuestionPanel questionPanel;
public TriviaPanel(){
score = 0;
scoreString = new JTextField();
scoreString.setFont(font);
questionPanel = new QuestionPanel();
//questionPanel.setLayout(new BorderLayout());
//questionPanel.add(scoreString,BorderLayout.EAST);
this.setLayout(new GridLayout(2,1));
pool = null;
try {
pool = new Pool();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
question = pool.getQuestion();
String[] answers = question.shuffle();
tf = question.getQuestion();
//tf2.setText(question.getQuestion());
//questionPanel.add(tf2,BorderLayout.CENTER);
this.add(questionPanel);
answersPanel = new JPanel();
answersPanel.setLayout(new GridLayout(2,2));
buttons = new JButton[NUM_OF_ANSWERS];
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
buttons[i] = new JButton(answers[i]);
answersPanel.add(buttons[i]);
buttons[i].addActionListener(lis);
}
this.add(answersPanel);
timer.start();
scoreString.setText("Score: "+score+"/"+pool.getIterator()*CORRECT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
questionPanel.repaint();
}
private void next(){
Question q = pool.getQuestion();
question=q;
tf = q.getQuestion();
String[] answers = q.shuffle();
for (int i = 0; i < NUM_OF_ANSWERS; i++)
buttons[i].setText(answers[i]);
}
private void gameOver(){
JOptionPane.showConfirmDialog(null,
"Score: "+score, "Select an Option...", JOptionPane.YES_NO_CANCEL_OPTION);
}
private void check(String guess) {
timer.stop();
String answer = question.getCorrectAnswer();
if (guess.equals(answer)) {
score += CORRECT;
tf = "Correct!!!";
} else {
score -= INCORRECT;
tf = "Wrong answer";
}
scoreString.setText("Score: "+score+"/"+pool.getIterator()*CORRECT);
repaint();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class QuestionPanel extends JPanel{
public QuestionPanel(){
this.setLayout(new BorderLayout());
this.add(scoreString,BorderLayout.EAST);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
g.drawString(tf,0,200);
}
}
private class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
pressed = (JButton) e.getSource();
String guess = pressed.getText();
check(guess);
if (pool.getIterator() < pool.getSize()) {
timer.restart();
next();
}
else
gameOver();
}
}
private class TimerListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
score-=INCORRECT;
scoreString.setText("Score: "+score+"/"+pool.getIterator()*CORRECT);
repaint();
timer.restart();
next();
}
}
}
Start by getting rid of
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
questionPanel.repaint();
}
Seriously this is just dangerous and could set you for a endless loop which will consume your CPU cycles
Next, I modified your QuestionPanel so the text is actually rendered somewhere within the realms of probability ...
private class QuestionPanel extends JPanel {
public QuestionPanel() {
this.setLayout(new BorderLayout());
this.add(scoreString, BorderLayout.EAST);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g.drawString(tf, 10, y);
}
}
But seriously, why aren't you just using a JLabel?
Now, any time tf changes, you need to call QuestionPanel's repaint method.
So, that's in the next and check(String) methods.
And finally (for now), you should never, ever do...
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
inside the context of the event dispatching thread. This is stopping the repaints from been processed, so, for one whole second, nothing will change.
If you want to stop the user for a second, disable the buttons and/or other controls and use another Swing Timer (for simplicity)
This is demonstrated in this self contained, compilable and runnable example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GameFrame frame = new GameFrame();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class GameFrame extends JFrame {
private JButton restart, finish;
private JPanel buttons;
public GameFrame() {
super("Trivia");
TriviaPanel tp = new TriviaPanel();
this.setLayout(new BorderLayout());
this.add(tp, BorderLayout.CENTER);
restart = new JButton("New game");
finish = new JButton("End game");
buttons = new JPanel();
buttons.add(restart);
buttons.add(finish);
this.add(buttons, BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static class TriviaPanel extends JPanel {
// private TimerListener tl = new TimerListener();
// private Timer timer = new Timer(10000, tl);
private static int score;
private JTextField scoreString;
private final int CORRECT = 10, INCORRECT = 5;
private JButton[] buttons;
private Pool pool;
private Question question;
private JButton pressed;
private final int NUM_OF_ANSWERS = 4;
private Listener lis = new Listener();
//private JPanel questionPanel;
private JPanel answersPanel;
private String tf;
private Font font = new Font("Serif", Font.BOLD, 24);
private JTextField tf2 = new JTextField();
private QuestionPanel questionPanel;
public TriviaPanel() {
score = 0;
scoreString = new JTextField();
scoreString.setFont(font);
questionPanel = new QuestionPanel();
//questionPanel.setLayout(new BorderLayout());
//questionPanel.add(scoreString,BorderLayout.EAST);
this.setLayout(new GridLayout(2, 1));
pool = null;
try {
pool = new Pool();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
question = pool.getQuestion();
String[] answers = question.shuffle();
tf = question.getQuestion();
//tf2.setText(question.getQuestion());
//questionPanel.add(tf2,BorderLayout.CENTER);
this.add(questionPanel);
answersPanel = new JPanel();
answersPanel.setLayout(new GridLayout(2, 2));
buttons = new JButton[NUM_OF_ANSWERS];
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
buttons[i] = new JButton(answers[i]);
answersPanel.add(buttons[i]);
buttons[i].addActionListener(lis);
}
this.add(answersPanel);
// timer.start();
scoreString.setText("Score: " + score + "/" + pool.getIterator() * CORRECT);
}
// #Override
// protected void paintComponent(Graphics g) {
// super.paintComponent(g);
// questionPanel.repaint();
// }
private void next() {
Question q = pool.getQuestion();
question = q;
tf = q.getQuestion();
String[] answers = q.shuffle();
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
buttons[i].setText(answers[i]);
}
questionPanel.repaint();
}
private void gameOver() {
JOptionPane.showConfirmDialog(null,
"Score: " + score, "Select an Option...", JOptionPane.YES_NO_CANCEL_OPTION);
}
private void check(String guess) {
// timer.stop();
String answer = question.getCorrectAnswer();
if (guess.equals(answer)) {
score += CORRECT;
tf = "Correct!!!";
} else {
score -= INCORRECT;
tf = "Wrong answer";
}
questionPanel.repaint();
scoreString.setText("Score: " + score + "/" + pool.getIterator() * CORRECT);
// OH GOD THIS IS A BAD IDEA!
// try {
// TimeUnit.SECONDS.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Timer timer = (Timer) e.getSource();
timer.stop();
// Personally, I'd use a listener, but this will do
afterCheckDelay();
}
});
timer.start();
}
protected void afterCheckDelay() {
if (pool.getIterator() < pool.getSize()) {
//timer.restart();
next();
} else {
gameOver();
}
}
private class QuestionPanel extends JPanel {
public QuestionPanel() {
this.setLayout(new BorderLayout());
this.add(scoreString, BorderLayout.EAST);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g.drawString(tf, 10, y);
}
}
private class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
pressed = (JButton) e.getSource();
String guess = pressed.getText();
check(guess);
}
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// timer.stop();
// score -= INCORRECT;
// scoreString.setText("Score: " + score + "/" + pool.getIterator() * CORRECT);
// repaint();
// timer.restart();
// next();
}
}
}
public static class Pool {
private ArrayList<Question> questions = new ArrayList<>();
// private Scanner input = new Scanner(new File("src/trivia.txt"));
private static int iterator = 0;
public Pool() throws FileNotFoundException {
Question question = new Question("Why am I doing this", "Because I'm awesome", "You feel for the trick", "You have no idea", "To much caffine");
questions.add(question);
// while (input.hasNext()) {
// String q = input.nextLine();
// String a = input.nextLine();
// String d1 = input.nextLine();
// String d2 = input.nextLine();
// String d3 = input.nextLine();
// Question question = new Question(q, a, d1, d2, d3);
// questions.add(question);
// }
Collections.shuffle(questions);
//System.out.println(questions);
}
public Question getQuestion() {
Question q = questions.get(iterator);
iterator++;
return q;
}
public int getSize() {
return questions.size();
}
public static int getIterator() {
return iterator;
}
}
public static class Question {
private final int NUM_OF_ANSWERS = 4;
private String question;
private String[] answers = new String[NUM_OF_ANSWERS];
private final int CORRECT_ANSWER = 0;
public Question(String qu, String an, String dm1, String dm2, String dm3) {
question = qu;
answers[0] = an;
answers[1] = dm1;
answers[2] = dm2;
answers[3] = dm3;
}
public String getCorrectAnswer() {
return answers[CORRECT_ANSWER];
}
public String getQuestion() {
return question;
}
public String[] getAnswers() {
return answers;
}
public String toString() {
String str = question;
for (int i = 0; i < 4; i++) {
str += " " + answers[i];
}
str += "\n";
return str;
}
public String[] shuffle() {
String[] shuffled = new String[NUM_OF_ANSWERS];
for (int i = 0; i < NUM_OF_ANSWERS; i++) {
shuffled[i] = answers[i];
}
Collections.shuffle(Arrays.asList(shuffled));
return shuffled;
}
}
}

Java : How to Save a File and overwrite it and display combobox strings?

I am working on a school project using BlueJay and I have created two classes in package Logic which are the Game class, and the VectorGames class.
In my package GUI, I created a class called AddGame and ViewGame class.
The issue that I have encountered is that, when I click the Save Button on Addgame, it saves the file only once. When I try to save it doesn't do or say anything it just stays there returning nothing. Another issue encountered is that on ViewGame, the gameType column is remaining empty ( this is from combo type box )
AddGame code :
package GUI;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import Logic.*;
public class AddGame extends JFrame implements ActionListener{
private JPanel north, south, east, west, center;
private JLabel titleLabel, westLabel, eastLabel;
private JTextField gameNameFld, gameKeyFld;
private JComboBox gameTypeCombo;
private JButton saveButton, clearButton;
private VectorGames vg;
public AddGame(){
super("Adding a Game");
this.setLayout(new BorderLayout());
vg = new VectorGames();
vg.readFromFile();
//north panel
north = new JPanel();
this.add(north,BorderLayout.NORTH);
titleLabel = new JLabel("Add a game below");
titleLabel.setFont(new Font("Verdana",Font.BOLD,20));
titleLabel.setForeground(Color.black);
north.add(titleLabel);
//west and east panels
west = new JPanel();
east = new JPanel();
this.add(west, BorderLayout.WEST);
this.add(east, BorderLayout.EAST);
westLabel = new JLabel(" ");
eastLabel = new JLabel(" ");
west.add(westLabel);
east.add(eastLabel);
//center panel
center = new JPanel();
this.add(center, BorderLayout.CENTER);
center.setLayout(new GridLayout(4,2,0,20));
gameNameFld = new JTextField();
gameKeyFld = new JTextField();
gameTypeCombo = new JComboBox();
gameTypeCombo.setModel(new DefaultComboBoxModel(new String[]
{"<--Select-->", "Arcade", "Puzzle", "Adventure", "Shooter", "Roleplay"}));
center.add(createLabel("Game Name"));
center.add(gameNameFld);
center.add(createLabel("Game Key"));
center.add(gameKeyFld);
center.add(createLabel("Game Type"));
center.add(gameTypeCombo);
//south panel
south = new JPanel();
south.setLayout(new FlowLayout());
this.add(south, BorderLayout.SOUTH);
clearButton = new JButton("Clear");
south.add(clearButton);
clearButton.addActionListener(this);
saveButton = new JButton("Save");
south.add(saveButton);
saveButton.addActionListener(this);
this.setSize(300,400);
this.setLocation(50,50);
this.setVisible(true);
}
private JLabel createLabel(String title){
return new JLabel(title);
}
private void clearFields(){
gameNameFld.setText("");
gameKeyFld.setText("");
gameTypeCombo.setSelectedIndex(0);
}
private boolean validateForm(){
boolean flag = false;
if(gameNameFld.getText().equals("")||gameKeyFld.getText().equals("")||
gameTypeCombo.getSelectedIndex()==0){
flag = true;
}
return flag;
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == clearButton){
clearFields();
}
if(event.getSource() == saveButton){
if(validateForm() == true){
JOptionPane.showMessageDialog(null,"You have empty fields",
"Empty Fields", JOptionPane.ERROR_MESSAGE);
} else if(vg.checkGamebyGameKey(gameKeyFld.getText()) == true){
JOptionPane.showMessageDialog(null,"Game Key already exists!",
"Game Key Check", JOptionPane.ERROR_MESSAGE);
} else {
Game tempGame = new Game(gameNameFld.getText(),gameKeyFld.getText(),
(String)gameTypeCombo.getSelectedItem());
vg.addGame(tempGame);
vg.saveToFile();
JOptionPane.showMessageDialog(null, "Game added successfully!", "Adding a Game",
JOptionPane.INFORMATION_MESSAGE);
clearFields();
}
}
}
}
ViewGame code:
package GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import Logic.*;
public class ViewGame extends JFrame {
private JTable table;
private VectorGames vg;
public ViewGame(){
super("Viewing Games by Name");
this.setLayout(new BorderLayout());
vg = new VectorGames();
vg.readFromFile();
vg.sortGamesByName();
int numOfGames = vg.getVectorSize();
int count = 0;
Game tempGame = new Game();
String[] tableHeader = {"Game Name", "Game Type", "Game Key"};
Object [][] tableContent = new Object[numOfGames][3];
for(int i = 0; i < numOfGames; i++){
tempGame = vg.getGamesByIndex(count);
tableContent[i][0] = tempGame.getGameName();
tableContent[i][2] = tempGame.getGameType();
tableContent[i][1] = tempGame.getGameKey();
}
table = new JTable (tableContent, tableHeader);
JScrollPane scrollPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(500, 400));
this.add(table.getTableHeader(), BorderLayout.NORTH);
this.add(table, BorderLayout.CENTER);
this.setSize(500,600);
this.setLocation(100,50);
this.setVisible(true);
}
}
Game code:
package Logic;
import java.io.*;
public class Game implements Serializable{ // Using serializable to allow easy save and read access
//Initializing variables related to Game
private String gameName, gameKey, gameType;
//Creating a constructor with the parameters for class Games
public Game(String gameName, String gamekey, String gameType){
setGameName(gameName);
setGameKey(gameKey);
setGameType(gameType);
}
//Setting up a parameterless constructor for class Games
public Game(){
}
public String getGameName(){//Get Method for gameName
return gameName;
}
public String getGameKey(){//Get Method for gameKey
return gameKey;
}
public String getGameType(){//Get Method for gameType
return gameType;
}
public void setGameName(String gameName){//Set Method for gameName
this.gameName = gameName;
}
public void setGameKey(String gameKey){//Set Method for gameKey
this.gameKey = gameKey;
}
public void setGameType(String gameType){//Set Method for gameType
this.gameType = gameType;
}
public String toString(){
return "Game Name : " + gameName + "\nGame Key : "
+ gameKey + "\nGame Type ; " + gameType;
}
}
VectorGames code:
package Logic;
import java.util.*;
import java.io.*;
import java.lang.*;
public class VectorGames extends IOException{
/* Add a Game, Remove a Game, getVectorGame Size, print allGamesAvailable,
* saveToFile , searchGame and return boolean literal, searchGame and return
* client object, sort games, readFromFile.
*
*/
private Vector<Game> games;
public VectorGames(){
games = new Vector<Game>();
}
//Adding a Game
public void addGame(Game game){
games.add(game);
}
public void deleteGame(Game game){
games.remove(game);
}
public int getVectorSize(){
return games.size();
}
public void clearVector(){
games.clear();
}
public void printGames(){
for(Game tempGame : games){
System.out.println(tempGame.toString());
System.out.println("");
}
}
public Game getGamesByIndex(int i){
Game tempGame = new Game();
if (i < getVectorSize()){
tempGame = games.get(i);
}
return tempGame;
}
public void sortGamesByName(){
Game currentGame = new Game();
Game nextGame = new Game();
Game tempGame = new Game();
for(int i = 0; i < getVectorSize(); i++){
for(int j = 0; j < getVectorSize()-i-1; j++){
currentGame = games.elementAt(j);
nextGame = games.elementAt(j+1);
if(currentGame.getGameName().compareTo(nextGame.getGameName())>0){
tempGame = currentGame;
games.setElementAt(nextGame, j);
games.setElementAt(tempGame, j+1);
}
}
}
}
public boolean checkGamebyGameKey(String gameKey){
boolean flag = false;
for(Game tempGames : games){
if(tempGames .getGameKey().equals(gameKey)){
flag = true;
}
}
return flag;
}
public Game accessGameByGameName(String gameName){
Game foundGameName = new Game();
for(Game tempGames: games){
if(tempGames.getGameName().equals(gameName)){
foundGameName = tempGames;
}
}
return foundGameName;
}
public void saveToFile(){
try{
File f = new File("C:/Users/Denis/Desktop/GameStore/Databases","gameList.obj");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(games);
oos.flush();
oos.close();
}catch (IOException ioe){
System.err.println("Cannot write to file!");
}
}
public void readFromFile(){
try{
File f = new File("C:/Users/Denis/Desktop/GameStore/Databases","gameList.obj");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
games = (Vector<Game>) ois.readObject();
ois.close();
} catch (FileNotFoundException fnfe){
System.err.println("Cannot find file!");
}catch (IOException ioe){
System.err.println("Cannot read from file!");
}catch(ClassNotFoundException cnfe){
System.err.println("Client class cannot be found!");
}
}
}
Main class: GameCenter
public class GameCenter extends JFrame {
public static void main(String... args) {
SwingUtilities.invokeLater(() -> new GameCenter().setVisible(true));
}
public GameCenter() {
super("Game Center");
init();
}
private void init() {
setLayout(new BorderLayout(5, 5));
Model model = new Model();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Add", new AddTabPanel(model));
tabbedPane.add("View", new ViewTabPanel(model));
add(tabbedPane, BorderLayout.CENTER);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 500);
setMinimumSize(new Dimension(400, 500));
setResizable(false);
}
}
Game entity:
final class Game {
private static final Pattern RECORD = Pattern.compile("(?<key>.+)\\|(?<name>.+)\\|(?<type>.+)");
private final String name;
private final String key;
private final String type;
public static Game createFromRecord(String str) {
Matcher matcher = RECORD.matcher(str);
return matcher.matches() ? new Game(matcher.group("name"), matcher.group("key"), matcher.group("type")) : null;
}
public Game(String name, String key, String type) {
this.name = name;
this.key = key;
this.type = type;
}
public String getName() {
return name;
}
public String getKey() {
return key;
}
public String getType() {
return type;
}
public String serialize() {
return String.format("%s|%s|%s", key, name, type);
}
}
Table model:
final class Model extends AbstractTableModel {
private static final long serialVersionUID = 1858846855164475327L;
private final Map<String, Game> keyGame = new TreeMap<>();
private final List<Game> data = new ArrayList<>();
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void add(String name, String key, String type) {
keyGame.put(key, new Game(name, key, type));
fireTableDataChanged();
}
public void remove(int rowIndex) {
keyGame.remove(data.get(rowIndex).getKey());
fireTableDataChanged();
}
public void save() throws IOException {
if (file == null)
return;
try (FileWriter out = new FileWriter(file, false)) {
for (Game game : keyGame.values())
out.write(game.serialize() + '\n');
}
}
public void read() throws IOException {
if (file == null)
return;
keyGame.clear();
for (String record : Files.readAllLines(file.toPath())) {
Game game = Game.createFromRecord(record);
if (game != null)
keyGame.put(game.getKey(), game);
}
fireTableDataChanged();
}
private enum Column {
NAME("Game Name", Game::getName),
KEY("Game Key", Game::getKey),
TYPE("Game Type", Game::getType);
private final String title;
private final Function<Game, Object> get;
Column(String title, Function<Game, Object> get) {
this.title = title;
this.get = get;
}
public Object getValue(Game game) {
return get.apply(game);
}
}
// ========== AbstractTableModel ==========
#Override
public void fireTableDataChanged() {
data.clear();
data.addAll(keyGame.values());
super.fireTableDataChanged();
}
// ========== TableModel ==========
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return Column.values().length;
}
#Override
public String getColumnName(int columnIndex) {
return Column.values()[columnIndex].title;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return Column.values()[columnIndex].getValue(data.get(rowIndex));
}
}
AddGame tab panel:
final class AddTabPanel extends JPanel implements ActionListener, DocumentListener {
private final Model model;
private final JTextField nameField = new JTextField();
private final JTextField keyField = new JTextField();
private final JLabel nameLabel = new JLabel("Game Name");
private final JLabel keyLabel = new JLabel("Game Key");
private final JLabel typeLabel = new JLabel("Game Type");
private final JComboBox<String> typeCombo = createGameTypeCombo();
private final JButton openButton = new JButton("Open");
private final JButton saveButton = new JButton("Save");
private final JButton clearButton = new JButton("Clear");
public AddTabPanel(Model model) {
this.model = model;
init();
addListeners();
}
private void init() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = createConstraints();
add(createTitlePanel(), gbc);
add(createMainPanel(), gbc);
add(createButtonPanel(), gbc);
gbc.weighty = 1;
add(Box.createVerticalGlue(), gbc);
onNameFieldChanged();
onKeyFieldChanged();
onTypeComboChanged();
}
private static JPanel createTitlePanel() {
JLabel label = new JLabel("Add a game below");
label.setFont(new Font("Verdana", Font.BOLD, 20));
JPanel panel = new JPanel();
panel.add(label);
return panel;
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(3, 2, 5, 5));
panel.add(nameLabel);
panel.add(nameField);
panel.add(keyLabel);
panel.add(keyField);
panel.add(typeLabel);
panel.add(typeCombo);
return panel;
}
private static GridBagConstraints createConstraints() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
return gbc;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
panel.add(clearButton);
panel.add(saveButton);
panel.add(openButton);
return panel;
}
private static JComboBox<String> createGameTypeCombo() {
JComboBox<String> combo = new JComboBox<>();
combo.setModel(new DefaultComboBoxModel<>(new String[] { "<--Select-->", "Arcade", "Puzzle", "Adventure", "Shooter", "Roleplay" }));
return combo;
}
private void addListeners() {
clearButton.addActionListener(this);
saveButton.addActionListener(this);
openButton.addActionListener(this);
nameField.getDocument().addDocumentListener(this);
keyField.getDocument().addDocumentListener(this);
typeCombo.addActionListener(this);
}
private void validateFields() {
String name = nameField.getText().trim();
String key = keyField.getText().trim();
int type = typeCombo.getSelectedIndex();
saveButton.setEnabled(!name.isEmpty() && !key.isEmpty() && type != 0);
}
private void onNameFieldChanged() {
nameLabel.setForeground(nameField.getText().trim().isEmpty() ? Color.RED : Color.BLACK);
validateFields();
}
private void onKeyFieldChanged() {
keyLabel.setForeground(keyField.getText().trim().isEmpty() ? Color.RED : Color.BLACK);
validateFields();
}
private void onTypeComboChanged() {
typeLabel.setForeground(typeCombo.getSelectedIndex() == 0 ? Color.RED : Color.BLACK);
validateFields();
}
private void onCleanButton() {
nameField.setText(null);
keyField.setText(null);
typeCombo.setSelectedIndex(0);
validateFields();
}
private void onSaveButton() {
String name = nameField.getText().trim();
String key = keyField.getText().trim();
String type = (String)typeCombo.getSelectedItem();
model.add(name, key, type);
if (model.getFile() == null) {
JFileChooser fileChooser = new JFileChooser();
int res = fileChooser.showSaveDialog(this);
model.setFile(res == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null);
}
try {
model.save();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot save file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
private void onOpenButton() {
JFileChooser fileChooser = new JFileChooser();
int res = fileChooser.showOpenDialog(null);
model.setFile(res == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null);
try {
model.read();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot read file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
// ========== ActionListener ==========
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == typeCombo)
onTypeComboChanged();
else if (e.getSource() == clearButton)
onCleanButton();
else if (e.getSource() == saveButton)
onSaveButton();
else if (e.getSource() == openButton)
onOpenButton();
}
// ========== DocumentListener ==========
#Override
public void insertUpdate(DocumentEvent e) {
if (e.getDocument() == nameField.getDocument())
onNameFieldChanged();
else if (e.getDocument() == keyField.getDocument())
onKeyFieldChanged();
}
#Override
public void removeUpdate(DocumentEvent e) {
if (e.getDocument() == nameField.getDocument())
onNameFieldChanged();
else if (e.getDocument() == keyField.getDocument())
onKeyFieldChanged();
}
#Override
public void changedUpdate(DocumentEvent e) {
}
}
ViewGame tab panel:
final class ViewTabPanel extends JPanel implements ActionListener, PopupMenuListener {
private final Model model;
private final JTable table = new JTable();
private final JPopupMenu popupMenu = new JPopupMenu();
private final JMenuItem deleteItem = new JMenuItem("Delete");
public ViewTabPanel(Model model) {
this.model = model;
init();
addListeners();
}
private void init() {
setLayout(new GridLayout(1, 1));
add(new JScrollPane(table));
popupMenu.add(deleteItem);
table.setComponentPopupMenu(popupMenu);
table.setAutoCreateRowSorter(true);
table.setModel(model);
table.updateUI();
}
private void addListeners() {
popupMenu.addPopupMenuListener(this);
deleteItem.addActionListener(this);
}
// ========== ActionListener ==========
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == deleteItem) {
model.remove(table.getSelectedRow());
try {
model.save();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot save file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
}
// ========== PopupMenuListener ==========
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
if (event.getSource() == popupMenu) {
SwingUtilities.invokeLater(() -> {
int rowAtPoint = table.rowAtPoint(SwingUtilities.convertPoint(popupMenu, new Point(0, 0), table));
if (rowAtPoint > -1)
table.setRowSelectionInterval(rowAtPoint, rowAtPoint);
});
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent event) {
}
}

How can I solve a string version of a calculation for a simple calculator? [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
This is a simple calculator where the user can type out the calculation and hit enter, and the calculator would determine if it is a valid calculation or not. If it is a valid calculation, the calculation is carried out. If not, an error message is written to the screen.
The calculation is carried out part isn't finished.
Can someone suggest a solutions to the getAnswer() method.
It would be very much appreciated.
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
#SuppressWarnings("serial")
public class Calculator extends JFrame{
private interface CalculatorInterface {
public void writeToScreen(String text);
public void clearScreen();
public String getScreenText();
}
private class CalculatorPanel extends JPanel implements CalculatorInterface {
private class NumberPanel extends JPanel implements CalculatorInterface {
private static final int NUMTOTAL = 10;
private CalculatorPanel calcPanel;
private JButton[] numButtons;
public NumberPanel(CalculatorPanel calcPanel) {
this.calcPanel = calcPanel;
buildLayout();
addButtons();
}
private void buildLayout() {
this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
GridLayout layout = new GridLayout(4,3);
layout.setHgap(1);
layout.setVgap(1);
this.setLayout(new GridLayout(4,3));
}
private void addButtons() {
numButtons = new JButton[NUMTOTAL];
for(int i = numButtons.length -1; i >= 0 ; i--) {
numButtons[i] = new JButton("" + i);
numButtons[i].setPreferredSize(new Dimension(60,40));
numButtons[i].setFont(new Font("Sans serif", Font.PLAIN, 18));
numButtons[i].addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = ((JButton)e.getSource()).getText().trim();
if(getScreenText().equals("Invalid Calc")) {
clearScreen();
writeToScreen(text);
}else {
writeToScreen(text);
}
}
});
this.add(numButtons[i]);
}
}
#Override
public void writeToScreen(String text) {
calcPanel.writeToScreen(text);
}
#Override
public void clearScreen() {
calcPanel.clearScreen();
}
#Override
public String getScreenText() {
return calcPanel.getScreenText();
}
}
private class OperPanel extends JPanel implements CalculatorInterface {
private static final int ADD = 0;
private static final int SUB = 1;
private static final int MULT = 2;
private static final int DIV = 3;
private static final int OPENB = 4;
private static final int CLOSEB = 5;
private static final int CLEAR = 6;
private static final int EQL = 7;
private static final int OPERTOTAL = 8;
private CalculatorPanel calcPanel;
private JButton[] operButtons;
public OperPanel(CalculatorPanel calcPanel) {
this.calcPanel = calcPanel;
buildLayout();
addButtons();
}
private void buildLayout() {
GridLayout layout = new GridLayout(4,1);
layout.setHgap(1);
layout.setVgap(1);
this.setLayout(new GridLayout(4,1));
}
private void addButtons() {
operButtons = new JButton[OPERTOTAL];
operButtons[ADD] = makeButton(ADD, "+");
operButtons[SUB] = makeButton(SUB, "-");
operButtons[MULT] = makeButton(MULT, "*");
operButtons[DIV] = makeButton(DIV, "/");
operButtons[CLEAR] = makeButton(CLEAR, "CL");
operButtons[EQL] = makeButton(EQL, "=");
operButtons[OPENB] = makeButton(OPENB, "(");
operButtons[CLOSEB] = makeButton(CLOSEB, ")");
for(JButton button: operButtons) {
this.add(button);
}
}
private JButton makeButton(int index, String label) {
operButtons[index] = new JButton(label);
operButtons[index].addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = ((JButton)e.getSource()).getText();
if(text.equals("=")) {
String screenText = getScreenText();
clearScreen();
try {
writeToScreen(getAnswer(screenText));
}catch(Exception excep) {
writeToScreen("Invalid Calc");
}
}else if(text.equals("CL")) {
clearScreen();
}else {
writeToScreen(text);
}
}
});
return operButtons[index];
}
private String getAnswer(String text) throws Exception {
/*I'm trying to solve for any input by the user e.g
*(the stuff in square brackets represents what is displayed
* on the screen:.
*[1+1] (hits equals) [2]
*[1+2-3] (hits equals) [0]
*[1+2*3] (hits equals) [7]
*[10*(14+1/2)] (hits equals) [145]
*/
throw new Exception();
}
#Override
public String getScreenText() {
return calcPanel.getScreenText();
}
#Override
public void clearScreen() {
calcPanel.clearScreen();
}
#Override
public void writeToScreen(String text) {
calcPanel.writeToScreen(text);
}
}
private NumberPanel numPanel;
private OperPanel operPanel;
private JTextField calcScreen;
public CalculatorPanel(JTextField calcScreen) {
this.calcScreen = calcScreen;
buildNumPanel();
buildOperPanel();
buildCalcPanel();
}
private void buildNumPanel() {
this.numPanel = new NumberPanel(this);
}
private void buildOperPanel() {
this.operPanel = new OperPanel(this);
}
private void buildCalcPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.add(numPanel);
this.add(operPanel);
}
#Override
public void writeToScreen(String text) {
calcScreen.setText(getScreenText() + text);
}
#Override
public String getScreenText() {
return calcScreen.getText();
}
#Override
public void clearScreen() {
calcScreen.setText("");
}
}
private JPanel mainPanel;
private JTextField calcScreen;
private CalculatorPanel calcPanel;
public Calculator() {
buildScreen();
buildCalcPanel();
buildMainPanel();
buildCalculator();
}
private void buildScreen() {
this.calcScreen = new JTextField();
this.calcScreen.setPreferredSize(new Dimension(150,50));
this.calcScreen.setHorizontalAlignment(JTextField.CENTER);
this.calcScreen.setFont(new Font("Sans serif", Font.PLAIN, 30));
}
private void buildCalcPanel() {
this.calcPanel = new CalculatorPanel(this.calcScreen);
}
private void buildMainPanel() {
this.mainPanel = new JPanel();
this.mainPanel.setBorder(new EmptyBorder(10,10,10,10));
this.mainPanel.setLayout(new BoxLayout(this.mainPanel, BoxLayout.Y_AXIS));
this.mainPanel.add(calcScreen);
this.mainPanel.add(calcPanel);
}
private void buildCalculator() {
this.add(mainPanel);
this.setTitle("Calculator");
this.pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Calculator calc = new Calculator();
}
}
How can I check to see if a string is a valid calculation for a simple calculator?
Edit 1: Fixed a silly bug in the makeButton() method were I passed in the text of the button to be verified instead of the text on screen. (I'm an idiot.)
Edit 2: Removed the isValid(String text) from the code and make it so the getAnswer() method just threw an exception if input is not a valid calculation.
As well mentioned in a previous StackOverflow answer (Evaluating a math expression given in string form), you could use Javascript's ScriptEngine to calculate expressions based on strings that you would retrieve from the Text Field. Place it in a try-catch block first to see if there's an error in the expression. In the catch block, set the variable storing whether its a valid expression or not to false.
boolean validExpression = true;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String input = textField.getText() // Modify this to whatever variable you have assigned to your text field
try {
System.out.println(engine.eval(foo));
}
catch (ScriptException e) {
validExpression = false;
System.out.println("Invalid Expression");
}
Make sure you include the following imports:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
Although you could try to implement Shunting-Yard Algorithm or another arithmetic parser, this is simply a way more pragmatic solution.

Java: Copying data from dialog box text field to JTable

This project requires that a user inputs data into text fields on a dialog box accessed from a menu bar and places the data from the text fields into a JTable. The problem is that once the user clicks okay on the dialog box after putting the information into the text field, the dialog box is no longer visible, but nothing appears in the JTable. The JTable headers are there, but the info just submitted is not.
It is a camping registration program, and all of the classes compile okay. I am only working on taking information from an RV reservation first, but will eventually do the same for a tent reservation. Here are the classes that correspond to an RV check in. There is an RV constructor that has parameters (String (name), String (check in day), int (days staying), String (leave day), int (site number), int (power needed)).
First the dialog box class:
package campingPrj;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogCheckInRv extends javax.swing.JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
private javax.swing.JTextField nameTxt;
private javax.swing.JTextField dateIn;
private javax.swing.JTextField stayingTxt;
private javax.swing.JTextField siteNumberTxt;
private javax.swing.JTextField checkOutDate;
private javax.swing.JTextField powerTxt;
private javax.swing.JButton okButton;
private javax.swing.JButton cancelButton;
private boolean cancel;
private boolean okay;
public DialogCheckInRv(java.awt.Frame parent) {
super(parent, true);
setupDialog();
setTitle("RV Check In");
}
private void setupDialog() {
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
nameTxt = new javax.swing.JTextField(27);
dateIn = new javax.swing.JTextField(25);
stayingTxt = new javax.swing.JTextField(25);
siteNumberTxt = new javax.swing.JTextField(27);
powerTxt = new javax.swing.JTextField(27);
okButton = new javax.swing.JButton("Ok");
okButton.addActionListener(this);
cancelButton = new javax.swing.JButton("Cancel");
cancelButton.addActionListener(this);
setLayout(new GridLayout(6, 1));
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Name Reserving:"));
panel.add(nameTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Start Date (mm/dd/yy) :"));
panel.add(dateIn);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Days Planning on Staying:"));
panel.add(stayingTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Requested Site Number:"));
panel.add(siteNumberTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Power Needed (in AMPs):"));
panel.add(powerTxt);
add(panel);
panel = new JPanel();
panel.add(okButton);
panel.add(cancelButton);
add(panel);
pack();
setLocationRelativeTo(null);
}
public void actionPerformed(java.awt.event.ActionEvent event) {
if (event.getSource() == okButton) {
okay = true;
cancel = false;
setVisible(false);
}
if (event.getSource() == cancelButton) {
okay = false;
cancel = true;
setVisible(false);
}
}
public boolean isOk() {
return okay;
}
public boolean isCancel() {
return cancel;
}
public String getName() {
return nameTxt.getText();
}
public String getDateIn() {
return dateIn.getText();
}
public String getDaysStaying() {
return stayingTxt.getText();
}
public String getCheckOutDate() {
return checkOutDate.getText();
}
public String getPower() {
return powerTxt.getText();
}
public String getSiteNumber() {
return siteNumberTxt.getText();
}
public void clear() {
nameTxt.setText(null);
dateIn.setText(null);
stayingTxt.setText(null);
dateIn.setText(null);
powerTxt.setText(null);
siteNumberTxt.setText(null);
}
}
The GUI with the table (where I'm guessing the problem is in the actionPerformed method):
package campingPrj;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUICampingReg extends javax.swing.JFrame implements ActionListener {
private JMenuItem openSerialFileItem = new JMenuItem("Open Serialized File");
private JMenuItem openTextFileItem = new JMenuItem("Open Text File");
private JMenuItem saveSerialFileItem = new JMenuItem("Save Serialized File");
private JMenuItem saveTextFileItem = new JMenuItem("Save Text File");
private JMenuItem exitItem = new JMenuItem("Exit");
private JMenuItem checkInTentItem = new JMenuItem("Check in tent");
private JMenuItem checkInRVItem = new JMenuItem("Check in RV");
private JMenuItem checkOutItem = new JMenuItem("Date Leaving");
private JTextField nameReservingTxt;
private JTextField dateInTxt;
private JTextField daysStayingTxt;
private JTextField checkOutOnTxt;
private JTextField siteNumberTxt;
private JTextField powerTxt;
private JFrame frame;
private JTable table;
private SiteModel model;
private JScrollPane scrollPane;
private DialogCheckInRv newRv;
public GUICampingReg() {
setupFrame();
newRv = new DialogCheckInRv(this);
model = new SiteModel();
table.setModel(model);
}
private void setupFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Camping Registration Program");
scrollPane = new JScrollPane();
table = new JTable();
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.add(openSerialFileItem);
fileMenu.add(openTextFileItem);
fileMenu.add(saveSerialFileItem);
fileMenu.add(saveTextFileItem);
fileMenu.add(exitItem);
JMenu checkInMenu = new JMenu("Check In");
checkInMenu.add(checkInRVItem);
checkInMenu.add(checkInTentItem);
JMenu checkOutMenu = new JMenu("Check Out");
checkOutMenu.add(checkOutItem);
menubar.add(fileMenu);
menubar.add(checkInMenu);
menubar.add(checkOutMenu);
openSerialFileItem.addActionListener(this);
openTextFileItem.addActionListener(this);
saveSerialFileItem.addActionListener(this);
saveTextFileItem.addActionListener(this);
exitItem.addActionListener(this);
checkInTentItem.addActionListener(this);
checkInRVItem.addActionListener(this);
checkOutItem.addActionListener(this);
frame.setJMenuBar(menubar);
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setToolTipText("");
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked();
}
});
scrollPane.setViewportView(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void tableMouseClicked() {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent evt) {
Object pressed = evt.getSource();
if (pressed == exitItem) {
System.exit(0);
}
if (pressed == openSerialFileItem) {
}
if (pressed == openTextFileItem) {
}
if (pressed == saveSerialFileItem) {
}
if (pressed == saveTextFileItem) {
}
if (pressed == checkInTentItem) {
}
if (pressed == checkInRVItem) {
newRv.clear();
newRv.setVisible(true);
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
}
if (pressed == checkOutItem) {
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUICampingReg();
}
});
}
}
The site model class:
package campingPrj;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class SiteModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private ArrayList<Site> listSites;
private String[] columnNames = { "Name Reserving", "Checked in Date",
"Days Staying", "Site #", "Tenters/RV Power Needed" };
public SiteModel() {
listSites = new ArrayList<Site>();
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return listSites.size();
}
public Object getValueAt(int row, int col) {
Object val = null;
switch (col) {
case 0:
val = listSites.get(row).getNameReserving();
break;
case 1:
val = listSites.get(row).getCheckIn();
break;
case 2:
val = listSites.get(row).getDaysStaying();
break;
case 3:
val = listSites.get(row).getSiteNumber();
break;
case 4:
val = listSites.get(row).getCheckOutOn();
break;
}
return val;
}
public Site get(int index) {
return listSites.get(index);
}
public int indexOf(Site s) {
return listSites.indexOf(s);
}
public void add(Site s) {
if (s != null) {
listSites.add(s);
fireTableRowsInserted(listSites.size() - 1, listSites.size() - 1);
}
}
public void add(int index, Site s) {
if (s != null) {
listSites.add(index, s);
fireTableRowsInserted(index, index);
}
}
public void remove(int index) {
listSites.remove(index);
fireTableRowsDeleted(index, index);
return;
}
public void remove(Site s) {
remove(indexOf(s));
}
public void saveAsSerialized(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(listSites);
os.close();
}
#SuppressWarnings("unchecked")
public void loadFromSerialized(String filename) throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream is = new ObjectInputStream(fis);
listSites = (ArrayList<Site>) is.readObject();
is.close();
}
}
So, how do I get the information to show up in JTable?
Maybe I'm misinterpreting your code, but I don't see where you areextracting the information that the user enters into the dialog. For example here:
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
You appear to be extracting information from the fields held by the GUICampingReg, not by the newRv object. Shouldn't you be calling methods of newRv to extract the data needed to create your RV object?
for example,
if (newRv.isOk()) {
String nameReserving = newRv.getName();
String checkIn = newRv.getDateIn();
// .... etc
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}

Using variable from actionlistener to a class

Help I'm lost I still cant use the previously initiated variable, I dont know if I'm doing this right I'm still new to java. I've been trying to build a payroll system, and I'm stuck at reading a variable from an action listener. Thanks in advance!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.print.attribute.SetOfIntegerSyntax;
import javax.swing. * ;
import java.awt. * ;
import java.awt.event. * ;
#SuppressWarnings("serial")
public class kapoy extends JFrame {
public static JTextField text1;
public static JTextField text2;
public JLabel label1;
public JLabel label2;
public JPanel panel1;
public JPanel panel2;
public JPanel panel3;
public JPanel panel4;
public kapoy() {
text1 = new JTextField();
text1.setPreferredSize(new Dimension(50, 20));
text2 = new JTextField();
text2.setPreferredSize(new Dimension(50, 20));
label1 = new JLabel("Inpute Employee ID: ");
label2 = new JLabel("Input worked Days: ");
panel1 = new JPanel();
panel1.setLocation(0, 0);
panel1.setSize(300, 40);
panel1.setBackground(Color.blue);
panel1.add(label1);
panel1.add(text1);
add(panel1);
panel2 = new JPanel();
panel2.setLocation(0, 40);
panel2.setSize(300, 40);
panel2.setBackground(Color.red);
panel2.add(label2);
panel2.add(text2);
add(panel2);
panel3 = new JPanel();
panel3.setLocation(0, 80);
panel3.setSize(400, 200);
panel3.setBackground(Color.green);
add(panel3);
panel4 = new JPanel();
panel4.setLocation(300, 0);
panel4.setSize(100, 80);
panel4.setBackground(Color.yellow);
add(panel4);
setSize(410, 300);
setLayout(null);
setTitle("Pay Roll by Migz");
}
public static void main(String[]args) {
kapoy cn = new kapoy();
cn.setVisible(true);
text1.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
try {
int idnum = Integer.parseInt(text1.getText());
bweset ka = new bweset(idnum);
} catch (NumberFormatException nfe) {
text1.setText("");
}
}
});
try {
File f = new File("D:/Users/DAVID Family/Desktop/Employees.txt");
Scanner sc = new Scanner(f);
List < Employee > people = new ArrayList < Employee > ();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[]details = line.split(" ");
int Id = Integer.parseInt(details[0]);
String name = details[1];
int rate = Integer.parseInt(details[2]);
Employee p = new Employee(Id, name, rate);
if (ka == Id) {
people.add(p);
}
}
for (Employee p : people) {
System.out.println(p.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class bweset {
private int ka;
public bweset(int ka) {
this.ka = ka;
}
public int getka() {
return ka;
}
public void setka(int ka) {
this.ka = ka;
}
public int ka() {
return this.ka;
}
public int toint() {
return this.ka;
}
}
class Employee {
private int Id;
private String name;
private int rate;
public Employee(int Id, String name, int rate) {
this.Id = Id;
this.setName(name);
this.rate = rate;
}
public int getId() {
return Id;
}
public void setId(int Id) {
this.Id = Id;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getrate() {
return rate;
}
public void setrate(int rate) {
this.rate = rate;
}
public String toString() {
return this.Id + " " + this.name + " " + this.rate;
}
}

Categories