Java displayField refuses to clear - java

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)

Related

How to use a button press from a second JFrame in a seperate Class as an action in the main class

So for school, we have to make 2 separate JFrames that interact with each other. From within the first JFrame, a button gets pressed which opens the second one, where a name, speed, and position can be filled in.
When pressing OK on the second JFrame, I save the filled-in text and numbers but I have no clue how to use them in the code of the first JFrame. I had tried to use a "getter" from the second JFrame to check in the first one if the "OK" button had been pressed. But this gets checked immediately after opening the window. That means it isn't true YET and it doesn't check it again.
CONTEXT:
We are forced to use 2 separate JFrame.
We are not allowed to add extra methods.
We are not allowed to change the constructor.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TourFrame extends JFrame implements ActionListener{
private Etappe etappe;
private JLabel jlAantal;
private JTextField jtfAantal;
private JButton knopPrint;
private JButton knopStap;
private JButton knopVoegFietsenToe;
private JButton knopVoegCustomFietsToe;
public TourFrame(Etappe etappe){
this.etappe = etappe;
setTitle("Tour de Windesheim: " + etappe.toString());
setSize(650, 550);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlAantal = new JLabel("aantal:");
add(jlAantal);
jtfAantal = new JTextField(10);
add(jtfAantal);
knopPrint = new JButton("print");
add(knopPrint);
knopPrint.addActionListener(this);
knopStap = new JButton("stap");
add(knopStap);
knopStap.addActionListener(this);
knopVoegFietsenToe = new JButton("voeg fietsen toe");
add(knopVoegFietsenToe);
knopVoegFietsenToe.addActionListener(this);
knopVoegCustomFietsToe = new JButton("voeg custom fiets toe");
add(knopVoegCustomFietsToe);
knopVoegCustomFietsToe.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == knopPrint){
etappe.print();
} else if(e.getSource() == knopStap){
etappe.stap();
setTitle("Tour de Windesheim: " + etappe.toString());
} else if(e.getSource() == knopVoegFietsenToe){
try {
int aantal = Integer.parseInt(jtfAantal.getText());
for(int i = 0; aantal > i; i++){
Fiets tijdelijk = new Fiets();
etappe.voegDeelnemerToe(tijdelijk);
}
} catch (NumberFormatException nfe){
jlAantal.setText("Voer een getal in");
}
} else if(e.getSource() == knopVoegCustomFietsToe){
FietsDialoog fietsdialoog = new FietsDialoog();
}
}
}
The Second one looks as follwed:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FietsDialoog extends JFrame implements ActionListener {
private JLabel jlNaam;
private JTextField jtfNaam;
private JLabel jlStartPositie;
private JTextField jtfStartPositie;
private JLabel jlSnelheid;
private JTextField jtfSnelheid;
private JButton knopOk;
private JButton knopCancel;
private String naam;
private int startpositie;
private int snelheid;
private boolean ok;
private boolean cancel;
public FietsDialoog(){
setTitle("FietsDialoog");
setSize(600, 100);
setLayout(new FlowLayout());
setDefaultCloseOperation(HIDE_ON_CLOSE);
jlNaam = new JLabel("naam");
add(jlNaam);
jtfNaam = new JTextField(10);
add(jtfNaam);
jlStartPositie = new JLabel("startpositie");
add(jlStartPositie);
jtfStartPositie = new JTextField(10);
add(jtfStartPositie);
jlSnelheid = new JLabel("snelheid");
add(jlSnelheid);
jtfSnelheid = new JTextField(10);
add(jtfSnelheid);
knopOk = new JButton("ok");
add(knopOk);
knopOk.addActionListener(this);
knopCancel = new JButton("cancel");
add(knopCancel);
knopCancel.addActionListener(this);
setVisible(true);
}
public String getNaam() {
return naam;
}
public int getStartpositie() {
return startpositie;
}
public int getSnelheid() {
return snelheid;
}
public boolean isOk() {
return ok;
}
public boolean isCancel() {
return cancel;
}
public JButton getKnopOk() {
return knopOk;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == knopOk){
this.naam = jtfNaam.getText();
this.startpositie = Integer.parseInt(jtfStartPositie.getText());
this.snelheid = Integer.parseInt(jtfSnelheid.getText());
this.ok = true;
this.cancel = false;
} else if(e.getSource() == knopCancel){
this.ok = false;
this.cancel = true;
dispose();
}
}
}
Try and print fietsdialoog.getNaam(), fietsdialoog.getStartpositie()...etc, the getter from the fietsdialoog class after closing the window.
Also, rather than dispose the window: use setVisible to false. JFrame.setVisible(true/false);

Add multiple instances of the same button

I am creating a simple calculator for a school assignment but I can't get it to work for multiple digits
package calculator;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;
public class Calculator implements ActionListener{
JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new Calculator();
}
});
}
public Calculator()
{
guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Simple Calculator");
guiFrame.setSize(300,300);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
numberCalc = new JTextField();
numberCalc.setHorizontalAlignment(JTextField.RIGHT);
numberCalc.setEditable(false);
guiFrame.add(numberCalc, BorderLayout.NORTH);
buttonPanel = new JPanel();
//Make a Grid that has three rows and four columns
buttonPanel.setLayout(new GridLayout(4,4));
guiFrame.add(buttonPanel, BorderLayout.CENTER);
//Add the number buttons
for (int i=1;i<10;i++)
{
addButton(buttonPanel, String.valueOf(i));
}
JButton addButton = new JButton("+");
addButton.setActionCommand("+");
OperatorAction subAction = new OperatorAction(1);
addButton.addActionListener(subAction);
JButton subButton = new JButton("-");
subButton.setActionCommand("-");
OperatorAction addAction = new OperatorAction(2);
subButton.addActionListener(addAction);
JButton multiplyButton = new JButton("*");
multiplyButton.setActionCommand("*");
OperatorAction multiAction = new OperatorAction(3);
multiplyButton.addActionListener(multiAction);
JButton divideButton = new JButton("/");
divideButton.setActionCommand("/");
OperatorAction diviAction = new OperatorAction(4);
divideButton.addActionListener(diviAction);
JButton clearButton = new JButton("ce");
clearButton.setActionCommand("ce");
OperatorAction clearAction = new OperatorAction(5);
clearButton.addActionListener(clearAction);
JButton blankButton = new JButton(" ");
JButton equalsButton = new JButton("=");
equalsButton.setActionCommand("=");
equalsButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
if (!numberCalc.getText().isEmpty())
{
int number = Integer.parseInt(numberCalc.getText());
if (calcOperation == 1)
{
int calculate = currentCalc + number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 2)
{
int calculate = currentCalc - number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 3)
{
int calculate = currentCalc * number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 4)
{
int calculate = currentCalc / number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 5)
{
int calculate = 0;
numberCalc.setText(Integer.toString(calculate));
}
}
}
});
buttonPanel.add(addButton);
buttonPanel.add(subButton);
buttonPanel.add(equalsButton);
buttonPanel.add(divideButton);
buttonPanel.add(multiplyButton);
buttonPanel.add(clearButton);
buttonPanel.add(blankButton);
guiFrame.setVisible(true);
}
//All the buttons are following the same pattern
//so create them all in one place.
private void addButton(Container parent, String name)
{
JButton but = new JButton(name);
but.setActionCommand(name);
but.addActionListener(this);
parent.add(but);
}
//As all the buttons are doing the same thing it's
//easier to make the class implement the ActionListener
//interface and control the button clicks from one place
#Override
public void actionPerformed(ActionEvent event)
{
//get the Action Command text from the button
String action = event.getActionCommand();
//set the text using the Action Command text
numberCalc.setText(action);
}
private class OperatorAction implements ActionListener
{
private int operator;
public OperatorAction(int operation)
{
operator = operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
}
}
However when I run the code It will not allow me to enter in numbers with more than one digit. Also the ce button I created will not reset to zero.
I have included an image of the output.
Thanks in advance.
Output of calculator
The ActionListener is not correct
#Override
public void actionPerformed(ActionEvent event)
{
//get the Action Command text from the button
String action = event.getActionCommand();
//set the text using the Action Command text
numberCalc.setText(action);
}
This will set the numberCalc text to the value of the button, not append the value.
Use numberCalc.setText(NumberCalc.getText() + action); to append the text
Also, for OperatorAction, you don't update any GUI component
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
You should clear numberCalc to wait for the next value or you will end up with 1 + 12 instead of 1 + 2.
If the button is clearButton, you need to change the logic and reset everything currentCalc, numberCalc, calcOperation, ...

How do I use IntBinaryOperator with a Switch Case Statement for Java Swing? (Simple Calculator)

I'm having trouble getting an output while using the switch-statement and IntBinaryOperator. I'm trying to build a simple calculator in Java, and I found that the IntBinaryOperator cut down on unnecessary boilerplate code. I hope that you can show me the best approach. Thank you.
The three classes that I wrote are below.
package gui_calc;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.function.IntBinaryOperator;
public class CalculatorJFrame extends JFrame implements ActionListener {
static protected JLabel lblOut;
private JButton btnEq;
private JButton btnClear;
public CalculatorJFrame() {
setTitle("CALCULATOR");
JPanel container = new JPanel(); //create a JPanel inside the JFrame as a container
container.setLayout(new BorderLayout());
//add your components in here
lblOut = new JLabel("");
btnEq = new JButton("=");
btnClear = new JButton("C");
btnEq.addActionListener(this);
btnClear.addActionListener(this);
NumButtonsJP numBtns = new NumButtonsJP(); //create an instance of NumButtonsJP
OpButtonsJP opBtns = new OpButtonsJP(); //create an instance of OpButtonsJP
container.add(btnClear, BorderLayout.WEST);
container.add(btnEq, BorderLayout.EAST);
container.add(lblOut, BorderLayout.NORTH);
container.add(numBtns, BorderLayout.CENTER); //add the numBtns JPanel to the container
container.add(opBtns, BorderLayout.SOUTH); //add the opBtns JPanel to the container
add(container); //add container to the JFrame
}
static protected void updateOutLabel(String suffix) {
String currLblContent = lblOut.getText().trim(); //get current content of lblOut
lblOut.setText(currLblContent + suffix); //update the output label on the main container
}
static protected void clearOutLabel() {
lblOut.setText("");
}
#Override
public void actionPerformed(ActionEvent e) {
String face = e.getActionCommand().trim();
switch (face) {
case "=":
//do math... get the values... and reset the label with the result
updateOutLabel("=" + getResultFromQuestion(lblOut.getText()));
break;
case "+":
IntBinaryOperator add = (a,b) -> a + b;
System.out.println("Your answer is" + (add));
break;
case "-":
IntBinaryOperator substract = (a, b) -> a - b;
System.out.println("Your answer is" + (substract.applyAsInt(lblOut.getText().charAt(0),lblOut.getText().charAt(1))));
break;
case "*":
IntBinaryOperator multiply = (a, b) -> a * b;
System.out.println("Your answer is" + (multiply));
break;
case "/":
IntBinaryOperator divide = (a, b) -> a / b;
System.out.println("Your answer is" + divide);
case "C":
clearOutLabel();
break;
}
}
private String getResultFromQuestion(String text) {
double resultStr = 10;
return "" + resultStr;
}
public static void main(String[] args) {
//create instance of calculator and run it
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CalculatorJFrame calcGUI = new CalculatorJFrame();
calcGUI.setDefaultCloseOperation(calcGUI.EXIT_ON_CLOSE);
calcGUI.setSize(300, 300);
calcGUI.setVisible(true);
}
});
}
package gui_calc;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class OpButtonsJP extends JPanel implements ActionListener{
JButton btnAdd = new JButton("+");
JButton btnSub = new JButton("-");
JButton btnMul = new JButton("*");
JButton btnDiv = new JButton("/");
JButton [] opsBtns = {btnAdd, btnSub, btnMul, btnDiv};//array of jbuttons
public OpButtonsJP(){
setLayout(new GridLayout(1,4));
for(int i=0; i<opsBtns.length; i++){
add(opsBtns[i]); //add the button to the JPanel
opsBtns[i].addActionListener(this); //add the ActionListener to make the button functional
}
}
#Override
public void actionPerformed(ActionEvent e) {
String face = e.getActionCommand();
System.out.println(face + " was clicked");
CalculatorJFrame.updateOutLabel(face);
//String currLblContent = CalculatorJFrame.lblOut.getText();
//CalculatorJFrame.lblOut.setText(currLblContent + face); //update the output label on the main container
}
}
package gui_calc;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class NumButtonsJP extends JPanel implements ActionListener {
JButton numButtons[];
public NumButtonsJP() {
setLayout(new GridLayout(4, 3));
numButtons = new JButton[10];
for (int i = 1; i < 10; i++) {
//create a JButton with the number on its face and add it to the array of JButtons
numButtons[i] = new JButton("" + i);
numButtons[i].addActionListener(this); //make the button trigger the event
//add the JButton to the JPanel
add(numButtons[i]);
}
JLabel spaceHolder = new JLabel(); //create the spaceHolder as a blank label
add(spaceHolder); //add the spaceHolder to the JPanel
numButtons[0] = new JButton("0"); //create the Zero button
numButtons[0].addActionListener(this);//make the Zero button trigger actioNPerformed
add(numButtons[0]); //add the Zero button to the JPanel
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String face = e.getActionCommand();
System.out.println(face + " was clicked");
int num = Integer.parseInt(face.trim()); // parse to an int so we can use in math
CalculatorJFrame.updateOutLabel(face);
//String currLblContent = CalculatorJFrame.lblOut.getText();
//CalculatorJFrame.lblOut.setText(currLblContent + face); //update the output label on the main container
}
}
I change a little your code, basically I'm adding an evaluator of expressions.
The UI basically construct the expression and pass to your getResultFromQuestion() function which takes the input and then try to parse to a math function.
You must handle the exceptions properly, and it brokes your BinaryOperators since you could entry two of more operands.
#Override
public void actionPerformed(ActionEvent e) {
String face = e.getActionCommand().trim();
switch (face) {
case "=":
// do math... get the values... and reset the label with the result
updateOutLabel("=" + getResultFromQuestion(lblOut.getText()));
break;
case "C":
clearOutLabel();
break;
}
}
private String getResultFromQuestion(String text) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(text);
} catch (ScriptException e) {
//Do something with the exception
}
return result.toString();
}

implementing actionListener with multiple classes?

I'm creating a program for my Java class and I'm having a hard time implementing a actionListener in conjunction to my main class.
This is an example of my main class, I am using other classes to create the components for the tabs. Where I'm running into trouble is when I try to implement action listeners in the other class. I keep running into errors regarding abstract classes. This is probably a simple solution, but I'm still fairly new to programming.
'
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import javax.swing.plaf.ColorUIResource;
public class TaikunStudyResource extends JFrame {
private static final int FRAME_WIDTH = 700;
private static final int FRAME_HIEGHT = 500;
private JPanel searchTab,addTab, grammerTab,testTab,homeTab;
public static void main(String[] args)throws UnsupportedOperationException {
TaikunStudyResource tsr = new TaikunStudyResource();
tsr.setVisible(true);
}
public TaikunStudyResource(){
//set basic features
setTitle("Taikun-Japanese Study Resource!");
setSize(FRAME_WIDTH,FRAME_HIEGHT);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(new Color(226,199,255));
addComponents(getContentPane());
}
public void addComponents(Container contentPane){
//add overlaying panel
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
contentPane.add(topPanel);
//create tabs
contentPane.add(createTabs());
}
public JTabbedPane createTabs(){
//UIManager.put("TabbedPane.contentAreaColor",ColorUIResource.getHSBColor(153,153,255));
//create tabs
JTabbedPane tabs = new JTabbedPane();
SearchPanel sp = new SearchPanel();
tabs.addTab("Search", sp);
addPanel ap = new addPanel();
tabs.addTab("Add",ap);
return tabs;
}
}
'
Here is a example of my my addPanel class
'
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
/**
*
* #author tyler.stanley.4937
*/
public abstract class addPanel extends JPanel{
//variables
private JPanel mainPanel, eastPanel,westPanel, checkboxPanel, radioPanel, typePanel, adjectivePanel, verbPanel, kanjiPanel;
private JLabel kanaKanjiLabel, romanjiLabel;
private JTextField kanaKanjiField, romanjiField,exampleInput, defInput, tagInput;
private JButton radicalButton, addDefButton, addExampleButton, addButton, addTagButton
,clearexButton,clearDefButton,clearTagButton;
private ButtonGroup commonGroup;
private JRadioButton[] commonButton;
private String[] commonTypeArray = {"very-common", "common", "Uncommon", "Out-dated"};
private JCheckBox[] typeCheckBox;
private String[] typeofWordArray = {"Noun", "Pronoun", "Verb","Adjective","Idiom"};
private JComboBox adjectiveTypeCombo;
private String[] adjectivetypeArray ={"Na","i"};
private JComboBox verbTypeCombo;
//private String[] verbTypetext = {"Suru","Kuru","da","desu","iku","-masu"};//these may not make it
private String[] verbTypeArray ={"-u","-ku","-gu","-su","-tsu","-nu","-bu","-mu","-ru"};
private JTextArea definitionArea, exampleArea, tagArea;
private List<String>definitionList, exampleList, tagList, radicalList,typeList;
private String kanjiKana,romanji;
private ActionListener a;
public static void main(String[] arg)throws UnsupportedOperationException{
}
public addPanel(){
setLayout(new BorderLayout());
//setBackground(Color.blue);
addComponents();
}
public void addComponents(){
fillSouthPanel();
fillEastPanel();
}
}
public void fillEastPanel(){
eastPanel = new JPanel(new BorderLayout());
//add definition pane
JPanel definitionPanel = new JPanel(new FlowLayout());
definitionPanel.setBorder(BorderFactory.createTitledBorder("Defintion"));
definitionArea = new JTextArea();
definitionArea.setColumns(22);
definitionArea.setRows(8);
definitionArea.setBorder(BorderFactory.createLineBorder(Color.black));
definitionArea.setEditable(false);
//add scroll pane
JScrollPane scrollPane = new JScrollPane(definitionArea);
scrollPane.setSize(200,135);
definitionPanel.add(scrollPane);
//add input and button
defInput = new JTextField(50);
definitionPanel.add(defInput);
addDefButton = new JButton("Add");
definitionPanel.add(addDefButton);
//addDefButton.addActionListener(al);
clearDefButton = new JButton("Clear");
definitionPanel.add(clearDefButton);
//clearDefButton.addActionListener(al);
//add tags
JPanel tagPanel = new JPanel(new FlowLayout());
tagPanel.setBorder(BorderFactory.createTitledBorder("Tags"));
tagArea = new JTextArea();
tagArea.setColumns(22);
tagArea.setRows(1);
tagArea.setBorder(BorderFactory.createLineBorder(Color.black));
tagArea.setEditable(false);
JScrollPane tagScrollPane = new JScrollPane(tagArea);
tagScrollPane.setSize(200,133);
tagPanel.add(tagScrollPane);
tagInput = new JTextField(22);
tagPanel.add(tagInput);
addTagButton = new JButton("Add Tag");
clearTagButton = new JButton("Clear Tag");
tagPanel.add(addTagButton);
tagPanel.add(clearTagButton);
//clearTagButton.addActionListener(al);
//addTagButton.addActionListener(al);
//examples
JPanel examplePanel = new JPanel(new FlowLayout());
examplePanel.setBorder(BorderFactory.createTitledBorder("example"));
exampleArea = new JTextArea();
exampleArea.setColumns(22);
exampleArea.setRows(8);
exampleArea.setBorder(BorderFactory.createLineBorder(Color.black));
exampleArea.setEditable(false);
JScrollPane exampleScrollPane = new JScrollPane(exampleArea);
exampleScrollPane.setSize(200,135);
examplePanel.add(exampleScrollPane);
exampleInput = new JTextField(30);
examplePanel.add(exampleInput);
addExampleButton = new JButton("Add");
examplePanel.add(addExampleButton);
//addExampleButton.addActionListener(this);
JButton clearExampleButton = new JButton("Clear");
examplePanel.add(clearExampleButton);
//clearExampleButton.addActionListener(this);
add(eastPanel, BorderLayout.EAST);
}
public void fillSouthPanel(){
JPanel southPanel = new JPanel(new FlowLayout());
addButton = new JButton("Add");
southPanel.add(addButton);
addButton.addActionListener(new Action() {
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
add(southPanel, BorderLayout.SOUTH);
}
public void addEntry(int buttonNumber){
switch(buttonNumber){
case 1:
tagList.add(tagInput.getText());
tagArea.append("/n"+tagInput.getText());
break;
case 2:
exampleList.add(exampleInput.getText());
exampleArea.append("/n"+exampleInput.getText());
break;
case 3:
definitionList.add(defInput.getText());
definitionArea.append("/n"+defInput.getText());
break;
}
}
public void clearEntry(int buttonNumber){
switch(buttonNumber){
case 0:
case 1:
case 2:
}
}
//public List radicalList(){
//RadicalFrame rf = new RadicalFrame();
//List<String>radicalList = rf.getRadicals();
//return
//}
public boolean getFieldEntries(){
boolean romaji,kanji, passable;
if(kanaKanjiField.getText()!= null){
kanjiKana = kanaKanjiField.getText();
kanji = true;
}else{
JOptionPane.showMessageDialog(null, "Please entry a vaild Japanese word");
kanaKanjiField.setText(null);
kanji = false;
}
//test if it's english
if(romanjiField.getText() !=null){
romanji = romanjiField.getText();
romaji = true;
}else{
JOptionPane.showMessageDialog(null, "please enter a vaild romaji entry");
romanjiField.setText(null);
romaji = false;
}
if(romaji == true && kanji == true){
passable =true;
}else{
passable = false;
}
return passable;
}
public boolean getTextArea(){
boolean defText, exText, tagText,passable;
if(tagList.size()!=0){
tagText = true;
}else{
JOptionPane.showMessageDialog(null, "Please enter tags to indentify the word");
tagText = false;
}
if(definitionList.size()!=0){
defText = true;
}else{
JOptionPane.showMessageDialog(null,"Please Enter defintion of the word");
defText = false;
}
if(exampleList.size()!=0){
exText = true;
}else{
JOptionPane.showMessageDialog(null, "Please Enter an Example of the word usage");
exText = false;
}
if(exText == true&&defText== true&& tagText == true){
passable = true;
}else{
passable = false;
}
return passable;
}
public void addWord() throws FileNotFoundException, IOException{
boolean vaild = getFieldEntries();
boolean vaild2 = getTextArea();
if(vaild == true&& vaild2 == true){
//Word word = new Word(KanjiKanaEntry, RomanjiEntry, CommonIndex, radicalList,typeentry, adjectiveIndex,VerbIndex);
File outFile = new File("dictionary.dat","UTF-8");
//Writer unicodeFileWriter = new OutputStreamWriter( new FileOutputStream("dictionary.dat)."UTF-8");//can't use writer
//fileOutputStream("dictionary.dat"),"UTF-8");
FileOutputStream outFileStream = new FileOutputStream(outFile,true);
ObjectOutputStream oos = new ObjectOutputStream(outFileStream);//append to a file
//oos.WriteObject(word);//store word
}
}
public void actionPermored(ActionEvent event) throws FileNotFoundException, IOException{
System.out.println("action");
//get even source
if(event.getSource() instanceof JButton){
JButton clickedButton = (JButton)event.getSource();
if(clickedButton == radicalButton){
//radicalList = radicalFrame();
}else if(clickedButton ==addButton){
addWord();
}else if(clickedButton == addTagButton){
addEntry(1);
}else if(clickedButton == addExampleButton){
addEntry(2);
}else if(clickedButton == addDefButton){
addEntry(3);
}else if(clickedButton == clearTagButton){
clearEntry(1);
}else if(clickedButton == clearDefButton){
clearEntry(0);
}else if(clickedButton == clearexButton){
clearEntry(2);
}
}
//get combo box entries
if(event.getSource() instanceof JComboBox){
JComboBox selectedComboBox = (JComboBox)event.getSource();
if(selectedComboBox == adjectiveTypeCombo){
int adjectiveform = selectedComboBox.getSelectedIndex();
}else if(selectedComboBox == verbTypeCombo){
int VerbForm = selectedComboBox.getSelectedIndex();
}
if(event.getSource() instanceof JCheckBox){
for(int i = 0;i<typeCheckBox.length;i++){
if(typeCheckBox[i].isSelected()){
typeList.add(typeCheckBox[i].getText()); //some how assign index numbers
}
}
}
}
}
}'
This is just a piece of code, so sorry if it seems a little jumbled, I'm trying to condense it as much as possible.
I've tried to create a internal class to handle the action listener, but I can't seem to get it to work. Also I know I can create actionlisteners for every button, but I would like to condense all the actionevents to one class or method.
The errors are due to unimplemented methods of the Action class anonymous instance.
Any instance of the Action interface requires that all the its methods be implemented. However using Action as an anonymous instance if neither practical or good practice. Rather create a single concrete instance of a class that extends AbstractAction and set the Action for for each component.
button.setAction(mySingleAction);
where
class SingleAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
// do stuff
}
}

Java guessing game

I am trying to write a program in Java that takes a random number from 1-1000 and then as the guess it the background color changes to blue(cold) or red(warm) if they are in the number. I am new to java GUI, but I think the rest of the logic is right, not sure. It compiles, but the guess button doesn't work. Any guidance will be appreciated.
package guessGame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.color.*;
import java.util.Random;
import java.util.Random;
import java.util.logging.FileHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class GuessGame extends JFrame
{
private JFrame mainFrame;
private JButton GuessButton;
private JButton QuitButton;
private JLabel prompt1, prompt2;
private JTextField userInput;
private JLabel comment = new JLabel("What is your destiny?");
private JLabel comment2 = new JLabel (" ");
//private int number, guessCount;
//private int lastGuess;
private int randomNumber;
private Color background;
public GuessGame()
{
mainFrame = new JFrame ("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
GuessButton = new JButton("Guess");
QuitButton = new JButton("Quit");
prompt1 = new JLabel("I have a number between 1 and 1000.");
prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
comment = new JLabel ("What is your destiny?");
comment2 = new JLabel (" ");
userInput = new JTextField(5);
//userInput.addActionListener(new GuessHandler());
//content pane
Container c = mainFrame.getContentPane();
c.setLayout(new FlowLayout());
//adding component to the pane
c.add(prompt1);
c.add(prompt2);
c.add(userInput);
c.add(comment2);
c.add(GuessButton);
c.add(QuitButton);
c.add(comment);
GuessButton.setMnemonic('G');
QuitButton.setMnemonic('Q');
mainFrame.setSize(300,200);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
// define and register window event handler
// mainFrame.addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e)
// { System.exit(0); }
// });
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
GuessButton.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
QuitButton.addActionListener(qhandler);
}
public void paint (Graphics g)
{
super.paint(g);
setBackground(background);
}
class QuitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int getUserInput=0;
int diff;
int Difference;
randomNumber = new Random().nextInt(1001);
try {
getUserInput = Integer.parseInt(
userInput.getText().trim());
} catch (NumberFormatException ex){
comment.setText("Enter a VALID number!");
return;
}
if (getUserInput == randomNumber){
JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber,
JOptionPane.INFORMATION_MESSAGE);
randomNumber = new Random().nextInt(1000) + 1;
return;
}
if (getUserInput > randomNumber){
comment.setText( "Too High. Try a lower number." );
diff=getUserInput - randomNumber;
Difference=Math.abs(diff);
} else {
comment.setText( "Too Low. Try a higher number." );
diff=randomNumber - getUserInput;
Difference=Math.abs(diff);
}
if(Difference<=25){
comment2.setText("Cold");
setBackgroundColor(Color.blue);
}
if(Difference<=10){
comment2.setText("Warm");
setBackgroundColor(Color.red);
}
else {
}
}
private void setBackgroundColor(Color color) {
setBackgroundColor(color);
}
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
The colors aren't changing because your setBackgroundColor always uses Color.black. Change it to:
private void setBackgroundColor(Color color) {
setBackground(color);
}
As for the number always being zero. You do not instantiate the randomNumber field. Add this to your constructor:
randomNumber = new Random().nextInt(1001);
Another problem I noticed was you added a window listener to ensure the program exits when you close the window. This is implemented in JFrame. In the constructor add:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Instead of using the deprecated method:
mainFrame.show();
use the not deprecated:
mainFrame.setVisible(true);
Furthermore you have a field, which is never queried:
private Color background;
It's best to do the logic before connecting it to the gui. It's a lot easier to test and find the worst bugs.
Refactored code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessGame extends JFrame {
private JTextField userInput;
private JLabel comment = new JLabel("What is your destiny?");
private JLabel comment2 = new JLabel(" ");
private int randomNumber;
public GuessGame() {
super("Guessing Game!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates components
JButton guessButton = new JButton("Guess");
JButton quitButton = new JButton("Quit");
JLabel prompt1 = new JLabel("I have a number between 1 and 1000.");
JLabel prompt2 = new JLabel("Can you guess my number? Enter your Guess:");
comment = new JLabel("What is your destiny?");
comment2 = new JLabel(" ");
userInput = new JTextField(5);
//content pane
Container c = getContentPane();
setLayout(new FlowLayout());
//adding component to the pane
c.add(prompt1);
c.add(prompt2);
c.add(userInput);
c.add(comment2);
c.add(guessButton);
c.add(quitButton);
c.add(comment);
guessButton.setMnemonic('G');
quitButton.setMnemonic('Q');
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
initializeNumber();
//creating the handler
GuessButtonHandler ghandler = new GuessButtonHandler(); //instantiate new object
guessButton.addActionListener(ghandler); // add event listener
QuitButtonHandler qhandler = new QuitButtonHandler();
quitButton.addActionListener(qhandler);
}
private void initializeNumber() {
randomNumber = new Random().nextInt(1000) + 1;
}
class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class GuessButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int getUserInput;
int diff;
int Difference;
try {
getUserInput = Integer.parseInt(userInput.getText().trim());
if (getUserInput == randomNumber) {
JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber,
JOptionPane.INFORMATION_MESSAGE);
initializeNumber();
return;
}
if (getUserInput > randomNumber) {
comment.setText("Too High. Try a lower number.");
diff = getUserInput - randomNumber;
Difference = Math.abs(diff);
} else {
comment.setText("Too Low. Try a higher number.");
diff = randomNumber - getUserInput;
Difference = Math.abs(diff);
}
if (Difference <= 25) {
comment2.setText("Cold");
GuessGame.this.setBackgroundColor(Color.blue);
}
if (Difference <= 10) {
comment2.setText("Warm");
GuessGame.this.setBackgroundColor(Color.red);
}
} catch (NumberFormatException ex) {
comment.setText("Enter a VALID number!");
}
}
}
private void setBackgroundColor(Color color) {
getContentPane().setBackground(color);
}
public static void main(String args[]) {
//instantiate gueesgame object
GuessGame app = new GuessGame();
}
}
You have more Swing components than you need, and you seem to be adding one set to the frame while manipulating another set. For example, you have two JTextFields, fieldBox and userInput. You add userInput to the frame, but check fieldBox for input in the Guess button handler. Since fieldBox is always empty, the NumberFormatException is caught by your exception handler (which should really just catch NumberFormatException, not Exception), and comment is updated with "Enter a VALID number!". However, just like with the double text area, comment isn't actually added to the frame, prompt1 and prompt2 are, so you can't see the change
I would write your logic without a UI first and test it until it was 100% correct. Just use a command line, text UI at first. Once that's done, put a GUI in front of it. It'll help to isolate your problems: once the text-driven logic is right, you'll know that future problems are due to UI.
It makes your MVC separation cleaner as well.

Categories