I have 2 classes (IterativeVsRecursive and Sequence) and the Sequence class performs mathematical actions and returns the values to IterativeVsRecursive, or at least that is the intent.
I believe I am missing something easy, but am stumped on how to make this work.
IterativeVsRecursive Class:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.sound.midi.Sequence;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class IterativeVsRecursiveGUI extends JFrame implements ActionListener {
private JLabel radioButton1Label = new JLabel();
private JLabel radioButton2Label = new JLabel();
private JLabel inputLabel = new JLabel();
private JLabel resultLabel = new JLabel();
private JLabel efficiencyLabel = new JLabel();
private JLabel computeButtonLabel = new JLabel();
private ButtonGroup radioButtonGroup = new ButtonGroup();
private JRadioButton radioButtonIterative = new JRadioButton("Iterative");
private JRadioButton radioButtonRecursive = new JRadioButton("Recursive");
private JTextField inputField = new JTextField();
private JTextField resultField = new JTextField();
private JTextField efficiencyField = new JTextField();
private JButton computeButton = new JButton();
private int efficiencyCounter;
public IterativeVsRecursiveGUI()
{
super("Project 3");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(6, 2));
radioButtonGroup.add(radioButtonIterative);
radioButtonIterative.setSelected(true);
// radioButtonIterative.setText("Iterative");
getContentPane().add(radioButtonIterative);
radioButtonGroup.add(radioButtonRecursive);
// radioButtonRecursive.setText("Recursive");
getContentPane().add(radioButtonRecursive);
inputLabel.setText("Enter number: ");
getContentPane().add(inputLabel);
getContentPane().add(inputField);
computeButton.setText("Compute");
computeButton.addActionListener(this);
getContentPane().add(computeButton);
resultLabel.setText("Result: ");
getContentPane().add(resultLabel);
getContentPane().add(resultLabel);
resultField.setEditable(false);
efficiencyLabel.setText("Efficiency: ");
getContentPane().add(efficiencyLabel);
getContentPane().add(efficiencyField);
efficiencyField.setEditable(false);
pack();
}
#Override
public void actionPerformed(ActionEvent button) {
int result;
efficiencyCounter = 0;
if (radioButtonIterative.isSelected()) {
result = Sequence.computeIterative(Integer.parseInt(inputField.getText()));
} else {
result = Sequence.computeRecursive(Integer.parseInt(inputField.getText()));
}
resultField.setText(Integer.toString(result));
efficiencyField.setText(Integer.toString(efficiencyCounter));
}
public static void main(String[] args) {
IterativeVsRecursiveGUI IterativeVsRecursiveGUI = new IterativeVsRecursiveGUI();
IterativeVsRecursiveGUI.setVisible(true);
}
}
Sequence class:
public class Sequence {
private int efficiencyCounter = 0;
public int computeIterative(int input) {
int answer = 0;
if (input == 0) {
efficiencyCounter++;
answer = 0;
} else if (input == 1) {
efficiencyCounter++;
answer = 1;
} else {
efficiencyCounter++;
int firstTerm = 0;
int secondTerm = 1;
for (int i = 2; i <= input; i++) {
answer = (3 * secondTerm) - (2 * firstTerm);
firstTerm = secondTerm;
secondTerm = answer;
}
}
return answer;
}
public int computeRecursive(int input) {
int answer = 0;
efficiencyCounter++;
if (input == 0) {
answer = 0;
} else if (input == 1) {
answer = 1;
} else {
answer = (3 * computeRecursive(input - 1)) - (2 * computeRecursive(input - 2));
}
return answer;
}
}
The intent is to have a GUI that displays the results of the Sequence class.
I should have been clear in that it is not allowing me to call the non-static methods in Sequence, but if I make them static, by adding "void", then the computeRecursive method throws an errror saying that 'void' type not allowed here
Or, since the method is already an instance method, create an instance of Sequence
#Override
public void actionPerformed(ActionEvent button) {
int result;
efficiencyCounter = 0;
Sequence sequence = new Sequence();
if (radioButtonIterative.isSelected()) {
result = sequence.computeIterative(Integer.parseInt(inputField.getText()));
} else {
result = sequence.computeRecursive(Integer.parseInt(inputField.getText()));
}
resultField.setText(Integer.toString(result));
efficiencyField.setText(Integer.toString(efficiencyCounter));
}
Related
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;
}
}
}
So I am trying to highlight the keywords in java,which I have stored in a text file, as the user opens a .java file or writes to .java file. I think I know how to tell if the file is of the right type. However, I do not know how to change the color of certain keywords. If anyone could help out that would be great because right now it's pretty confusing. I was wondering if I could use my replace function somehow. I have tried to go about trying to do this with the few methods I have, yet it's still not clear. I have taken out he majority of the methods and listeners, just know they are there but kept out to make it easier to read.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import java.util.Scanner;
import java.io.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.JTextComponent;
import java.net.URI;
import java.util.*;
public class MyTextEditor extends JFrame implements ActionListener
{
private JPanel panel = new JPanel(new BorderLayout());
private JTextArea textArea = new JTextArea(0,0);
private static final Color TA_BKGRD_CL = Color.BLACK;
private static final Color TA_FRGRD_CL = Color.GREEN;
private static final Color TA_CARET_CL = Color.WHITE;
private JScrollPane scrollPane;
private MenuBar menuBar = new MenuBar();
public MyTextEditor()
{
this.setSize(750,800);
this.setTitle("Zenith");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea.setFont(new Font("Consolas", Font.BOLD, 14));
textArea.setForeground(TA_FRGRD_CL);
textArea.setBackground(TA_BKGRD_CL);
textArea.setCaretColor(TA_CARET_CL);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVisible(true);
textArea.add(scrollPane,BorderLayout.EAST);
final LineNumberingTextArea lineNTA = new LineNumberingTextArea(textArea);
DocumentListener documentListen = new DocumentListener()
{
public void insertUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
public void removeUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
public void changedUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
};
textArea.getDocument().addDocumentListener(documentListen);
// Line numbers
lineNTA.setBackground(Color.BLACK);
lineNTA.setForeground(Color.WHITE);
lineNTA.setFont(new Font("Consolas", Font.BOLD, 13));
lineNTA.setEditable(false);
lineNTA.setVisible(true);
textArea.add(lineNTA);
scrollPane.setVisible(true);
scrollPane.add(textArea);
getContentPane().add(scrollPane);
}
public void findKeyWords(String ext)
{
ArrayList<String> wordsInTA = new ArrayList<String>();
int index = 0;
if(ext == "java")
{
for(String line : textArea.getText().split(" "))
{
wordsInTA.add(line);
index++;
}
try
{
while(index>0)
{
String temp = wordsInTA.get(index);
boolean isKeyWord = binarySearch(temp);
if(isKeyWord)
{
//Code that has not yet been made
}
index--;
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
private ArrayList<String> loadJavaWords() throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
Scanner scan = new Scanner(new File("JavaKeyWords.txt"));
while(scan.hasNext())
{
javaWords.add(scan.next());
}
scan.close();
return javaWords;
}
private boolean binarySearch(String word) throws FileNotFoundException
{
ArrayList<String> javaWords = loadJavaWords();
int min = 0;
int max = javaWords.size()-1;
while(min <= max)
{
int index = (max + min)/2;
String guess = javaWords.get(index);
int result = word.compareTo(guess);
if(result == 0)
{
return true;
}
else if(result > 0)
{
min = index +1;
}
else if(result < 0)
{
max = index -1;
}
}
return false;
}
public void replace()
{
String wordToSearch = JOptionPane.showInputDialog(null, "Word to replace:");
String wordToReplace = JOptionPane.showInputDialog(null, "Replacement word:");
int m;
int total = 0;
int wordLength = wordToSearch.length();
for (String line : textArea.getText().split("\\n"))
{
m = line.indexOf(wordToSearch);
if(m == -1)
{
total += line.length() + 1;
continue;
}
String newLine = line.replaceAll(wordToSearch, wordToReplace);
textArea.replaceRange(newLine, total, total + line.length());
total += newLine.length() + 1;
}
}
public static void main(String args[])
{
MyTextEditor textEditor = new MyTextEditor();
textEditor.setVisible(true);
}
}
So I've been trying to figure out why my JApplet is starting and giving no errors but nothing is showing up. I have an init() method that calls setup_layout(), but I think I may have done something wrong the layouts. Anyone help?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Assignment8 extends JApplet implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_DIGITS = 30;
private JTextArea operand, result;
private double answer = 0.0;
private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB,
zeroB, dotB, addB, resetB, clearB, sqrtB, absB, expB;
/** public static void main(String[] args)
{
Assignment8 aCalculator = new Assignment8( );
aCalculator.setVisible(true);
}**/
public void init( )
{
setup_layout();
}
private void setup_layout() {
setSize(WIDTH, HEIGHT);
JPanel MainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel calcPanel = new JPanel();
JPanel textPanel = new JPanel ();
buttonPanel.setLayout(new GridLayout(3, 4));
calcPanel.setLayout(new GridLayout(3, 3));
textPanel.setLayout(new FlowLayout());
MainPanel.setLayout(new BorderLayout());
MainPanel.setBackground(Color.red);
operand = new JTextArea();
result = new JTextArea();
operand.setEditable(false);
result.setEditable(false);
textPanel.add(operand);
textPanel.add(result);
sevenB = new JButton("7");
eightB = new JButton("8");
nineB = new JButton("9");
divideB = new JButton("/");
fourB = new JButton("4");
fiveB = new JButton("5");
sixB = new JButton("6");
multiplyB = new JButton("*");
oneB = new JButton("1");
twoB = new JButton("2");
threeB = new JButton("3");
subtractB = new JButton("-");
zeroB = new JButton("0");
dotB = new JButton(".");
addB = new JButton("+");
resetB = new JButton("Reset");
clearB = new JButton("Clear");
sqrtB = new JButton("Sqrt");
absB = new JButton("Abs");
expB = new JButton("Exp");
sevenB.addActionListener(this);
eightB.addActionListener(this);
nineB.addActionListener(this);
divideB.addActionListener(this);
fourB.addActionListener(this);
fiveB.addActionListener(this);
sixB.addActionListener(this);
multiplyB.addActionListener(this);
oneB.addActionListener(this);
twoB.addActionListener(this);
threeB.addActionListener(this);
subtractB.addActionListener(this);
zeroB.addActionListener(this);
dotB.addActionListener(this);
addB.addActionListener(this);
resetB.addActionListener(this);
clearB.addActionListener(this);
absB.addActionListener(this);
expB.addActionListener(this);
sqrtB.addActionListener(this);
buttonPanel.add(sevenB);
buttonPanel.add(eightB);
buttonPanel.add(nineB);
buttonPanel.add(fourB);
buttonPanel.add(fiveB);
buttonPanel.add(sixB);
buttonPanel.add(oneB);
buttonPanel.add(twoB);
buttonPanel.add(threeB);
buttonPanel.add(zeroB);
buttonPanel.add(dotB);
calcPanel.add(subtractB);
calcPanel.add(multiplyB);
calcPanel.add(divideB);
calcPanel.add(sqrtB);
calcPanel.add(absB);
calcPanel.add(expB);
calcPanel.add(addB);
calcPanel.add(resetB);
calcPanel.add(clearB);
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
assumingCorrectNumberFormats(e);
}
catch (NumberFormatException e2)
{
result.setText("Error: Reenter Number.");
}
catch (DivideByZeroException e1) {
result.setText("Error: CANNOT Divide By Zero. Reenter Number.");
}
}
//Throws NumberFormatException.
public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("1"))
{
int num = 1;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("2"))
{
int num = 2;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("3"))
{
int num = 3;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("4"))
{
int num = 4;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("5"))
{
int num = 5;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("6"))
{
int num = 6;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("7"))
{
int num = 7;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("8"))
{
int num = 8;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("9"))
{
int num = 9;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("0"))
{
int num = 0;
String text = operand.getText();
//double check = stringToDouble(text);
if(text.isEmpty()||text.contains(".")) {
operand.append(Integer.toString(num));
}
}
else if (actionCommand.equals("."))
{
String text = operand.getText();
if(!text.contains(".")) {
operand.append(".");
}
}
else if (actionCommand.equals("+"))
{
answer = answer + stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("-"))
{
answer = answer - stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("*"))
{
answer = answer * stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("/"))
{
double check = stringToDouble(operand.getText());
if(check >= -1.0e-10 && check <= 1.0e-10 ) {
throw new DivideByZeroException();
}
else {
answer = answer / stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Sqrt"))
{
double check = stringToDouble(result.getText());
if(check < 0 ) {
throw new NumberFormatException();
}
else {
answer = Math.sqrt(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Abs"))
{
answer = Math.abs(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Exp"))
{
answer = Math.pow(stringToDouble(result.getText( )),stringToDouble(operand.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Reset"))
{
answer = 0.0;
result.setText("");
operand.setText("");
}
else if (actionCommand.equals("Clear"))
{
operand.setText("");
}
else
result.setText("Unexpected error.");
}
//Throws NumberFormatException.
private static double stringToDouble(String stringObject)
{
return Double.parseDouble(stringObject.trim( ));
}
//Divide by Zero Exception Class
public class DivideByZeroException extends Exception {
DivideByZeroException() {
}
}
}
You never add MainPanel to the applet itself.
i.e.,
add(MainPanel);
Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e.,
change this:
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
to:
MainPanel.add(buttonPanel, BorderLayout.CENTER);
MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this
MainPanel.add(textPanel, BorderLayout.PAGE_START);
Note that your code can be simplified greatly by using arrays or Lists.
Or could simplify it in other ways, for instance:
public void assumingCorrectNumberFormats(ActionEvent e)
throws DivideByZeroException {
String actionCommand = e.getActionCommand();
String numbers = "1234567890";
if (numbers.contains(actionCommand)) {
operand.append(actionCommand);
// if you need to work with it as a number
int num = Integer.parseInt(actionCommand);
}
Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.
I am confused at what is going wrong here.
I believe its something wrong with the way JFrame is set up.
There is also a generator class but I think if I can get the launcher working then the Generator will come after.
Any help is greatly appreciated!
here is my source code:
main:
public class Main {
static Launcher launcher;
public static void main(String[]args){
launcher = new Launcher();
}
}
Launcher:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
#SuppressWarnings("serial")
public class Launcher extends JFrame {
public static Font titleFont;
public static Font secondFont;
public static Font generateFont;
public static int levelHeight;
public static int levelWidth;
public static String tileWidth;
public static String tileHeight;
public static String destination;
public static String levelSource;
public static String tilesetSource;
public static int tilesetWidth;
public static int tilesetHeight;
public static Box box;
public static JPanel panel;
public static JPanel panel1;
public static JPanel panel2;
public static JPanel panel3;
public static JPanel panel4;
public static JPanel panel5;
public static JPanel panel6;
public static JLabel lbltitle;
public static JLabel lblsecondTitle;
public static JLabel lblemptyString;
public static JLabel lblemptyString2;
public static JLabel lblcomment;
public static JLabel lblauthor;
public static JLabel lblTileWidth;
public static JLabel lblTileHeight;
public static JLabel lblDestinationFile;
public static JLabel lblLevelSourceFile;
public static JLabel lblTileSetSourceFile;
public static JLabel lblHelp;
public static JButton generate;
public static JTextField tfTileWidth;
public static JTextField tfTileHeight;
public static JTextField tfDestinationFile;
public static JTextField tfLevelSourceFile;
public static JTextField tfTileSetSourceFile;
public static int dWidth;
public static int dHeight;
public static int dTileWidth;
public static int dTileHeight;
public static int dTilesetHeight;
public static int dTilesetWidth;
public static File fDestination;
public static File fLevelSource;
public static File fTileSetSource;
public static File tsdirectory;
public static File lmdirectory;
public static File[] tsList;
public static File[] lmList;
public static String[] tslist;
public static String[] lmlist;
public static int i;
public static int checkInputs;
private JComboBox<String> comboBox;
private JComboBox<String> comboBox1;
public Launcher(){
super("Dafon's World: Level Generator");
init();
}
public void init(){
i = 0;
checkInputs = 0;
setFrame();
setDirectories();
setFonts();
setJLabels();
setJButton();
setJTextFields();
setJPanels();
setBox();
addListeners();
add(box, BorderLayout.NORTH);
add(lblauthor, BorderLayout.SOUTH);
setVisible(true);
System.out.println("init() completed\n");
}
public void setFrame(){
setSize(400, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setFocusable(true);
setLocationRelativeTo(null);
System.out.println("Frame set");
}
public void setDirectories(){
lmdirectory = new File("Resources/LevelMaps");
tsdirectory = new File("Resources/TileSets");
comboBox = new JComboBox<String>();
comboBox1 = new JComboBox<String>();
tsList = tsdirectory.listFiles();
tslist = new String[tsList.length];
for (int i = 0; i < tsList.length; ++i){
tslist[i] = tsList[i].getName();
comboBox.addItem(tslist[i]);
}
lmList = lmdirectory.listFiles();
lmlist = new String[lmList.length];
for (int i = 0; i < lmList.length; ++i){
lmlist[i] = lmList[i].getName();
comboBox1.addItem(lmlist[i]);
}
System.out.println("Directories set");
}
public void setJPanels(){
panel = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
panel5 = new JPanel();
panel6 = new JPanel();
panel.add(lblTileWidth);
panel.add(tfTileWidth);
panel2.add(lblTileHeight);
panel2.add(tfTileHeight);
panel3.add(lblTileSetSourceFile);
panel3.add(comboBox);
panel4.add(lblLevelSourceFile);
panel4.add(comboBox1);
panel5.add(lblDestinationFile);
panel5.add(tfDestinationFile);
panel6.add(lblHelp);
System.out.println("JPanels set");
}
public void setFonts(){
titleFont = new Font("Verdana", 1, 38);
secondFont = new Font("Verdana", 2, 28);
generateFont = new Font("Verdana", 0, 16);
System.out.println("Fonts Set");
}
public void setJLabels(){
lbltitle = new JLabel("Dafon's World:");
lbltitle.setFont(titleFont);
lbltitle.setAlignmentX(JLabel.CENTER_ALIGNMENT);
lblsecondTitle = new JLabel("Level Generator");
lblsecondTitle.setFont(secondFont);
lblsecondTitle.setAlignmentX(JLabel.CENTER_ALIGNMENT);
lblemptyString = new JLabel(" ");
lblemptyString.setFont(secondFont);
lblemptyString2 = new JLabel(" ");
lblemptyString2.setFont(secondFont);
lblauthor = new JLabel("Created by Brett A. Blashko", SwingConstants.RIGHT);
lblcomment = new JLabel("** Please you enter all of the fields below **");
lblcomment.setForeground(Color.red);
lblcomment.setAlignmentX(CENTER_ALIGNMENT);
lblTileWidth = new JLabel("Tile Width: ");
lblTileHeight = new JLabel("Tile Height: ");
lblDestinationFile = new JLabel("TileMap Destination Filename (.txt):");
lblLevelSourceFile = new JLabel("Level Source Filename (.png):");
lblTileSetSourceFile = new JLabel("TileSet Source Filename (.png):");
lblHelp = new JLabel();
lblHelp.setText("**One or more fields have been filled in incorrectly**");
lblHelp.setForeground(Color.red);
lblHelp.setAlignmentX(JLabel.CENTER_ALIGNMENT);
System.out.println("JLabels set");
}
public void setJButton(){
generate = new JButton("Generate!");
generate.setAlignmentX(CENTER_ALIGNMENT);
generate.setLayout(null);
generate.setPreferredSize(new Dimension(600, 40));
generate.setFont(generateFont);
}
public void setJTextFields(){
tfTileWidth = new JTextField("", 12);
tfTileHeight = new JTextField("", 12);
tfDestinationFile = new JTextField("", 12);
tfLevelSourceFile = new JTextField("", 12);
tfTileSetSourceFile = new JTextField("", 12);
System.out.println("JTextFields set");
}
public void setBox(){
box = Box.createVerticalBox();
box.add(lbltitle);
box.add(lblsecondTitle);
box.add(lblemptyString);
box.add(lblcomment);
box.add(panel);
box.add(panel2);
box.add(panel3);
box.add(panel4);
box.add(panel5);
box.add(lblemptyString2);
box.add(generate);
box.add(lblHelp).setVisible(false);
System.out.println("Box set");
}
public void addListeners(){
comboBox.addActionListener(new comboBoxListener());
comboBox1.addActionListener(new comboBoxListener());
generate.addActionListener(new ButtonPressedListener());
tfTileWidth.addFocusListener(new tfTextListener());
tfTileHeight.addFocusListener(new tfTextListener());
tfDestinationFile.addFocusListener(new tfTextListener());
tfLevelSourceFile.addFocusListener(new tfTextListener());
tfTileSetSourceFile.addFocusListener(new tfTextListener());
System.out.println("Listeners created");
}
public class comboBoxListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == comboBox){
i = 2;
String s = "Resources/TileSets/" + comboBox.getItemAt(comboBox.getSelectedIndex());
fTileSetSource = new File(s);
comboBox.setBackground(Color.green);
checkInputs++;
}
if(e.getSource() == comboBox1){
i = 3;
String s = "Resources/LevelMaps/" + comboBox1.getItemAt(comboBox1.getSelectedIndex());
fLevelSource = new File(s);
comboBox1.setBackground(Color.green);
checkInputs++;
}
}
}
public class tfTextListener implements FocusListener{
public void focusGained(FocusEvent e) {
if(e.getSource() == tfTileWidth){
tfTileWidth.setBackground(Color.white);
i = 0;
}
if(e.getSource() == tfTileHeight){
tfTileHeight.setBackground(Color.white);
i = 1;
}
if(e.getSource() == tfDestinationFile){
tfDestinationFile.setBackground(Color.white);
i = 4;
}
}
public void focusLost(FocusEvent e) {
if(e.getSource() == tfTileWidth){
tileWidth = tfTileWidth.getText();
stringType(tileWidth);
}
if(e.getSource() == tfTileHeight){
tileHeight = tfTileHeight.getText();
stringType(tileHeight);
}
if(e.getSource() == tfTileSetSourceFile){
tilesetSource = tfTileSetSourceFile.getText();
stringType(tilesetSource);
}
if(e.getSource() == tfLevelSourceFile){
levelSource = tfLevelSourceFile.getText();
stringType(levelSource);
}
if(e.getSource() == tfDestinationFile){
destination = tfDestinationFile.getText();
stringType(destination);
}
}
}
public static void stringType(String str) {
int length = 0;
length = str.length();
if (i >= 0 && i < 2) {
try {
int d = (int)Double.parseDouble(str);
if(i == 0){
dTileWidth = d;
tfTileWidth.setBackground(Color.green);
checkInputs++;
}else if(i == 1){
dTileHeight = d;
tfTileHeight.setBackground(Color.green);
checkInputs++;
}
System.out.println("Entry is valid number");
} catch (NumberFormatException nfe) {
System.out.println("Entry is not valid number");
if(i == 0){
tfTileWidth.setBackground(Color.red);
}else if(i == 1){
tfTileHeight.setBackground(Color.red);
}
}
} else {
length = str.length();
if (str.matches("[a-zA-Z._0-9]+") && length >= 4 && length != 0) {
if(i == 2){
if (str.substring(length - 4, length).equals(".png")) {
System.out.println("Entry is a valid String");
String file = ("Resources/TileSets/" + str);
fTileSetSource = new File(file);
if(fTileSetSource.exists()) {
tfTileSetSourceFile.setBackground(Color.green);
checkInputs++;
}else{
tfTileSetSourceFile.setBackground(Color.red);
}
}
}else if(i == 3){
if (str.substring(length - 4, length).equals(".png")) {
System.out.println("Entry is a valid String");
String file = ("Resources/LevelMaps/" + str);
fLevelSource = new File(file);
if(fLevelSource.exists()) {
tfLevelSourceFile.setBackground(Color.green);
checkInputs++;
}else{
tfLevelSourceFile.setBackground(Color.red);
}
}
}else if(i == 4){
if (str.substring(length - 4, length).equals(".txt")) {
System.out.println("Entry is a valid String");
tfDestinationFile.setBackground(Color.green);
String file = ("Resources/TileMaps/" + str);
fDestination = new File(file);
checkInputs++;
}
}
} else {
System.out.println("Entry is not a valid String");
if(i == 2){
tfTileSetSourceFile.setBackground(Color.red);
}else if(i == 3){
tfLevelSourceFile.setBackground(Color.red);
}else if(i == 4){
tfDestinationFile.setBackground(Color.red);
}
}
}
}
public class ButtonPressedListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(checkInputs >= 5){
dispose();
Generator gen = new Generator();
gen.setDefaultCloseOperation(EXIT_ON_CLOSE);
}else{
box.getComponent(11).setVisible(true);
repaint();
}
}
}
public void lsetvisible(boolean b){
setVisible(b);
}
}
I'm working on a calculator application (which I have simplified downed to make it easier to debug). When the user hits '=' the IMPORTANTINT will change to 1. When the users clicks another button the field is supposed to clear with the if then statement in CalculatorEngine:
if(IMPORTANTINT == 1){
System.out.println("Ran the block of code");
parent.setDisplayValue("");
IMPORTANTINT = 0;
System.out.println(IMPORTANTINT);
}
This is done so the user can view the result and then start a new calculation. The textField doesn't want to clear. Does anyone know why this is? Thanks!
CalculatorEngine.java
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JButton;
public class CalculatorEngine implements ActionListener{
Calculator parent;
double firstNum, secondNum;
String symbol;
int IMPORTANTINT = 0;
CalculatorEngine(Calculator parent){
this.parent = parent;
}
public void actionPerformed(ActionEvent e){
JButton clickedButton = (JButton) e.getSource();
String clickedButtonLabel = clickedButton.getText();
String dispFieldText = parent.getDisplayValue();
if(IMPORTANTINT == 1){
System.out.println("Ran the block of code");
parent.setDisplayValue("");
IMPORTANTINT = 0;
System.out.println(IMPORTANTINT);
}
if(clickedButtonLabel == "+"){
firstNum = (Double.parseDouble(parent.getDisplayValue()));
parent.setDisplayValue("");
symbol = clickedButtonLabel;
} else if(clickedButtonLabel == "="){
IMPORTANTINT = 1;
secondNum = Double.parseDouble(parent.getDisplayValue());
double answer = firstNum + secondNum;
parent.setDisplayValue(Double.toString(answer));
} else{
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
}
Calculator.java
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
public class Calculator {
private JPanel windowContent;
private JPanel p1;
private JPanel sideBar;
private JTextField displayField;
private JButton button8;
private JButton button9;
private JButton buttonEqual;
private JButton buttonPlus;
Calculator(){
windowContent= new JPanel();
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
displayField = new JTextField(30);
windowContent.add("North",displayField);
button8=new JButton("8");
button9=new JButton("9");
buttonEqual=new JButton("=");
buttonPlus = new JButton("+");
p1 = new JPanel();
GridLayout gl =new GridLayout(4,3);
p1.setLayout(gl);
sideBar = new JPanel();
GridLayout gl2 = new GridLayout(5,1);
sideBar.setLayout(gl2);
p1.add(button8);
p1.add(button9);
p1.add(buttonEqual);
sideBar.add(buttonPlus);
windowContent.add("Center", p1);
windowContent.add("East", sideBar);
JFrame frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
frame.pack();
frame.setVisible(true);
CalculatorEngine calcEngine = new CalculatorEngine(this);
button8.addActionListener(calcEngine);
button9.addActionListener(calcEngine);
buttonEqual.addActionListener(calcEngine);
buttonPlus.addActionListener(calcEngine);
}
public void setDisplayValue(String val){
displayField.setText(val);
}
public String getDisplayValue(){
return displayField.getText();
}
public static void main(String[] args)
{
Calculator calc = new Calculator();
}
}
public void setDisplayValue(String val){
SwingUtilities.invokeLater(new Runnable{
#Override
public void run()
{
displayField.setText(val);
}
});
}
You are effectively caching the dispFieldText before entering the IMPORTANTINT if statement block. Therefore the JTextField is being cleared but subsequently then to the cached value in the else block.
if (IMPORTANTINT == 1) {
dispFieldText = ""; // add this
...
}
if (clickedButtonLabel.equals("+")) {
...
} else if (clickedButtonLabel.equals("=")) {
...
} else {
// Field being reset here vvvv
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
Make sure to clear the variable. Use String#equals to check String content. The == operator checks Object references.
Aside: Use Java naming conventions, IMPORTANTINT is a modifiable variable so should be importantInt (A boolean typically handles a true/false scenario)