Missing something to finish my program - java

Im working on my palindrome program and implementing it into a JFrame. Im stuck on how to display the result in the resultTF in the CalculateButtonHandler scope. any help would be appreciated.
Heres my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Exercise5 extends JFrame
{
private static final int Width = 400;
private static final int Height = 200;
private JLabel wordJL,resultJL;
private JTextField wordTF,resultTF;
private JButton checkJB,exitJB;
private CalculateButtonHandler checkHandler;
private ExitButtonHandler exitB;
public Exercise5()
{
setTitle ("Palindrome");
wordJL = new JLabel ("Enter a word: ", SwingConstants.RIGHT);
resultJL = new JLabel ("Result: ", SwingConstants.RIGHT);
wordTF = new JTextField(10);
resultTF = new JTextField(10);
checkJB = new JButton ("Calculate");
checkHandler = new CalculateButtonHandler();
exitJB = new JButton ("Exit");
exitB = new ExitButtonHandler();
exitJB.addActionListener (exitB);
Container pane = getContentPane();
pane.setLayout (new GridLayout (3,2));
pane.add(wordJL);
pane.add(wordTF);
pane.add(checkJB);
pane.add(exitJB);
pane.add(resultJL);
pane.add(resultTF);
setSize(Width, Height);
setVisible (true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
if(e.getSource().equals(checkJB)) {
String pal1, pal2="";
pal1 = wordTF.getText();
int length = pal1.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
pal2 = pal2 + pal1.charAt(i);
}
if (pal1.equals(pal2))
resultTF.setText("True");
else
resultTF.setText("False");
}
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
public static void main (String[] args){
Exercise5 rectObject = new Exercise5();
}
}

you haven't added checkHandler as the action listener of checkJB.. try:
checkJB = new JButton ("Calculate");
checkHandler = new CalculateButtonHandler();
checkJB.addActionListener(checkHandler); //THIS LINE!

Related

Switching between different panels in Java to create a GUI interface

I'm trying to write a program to convert Celsius to Fahrenheit or Fahrenheit Celsius based on the users choice (all GUI using AWT and Swing).
How to allow one method to change the visibility of the others in order to change what part of the program is visible?
Below is my code because my exact issue is difficult to explain:
package javapp1;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
/**
*
* #author logan
*/
public class FahrenheitToCelsius extends JFrame
{
private JPanel startPanel;
private JPanel fahrenheitToCelsiusPanel;
private JPanel celsiusToFahrenheitPanel;
private JLabel decideLabel;
private JLabel FahrenheitToCelsiusLabel;
private JLabel CelsiusToFahrenheitLabel;
private JTextField FahrenheitToCelsiusText;
private JTextField CelsiusToFahrenheitText;
private JButton fahrenheitButton;
private JButton celsiusButton;
private JButton calcButton;
private JButton exitButton;
private JButton backButton;
private final int WINDOW_WIDTH = 400;
private final int WINDOW_HEIGHT = 100;
public FahrenheitToCelsius()
{
setTitle("Fahrenheit/Celsius Conversion");
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildStartPanel();
add(startPanel);
}
private void buildStartPanel()
{
decideLabel = new JLabel("Would you like to convert from Celsius or Fahrenheit?");
fahrenheitButton = new JButton("Fahrenheit");
fahrenheitButton.addActionListener(new FahrenheitToCelsiusListener());
celsiusButton = new JButton("Celsius");
celsiusButton.addActionListener(new CelsiusToFahrenheitListener());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ExitButtonListener());
startPanel = new JPanel();
startPanel.add(decideLabel);
startPanel.add(fahrenheitButton);
startPanel.add(celsiusButton);
setVisible(true);
}
private void buildFahrenheitToCelsiusPanel()
{
FahrenheitToCelsiusLabel = new JLabel("Enter the degrees Fahrenheit");
FahrenheitToCelsiusText = new JTextField(10);
calcButton = new JButton("Calculate");
calcButton.addActionListener(new CalculateFtoC());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ExitButtonListener());
backButton = new JButton("Back");
backButton.addActionListener(new BackButtonListener());
fahrenheitToCelsiusPanel = new JPanel();
fahrenheitToCelsiusPanel.add(FahrenheitToCelsiusLabel);
fahrenheitToCelsiusPanel.add(FahrenheitToCelsiusText);
fahrenheitToCelsiusPanel.add(calcButton);
fahrenheitToCelsiusPanel.add(exitButton);
}
private void buildCelsiusToFahrenheitPanel()
{
CelsiusToFahrenheitLabel = new JLabel("Enter the degree Celsius");
CelsiusToFahrenheitText = new JTextField(10);
calcButton = new JButton("Calculate");
calcButton.addActionListener(new CalculateCtoF());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ExitButtonListener());
backButton = new JButton("Back");
backButton.addActionListener(new BackButtonListener());
celsiusToFahrenheitPanel = new JPanel();
celsiusToFahrenheitPanel.add(CelsiusToFahrenheitLabel);
celsiusToFahrenheitPanel.add(CelsiusToFahrenheitText);
celsiusToFahrenheitPanel.add(calcButton);
celsiusToFahrenheitPanel.add(exitButton);
}
private class FahrenheitToCelsiusListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
startPanel.setVisible(false);
celsiusToFahrenheitPanel.setVisible(false);
buildFahrenheitToCelsiusPanel();
}
}
private class CelsiusToFahrenheitListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
startPanel.setVisible(false);
fahrenheitToCelsiusPanel.setVisible(false);
buildCelsiusToFahrenheitPanel();
}
}
private class ExitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
private class BackButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
fahrenheitToCelsiusPanel.setVisible(false);
celsiusToFahrenheitPanel.setVisible(false);
buildStartPanel();
}
}
private class CalculateFtoC implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String input;
int celsius;
int fahrenheit;
input = FahrenheitToCelsiusText.getText();
fahrenheit = Integer.parseInt(input);
celsius = ((fahrenheit-32)*(5/9));
JOptionPane.showMessageDialog(null, fahrenheit+" degrees fahrenheit is "+celsius+" degrees celsius.");
}
}
private class CalculateCtoF implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String input;
int celsius;
int fahrenheit;
input = CelsiusToFahrenheitText.getText();
celsius = Integer.parseInt(input);
fahrenheit = ((celsius*(9/32))+32);
JOptionPane.showMessageDialog(null, celsius+" degrees celsius is "+fahrenheit+" degrees fahrenheit.");
}
}
public static void main(String[] args)
{
new FahrenheitToCelsius();
}
}

How to use single ActionListener for JCheckBox and JTextField

I am writing an eJuice Calculator. Its nowhere near finished as you will see below. My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
This is a rough draft of code.
package ejuicecalculatorv2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EJuiceCalculatorV2 extends JFrame {
//Form Controls
private JCheckBox isPGbasedNic_CB = new JCheckBox("PG Based NIC");
private JCheckBox isPGbasedFlavor_CB = new JCheckBox("PG Based Flavor");
private JCheckBox isVGbasedNic_CB = new JCheckBox("VG Based NIC");
private JCheckBox isVGbasedFlavor_CB = new JCheckBox("VG Based Flavor");
private JTextField batchSize_TF = new JTextField(5);
private JLabel batchSize_LB = new JLabel("Batch Size:");
private JTextField baseNicStrength_TF = new JTextField(5);
private JLabel baseNicStrength_LB = new JLabel("Base NIC Strength:");
private JTextField targetNicStrength_TF = new JTextField(5);
private JLabel targetNicStrength_LB = new JLabel("Target NIC Strength:");
private JTextField totalNic_TF = new JTextField(5);
private JLabel totalNic_LB = new JLabel("Total NIC:");
private JTextField flavorStrength_TF = new JTextField(5);
private JLabel flavorStrength_LB = new JLabel("Flavoring Strength:");
private JTextField totalFlavor_TF = new JTextField(5);
private JLabel totalFlavor_LB = new JLabel("Total Flavoring:");
private JTextField vgRatio_TF = new JTextField(5);
private JLabel vgRatio_LB = new JLabel("VG Ratio:");
private JTextField pgRatio_TF = new JTextField(5);
private JLabel pgRatio_LB = new JLabel("PG Ratio:");
private JTextField additionalVG_TF = new JTextField(5);
private JLabel additionalVG_LB = new JLabel("Additional VG:");
private JTextField additionalPG_TF = new JTextField(5);
private JLabel additionalPG_LB = new JLabel("Additional PG:");
private JTextField totalVG_TF = new JTextField(5);
private JLabel totalVG_LB = new JLabel("Total VG:");
private JTextField totalPG_TF = new JTextField(5);
private JLabel totalPG_LB = new JLabel("Total PG:");
private JTextField vgBasedIng_TF = new JTextField(5);
private JLabel vgBasedIng_LB = new JLabel("Total VG Ingredients:");
private JTextField pgBasedIng_TF = new JTextField(5);
private JLabel pgBasedIng_LB = new JLabel("Total PG Ingredients:");
//Variables
private boolean _PGnicFlag;
private boolean _VGnicFlag;
private boolean _PGflavorFlag;
private boolean _VGflavorFlag;
private double baseNic;
private double targetNic;
private double totalNic;
private double flavorStrength;
private double totalFlavor;
private double batchSize;
private double totalPG;
private double totalVG;
private double additionalVG;
private double additionalPG;
private double pgBasedIng;
private double vgBasedIng;
private double pgRatio;
private double vgRatio;
public EJuiceCalculatorV2() {
super("EJuice Calculator V2");
setLayout(new FlowLayout());
//Add CheckBoxes
add(isPGbasedNic_CB);
add(isPGbasedFlavor_CB);
add(isVGbasedNic_CB);
add(isVGbasedFlavor_CB);
//Add TextFields and Labels
add(batchSize_LB);
add(batchSize_TF);
add(vgRatio_LB);
add(vgRatio_TF);
add(pgRatio_LB);
add(pgRatio_TF);
add(baseNicStrength_LB);
add(baseNicStrength_TF);
add(targetNicStrength_LB);
add(targetNicStrength_TF);
add(flavorStrength_LB);
add(flavorStrength_TF);
//Add ActionListeners
ActionListener actionListener = new ActionHandler();
isPGbasedNic_CB.addActionListener(actionListener);
isPGbasedFlavor_CB.addActionListener(actionListener);
isVGbasedNic_CB.addActionListener(actionListener);
isVGbasedFlavor_CB.addActionListener(actionListener);
batchSize_TF.addActionListener(actionListener);
vgRatio_TF.addActionListener(actionListener);
pgRatio_TF.addActionListener(actionListener);
baseNicStrength_TF.addActionListener(actionListener);
targetNicStrength_TF.addActionListener(actionListener);
flavorStrength_TF.addActionListener(actionListener);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event){
//if event.getSource() == JCheckBox then execute the following code.
if(checkBox.isSelected()){
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = true;
_VGnicFlag = false;
checkBox = isVGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = true;
_PGnicFlag = false;
checkBox = isPGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = true;
_PGflavorFlag = false;
checkBox = isPGbasedFlavor_CB;
checkBox.setSelected(false);
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = true;
_VGflavorFlag = false;
checkBox = isVGbasedFlavor_CB;
checkBox.setSelected(false);
}
}
else{
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = false;
_VGnicFlag = true;
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = false;
_PGnicFlag = true;
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = false;
_PGflavorFlag = true;
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = false;
_VGflavorFlag = true;
}
}
}
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run (){
new EJuiceCalculatorV2().setVisible(true);
}
});
}
}
My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
You have a bunch of control components, but none appear ones that would initiate an action from the GUI. Rather all of them, the JCheckBoxes and the JTextFields are there to get input, and you appear to be missing one final component, such as a JButton. I would add this component to your GUi, and I would add a single ActionListener to it and it alone. And then when pressed, it would check the state of the check boxes and the text components and then based on their state, give the user the appropriate response.
Also some, if not most or all of the JTextFields, I'd change to either JComboBoxes or JSpinners, to limit the input that the user can enter to something that is allowable since you don't want the user entering "yes" into the "Batch Size" JTextField.
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.JSpinner.DefaultEditor;
#SuppressWarnings("serial")
public class JuiceTwo extends JPanel {
private static final String[] FLAVORS = {"Flavor 1", "Flavor 2", "Flavor 3", "Flavor 4"};
private static final Integer[] ALLOWABLE_BATCH_SIZES = {1, 2, 5, 10, 15, 20};
private static final String[] ALLOWABLE_VG_RATIOS = {"1/4", "1/3", "1/2", "1/1", "2/1", "3/1", "4/1", "8/1", "16/1"};
private List<JCheckBox> flavorBoxes = new ArrayList<>();
private JComboBox<Integer> batchSizeCombo;
private JSpinner vgRatioSpinner;
public JuiceTwo() {
// JPanel to hold the flavor JCheckBoxes
JPanel flavorPanel = new JPanel(new GridLayout(0, 1)); // hold them in vertical grid
flavorPanel.setBorder(BorderFactory.createTitledBorder("Flavors"));
for (String flavor : FLAVORS) {
JCheckBox flavorBox = new JCheckBox(flavor);
flavorBox.setActionCommand(flavor);
flavorPanel.add(flavorBox);
flavorBoxes.add(flavorBox);
}
batchSizeCombo = new JComboBox<>(ALLOWABLE_BATCH_SIZES);
SpinnerListModel vgRatioModel = new SpinnerListModel(ALLOWABLE_VG_RATIOS);
vgRatioSpinner = new JSpinner(vgRatioModel);
JComponent editor = vgRatioSpinner.getEditor();
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setColumns(4);
}
JButton getSelectionButton = new JButton("Get Selection");
getSelectionButton.setMnemonic(KeyEvent.VK_S);
getSelectionButton.addActionListener(new SelectionActionListener());
add(flavorPanel);
add(Box.createHorizontalStrut(20));
add(new JLabel("Batch Size:"));
add(batchSizeCombo);
add(Box.createHorizontalStrut(20));
add(new JLabel("VG Ratio:"));
add(vgRatioSpinner);
add(Box.createHorizontalStrut(20));
add(getSelectionButton);
}
private class SelectionActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox flavorBox : flavorBoxes) {
System.out.printf("%s selected: %b%n", flavorBox.getActionCommand(), flavorBox.isSelected());
}
System.out.println("Batch Size: " + batchSizeCombo.getSelectedItem());
System.out.println("VG Ration: " + vgRatioSpinner.getValue());
System.out.println();
}
}
private static void createAndShowGui() {
JuiceTwo mainPanel = new JuiceTwo();
JFrame frame = new JFrame("JuiceTwo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Java Multidemensional Array Loop that inputs data with Button Action

Questions I am pulling my hair out over.
How do I get the array to add data to current index, then increment to the next index to add changed JTextField data for the next button press. currently I'm overwriting the same index.
I have tried to figure out actionlisteners for the button "Submit" that uses a counter with nesting of the loop. played with ideas from question 23331198 and 3010840 and 17829577 many others as a reference but didn't really get it to far. Most searches pull up info on managing buttons with arrays and creating button arrays so I assume I'm not using the correct wording to search with. I have read a few places that an MD array is not the best option to use.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
int arrayIndex = 0;
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < tutArray.length; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
textArea.append("\n");
textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
This is what I was looking for thanks for the help!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
int arrayIndex = 0;
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
textArea.setText("");
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < arrayIndex; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
// textArea.append("\n");
//textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
You can add the index as a field in your main object:
protected int index;
in your actionPerformed you increase index:
index++;
NOTE:
But why do you extend from JFrame AND use the field mainFrame?
you can use
this.setSize(800,800);
this.add(mainPanel);
Please declare (because of extends JFrame):
private static final long serialVersionUID = 1L;
Please start the name of an object with a lower case letter:
JButton exit = new JButton("Quit");

GUI: action listener compiler-error

I cannot seem to make the Exit Button work and thus my program does not compile. If I comment out everything related to the exit button the program works and functions properly. All other buttons work. What is wrong with my Exit Button?
/**
* Write a description of class Converterr here.
*
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
public class Converterr
{
private JLabel usdL, pesosL, eurosL;
private JTextField usdTF, pesosTF, eurosTF;
private JButton pesosB, eurosB, exitB;
PesosButtonHandler pbHandler;
EurosButtonHandler eubHandler;
ExitButtonHandler ebHandler;
public void driver()
{
JFrame c = new JFrame ("Currency Converter");
c.setSize(400,300);
c.setDefaultCloseOperation(c.EXIT_ON_CLOSE);
//Content Pane
Container cp = c.getContentPane ( );
cp.setLayout ( new GridLayout (5,2) );
pesosL = new JLabel ("Pesos: ", SwingConstants.RIGHT);
usdL = new JLabel ("USD: ", SwingConstants.RIGHT);
eurosL = new JLabel ("Euros: ", SwingConstants.RIGHT);
usdTF = new JTextField(8);
pesosTF = new JTextField(8);
eurosTF = new JTextField(8);
pesosTF.setEditable(false);
eurosTF.setEditable(false);
pesosB = new JButton ("Convert to Pesos");
eurosB = new JButton ("Convert to Euros");
exitB = new JButton ("Exit");
// add to content pane container
cp.add(usdL);
cp.add(usdTF);
cp.add(pesosL);
cp.add(pesosTF);
cp.add(eurosL);
cp.add(eurosTF);
cp.add(pesosB);
cp.add(eurosB);
cp.add(exitB);
c.setVisible(true);
//Instantiate Listeners
pbHandler = new PesosButtonHandler();
eubHandler = new EurosButtonHandler();
ebHandler = new ExitButtonHandler();
pesosB.addActionListener(pbHandler);
eurosB.addActionListener(eubHandler);
exitB.addActionListener(ebHandler);
}
//action listener interfaces
private class PesosButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
double inusd;
double outpesos;
inusd = Double.parseDouble(usdTF.getText() );
outpesos = inusd * 12.31;
pesosTF.setText(Double.toString(outpesos));
}
}
private class EurosButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
double inusd, outeuros;
inusd = Double.parseDouble(usdTF.getText() );
outeuros = inusd * .78;
eurosTF.setText(Double.toString(outeuros));
}
}
private class ExitButtonHandler implements ActionListener
{
public void ActionPerformed (ActionEvent e)
{
System.exit(0);
}
}
public static void main (String [ ] args)
{
Converterr conv = new Converterr();
conv.driver();
}
}
Error Message:
Converterr.ExitButtonHandler is not abstract and does not override
abstract method actionPerformed(java.awt.event.ActionEnvt) in java.awt.event.ActionListener
public void ActionPerformed (ActionEvent e)
You have a typo in the method name. It should be:
public void actionPerformed (ActionEvent e)

Can anyone tell me why my change QTY button isnt changing the QTY?

Can anyone tell me why my change QTY button isnt changing the QTY?
The buttonlistener2 is supposed to change the number of items in arrayCount[x]
to the number in the count JTextfield, but its not, could use a new set of eyes.
thanks all
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ProduceInventory extends JFrame
{
ArrayList<String> arrayName = new ArrayList<String>();
ArrayList<Integer> arrayCount = new ArrayList<Integer>();
// declares panels and items
private final int WINDOW_WIDTH = 450;
private final int WINDOW_HEIGHT = 350;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JLabel messageLabel1;
private JLabel messageLabel2;
private JTextField name;
private JTextField count;
private JTextArea output;
private JButton add;
private JButton changeQTY;
private JButton delete;
private JButton clear;
private JButton report;
private JButton save;
private JButton load;
public ProduceInventory()
{
//creates Jframe
setTitle("Produce Inventory");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1(); //build panels
panel2();
panel3();
add(panel1, BorderLayout.NORTH); //add panels
add(panel2, BorderLayout.SOUTH);
add(panel3, BorderLayout.CENTER);
setVisible(true);
}
private void panel1() //builds panel 1
{
messageLabel1 = new JLabel("Name");
messageLabel2 = new JLabel("Count");
name = new JTextField(20);
count = new JTextField(5);
panel1 = new JPanel();
panel1.add(messageLabel1);
panel1.add(name);
panel1.add(messageLabel2);
panel1.add(count);
}
private void panel2() //builds panel 2
{
add = new JButton("Add");
changeQTY = new JButton("CHANGE QTY");
delete = new JButton("Delete");
clear = new JButton("Clear");
report = new JButton("Report");
save = new JButton("Save File");
load = new JButton("Load File");
add.addActionListener(new ButtonListener());
changeQTY.addActionListener(new ButtonListener2());
panel2 = new JPanel();
panel2.setLayout(new GridLayout(2,4));
panel2.add(add);
panel2.add(changeQTY);
panel2.add(delete);
panel2.add(clear);
panel2.add(report);
panel2.add(save);
panel2.add(load);
}
private void panel3() //builds panel 3
{
output = new JTextArea(10,30);
panel3 = new JPanel();
panel3.add(output);
}
private class ButtonListener implements ActionListener //add listener
{
String nameIn;
String countIn;
int number;
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
nameIn = name.getText();
arrayName.add(name.getText());
countIn = count.getText();
number = Integer.parseInt(countIn);
arrayCount.add(number);
output.setText(name.getText() + " " + count.getText() + " Item Added");
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
private class ButtonListener2 implements ActionListener //add listener
{
public void actionPerformed(ActionEvent e)
{
String nameIn;
String countIn;
int number;
String actionCommand = e.getActionCommand();
if (actionCommand.equals("CHANGE QTY"))
{
nameIn = name.getText();
countIn = count.getText();
number = Integer.parseInt(countIn);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
if(arrayName.get(x) == nameIn)
{
arrayCount.set(x, number);
}
}
output.setText("Qty is updated to: " + number);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ProduceInventory(); //runs program
}
}
In the action listener, on the line
if(arrayName.get(x) == nameIn)
you are checking if the two variables refer to the same object. Instead of that you have to check if the objects they refer to are equal:
if(nameIn.equals(arrayName.get(x)))

Categories

Resources