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();
}
}
Related
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());
}
}
I need a little help on java temperature conversion GUI
so here is my code for result
public class ResultsPanel extends JPanel
{
private JLabel result;
private JPanel panel;
final int WIDTH_CONST=120;
final int HEIGHT_CONST=60;
public ResultsPanel()
{
setPreferredSize(new Dimension(WIDTH_CONST, HEIGHT_CONST));
setBorder(BorderFactory.createTitledBorder("Result"));
result = new JLabel();
add(result);
}
public void setResultLabel(String str)
{
result.setText(str);
}
public void setResultLabel()
{
result.setText("");
}
}
so what I'm trying to do is, that when i click on the convert button i want to label the result
and here is my button handler class:
private class ConvertButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//calculate and convert temperatures
//convert the temperature into String
ResultsPanel result = new ResultsPanel();
String temp; // temperature in string
result.setResultLabel(temp);
}
}
but it doesn't seem like it's printing out the result,
any help appreciated, thanks
update :
here is my tempGUI class:
public class TempGUI extends JFrame
{
private BannerPanel banner;
private TypePanel type;
private TemperaturePanel temperature;
private ResultsPanel results;
private JPanel buttonPanel;
private JButton convert;
private JButton clear;
private JButton exit;
public TempGUI()
{
setTitle("Temperature Concverter GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
banner = new BannerPanel();
type = new TypePanel();
temperature = new TemperaturePanel();
results = new ResultsPanel();
buildButtonPanel();
add(banner, BorderLayout.NORTH);
add(type, BorderLayout.WEST);
add(temperature, BorderLayout.CENTER);
add(results, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void buildButtonPanel()
{
buttonPanel = new JPanel();
convert = new JButton("Convert");
clear = new JButton("Clear");
exit = new JButton("Exit");
convert.addActionListener(new ConvertButtonHandler());
clear.addActionListener(new ClearButtonHandler());
exit.addActionListener(new ExitButtonHandler());
buttonPanel.add(convert);
buttonPanel.add(clear);
buttonPanel.add(exit);
}
private class ConvertButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
double celsius = 0, fahrenheit = 0;
DecimalFormat decimalFormatter = new DecimalFormat("0,00");
TypePanel type = new TypePanel();
TemperaturePanel temp = new TemperaturePanel();
ResultsPanel result = new ResultsPanel();
String temp1 = "Test";
result.setResultLabel(temp1);
add(result);
}
}
private class ClearButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
ResultsPanel results = new ResultsPanel();
results.setResultLabel();
TemperaturePanel temp = new TemperaturePanel();
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
You're creating the ResultsPanel but you're not adding it to any frame. Thus, the ResultsPanel is not displayed. You will have to create a frame for the ResultsPanel or add it to an existing frame like this yourFrame.add(result).
I am in the process of building a Geometric Calculator, but am having difficult implementing the ActionListener. I found some sample code on the Oracle site and modified to fit the visual concept I am trying to do.
I combed through my code looking for typos and incorrect punctuation and either corrected it or did not find anything that stuck out to me. I looked at similar questions on Stack Overflow and in text books, and my code looks similar in structure to what is being done in the examples. I have pasted the relevant section of the code below.
Eclipse gives me this error message: Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
CalcButtonListenerA cannot be resolved to a type I don't understand why this is happening. I thought these lines would take care of resolving the type:
`calcButton1 = new JButton("Calculate");
calcButton1.addActionListener(new CalcButtonListenerA());`
The other relevant code is below...
package layout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GeometryCalculator implements ItemListener {
JPanel calcTools;
final static String CIRCLEPANEL = "Circle Calculator";
final static String RECTANGLEPANEL = "Rectangle Calculator";
final static String TRIANGLEPANEL = "Triangle Calculator";
private JLabel messageLabel1;
private JLabel messageLabel2;
private JLabel messageLabel3;
private JLabel radiusLabel;
private JLabel baseLabel;
private JLabel heightLabel;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel circleAreaLabel;
private JLabel circumferenceLabel;
private JLabel rectanglePerimeterLabel;
private JLabel rectangleAreaLabel;
private JLabel triangleAreaLabel;
private JTextField choiceTextField;
private JTextField radiusTextField;
private JTextField baseTextField;
private JTextField heightTextField;
private JTextField lengthTextField;
private JTextField widthTextField;
private JButton calcButton1;
private JButton calcButton2;
private JButton calcButton3;
JTextField rectanglePerimeterField = new JTextField(15);
JTextField rectangleAreaField = new JTextField(15);
JTextField triangleAreaField = new JTextField(15);
public void addComponentToPane(Container pane) {
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = { CIRCLEPANEL, RECTANGLEPANEL, TRIANGLEPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
//Create the "calcTools".
JPanel calcTool1 = new JPanel();
radiusLabel = new JLabel("Radius");
circumferenceLabel = new JLabel("Circumference");
circleAreaLabel = new JLabel("Area");
radiusTextField= new JTextField(10);
messageLabel1 = new JLabel("Let's make some circle calculations.");
final JTextField circumferenceField = new JTextField(15);
circumferenceField.setEditable(false);
final JTextField circleAreaField = new JTextField(15);
circleAreaField.setEditable(false);
calcButton1 = new JButton("Calculate");
calcButton1.addActionListener(new CalcButtonListenerA());
calcTool1.add(messageLabel1);
calcTool1.add(radiusLabel);
calcTool1.add(radiusTextField);
calcTool1.add(circumferenceLabel);
calcTool1.add(circumferenceField);
calcTool1.add(circleAreaLabel);
calcTool1.add(circleAreaField);
calcTool1.add(calcButton1);
class CalcButtonListenerA implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String radius;
double circumference;
double circleArea;
radius = radiusTextField.getText();
circumference = 2*Double.parseDouble(radius)*Math.PI;
String circ = String.valueOf(circumference);
circleArea = Double.parseDouble(radius)* Double.parseDouble(radius)*Math.PI;
String area = String.valueOf(circleArea);
circumferenceField.setText(circ);
circleAreaField.setText(area);
}
}
JPanel calcTool2 = new JPanel();
messageLabel2 = new JLabel("Let's make some rectangle calculations.");
lengthLabel = new JLabel("Length");
widthLabel = new JLabel("Width");
lengthTextField = new JTextField(10);
widthTextField = new JTextField(10);
rectanglePerimeterLabel = new JLabel("Perimeter");
rectangleAreaLabel = new JLabel("Area");
JTextField rectanglePerimeterField = new JTextField(15);
rectanglePerimeterField.setEditable(false);
JTextField rectangleAreaField = new JTextField(15);
rectangleAreaField.setEditable(false);
JButton calcButton2 = new JButton("Calculate");
calcTool2.add(messageLabel2);
calcTool2.add(lengthLabel);
calcTool2.add(lengthTextField);
calcTool2.add(widthLabel);
calcTool2.add(widthTextField);
calcTool2.add(rectanglePerimeterLabel);
calcTool2.add(rectanglePerimeterField);
calcTool2.add(rectangleAreaLabel);
calcTool2.add(rectangleAreaField);
calcTool2.add(calcButton2);
JPanel calcTool3 = new JPanel();
messageLabel3 = new JLabel("Let's make some triangle calculations");
baseLabel = new JLabel("Base");
heightLabel = new JLabel("Height");
baseTextField = new JTextField(10);
heightTextField = new JTextField(10);
triangleAreaLabel = new JLabel("Area");
triangleAreaField = new JTextField(15);
triangleAreaField.setEditable(false);
JButton calcButton3 = new JButton("calculate");
calcTool3.add(messageLabel3);
calcTool3.add(baseLabel);
calcTool3.add(baseTextField);
calcTool3.add(heightLabel);
calcTool3.add(heightTextField);
calcTool3.add(triangleAreaLabel);
calcTool3.add(triangleAreaField);
calcTool3.add(calcButton3);
calcTools = new JPanel(new CardLayout());
calcTools.add(calcTool1, CIRCLEPANEL);
calcTools.add(calcTool2, RECTANGLEPANEL);
calcTools.add(calcTool3, TRIANGLEPANEL);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(calcTools, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(calcTools.getLayout());
cl.show(calcTools, (String)evt.getItem());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Geometry Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GeometryCalculator demo = new GeometryCalculator();
demo.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
UIManager.put("swing.boldMetal", Boolean.FALSE);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The compile error simply says that at that point the compiler does not know what CalcButtonListenerA means. You define the class CalcButtonListenerA inside the method addComponentToPane however the definition is placed after the usage so at that moment the class is not yet defined, this is somewhat equivalent to what would happen with a variable, you can't do the following:
int y = x + 5; //what is x?
int x = 10; //even if it's defined below, compiler error
You can do this properly in a few ways:
Define it in the method, as a "local class" but before the usage:
public void addComponentToPane(Container pane) {
class CalcButtonListenerA implements ActionListener
{
//...
}
//...
calcButton1.addActionListener(new CalcButtonListenerA());
}
Define it in the class GeometryCalculator not in the method:
public class GeometryCalculator implements ItemListener {
public void addComponentToPane(Container pane) {
//...
calcButton1.addActionListener(new CalcButtonListenerA());
}
private class CalcButtonListenerA implements ActionListener
{
//...
}
}
Define it as an anonymous class, this is a compact way to do it if you don't want to use that code in any other actionListener.
public void addComponentToPane(Container pane) {
//...
calcButton1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//the actionPerformed code of CalcButtonListenerA
}
});
}
If it was a very important class you could also place it in its own file and import it here.
Don't define a method inside a method.
Use an anonymous class like this (much cleaner) :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GeometryCalculator implements ItemListener {
JPanel calcTools;
final static String CIRCLEPANEL = "Circle Calculator";
final static String RECTANGLEPANEL = "Rectangle Calculator";
final static String TRIANGLEPANEL = "Triangle Calculator";
private JLabel messageLabel1;
private JLabel messageLabel2;
private JLabel messageLabel3;
private JLabel radiusLabel;
private JLabel baseLabel;
private JLabel heightLabel;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel circleAreaLabel;
private JLabel circumferenceLabel;
private JLabel rectanglePerimeterLabel;
private JLabel rectangleAreaLabel;
private JLabel triangleAreaLabel;
private JTextField choiceTextField;
private JTextField radiusTextField;
private JTextField baseTextField;
private JTextField heightTextField;
private JTextField lengthTextField;
private JTextField widthTextField;
private JButton calcButton1;
private JButton calcButton2;
private JButton calcButton3;
JTextField rectanglePerimeterField = new JTextField(15);
JTextField rectangleAreaField = new JTextField(15);
JTextField triangleAreaField = new JTextField(15);
public void addComponentToPane(Container pane) {
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = { CIRCLEPANEL, RECTANGLEPANEL, TRIANGLEPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
//Create the "calcTools".
JPanel calcTool1 = new JPanel();
radiusLabel = new JLabel("Radius");
circumferenceLabel = new JLabel("Circumference");
circleAreaLabel = new JLabel("Area");
radiusTextField= new JTextField(10);
messageLabel1 = new JLabel("Let's make some circle calculations.");
final JTextField circumferenceField = new JTextField(15);
circumferenceField.setEditable(false);
final JTextField circleAreaField = new JTextField(15);
circleAreaField.setEditable(false);
calcButton1 = new JButton("Calculate");
calcButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String radius;
double circumference;
double circleArea;
radius = radiusTextField.getText();
circumference = 2*Double.parseDouble(radius)*Math.PI;
String circ = String.valueOf(circumference);
circleArea = Double.parseDouble(radius)* Double.parseDouble(radius)*Math.PI;
String area = String.valueOf(circleArea);
circumferenceField.setText(circ);
circleAreaField.setText(area);
}
});
// class CalcButtonListenerA implements ActionListener
// {
//
// public void actionPerformed(ActionEvent e)
// {
// String radius;
// double circumference;
// double circleArea;
//
// radius = radiusTextField.getText();
// circumference = 2*Double.parseDouble(radius)*Math.PI;
// String circ = String.valueOf(circumference);
// circleArea = Double.parseDouble(radius)* Double.parseDouble(radius)*Math.PI;
// String area = String.valueOf(circleArea);
//
// circumferenceField.setText(circ);
// circleAreaField.setText(area);
//
// }
// }
calcTool1.add(messageLabel1);
calcTool1.add(radiusLabel);
calcTool1.add(radiusTextField);
calcTool1.add(circumferenceLabel);
calcTool1.add(circumferenceField);
calcTool1.add(circleAreaLabel);
calcTool1.add(circleAreaField);
calcTool1.add(calcButton1);
JPanel calcTool2 = new JPanel();
messageLabel2 = new JLabel("Let's make some rectangle calculations.");
lengthLabel = new JLabel("Length");
widthLabel = new JLabel("Width");
lengthTextField = new JTextField(10);
widthTextField = new JTextField(10);
rectanglePerimeterLabel = new JLabel("Perimeter");
rectangleAreaLabel = new JLabel("Area");
JTextField rectanglePerimeterField = new JTextField(15);
rectanglePerimeterField.setEditable(false);
JTextField rectangleAreaField = new JTextField(15);
rectangleAreaField.setEditable(false);
JButton calcButton2 = new JButton("Calculate");
calcTool2.add(messageLabel2);
calcTool2.add(lengthLabel);
calcTool2.add(lengthTextField);
calcTool2.add(widthLabel);
calcTool2.add(widthTextField);
calcTool2.add(rectanglePerimeterLabel);
calcTool2.add(rectanglePerimeterField);
calcTool2.add(rectangleAreaLabel);
calcTool2.add(rectangleAreaField);
calcTool2.add(calcButton2);
JPanel calcTool3 = new JPanel();
messageLabel3 = new JLabel("Let's make some triangle calculations");
baseLabel = new JLabel("Base");
heightLabel = new JLabel("Height");
baseTextField = new JTextField(10);
heightTextField = new JTextField(10);
triangleAreaLabel = new JLabel("Area");
triangleAreaField = new JTextField(15);
triangleAreaField.setEditable(false);
JButton calcButton3 = new JButton("calculate");
calcTool3.add(messageLabel3);
calcTool3.add(baseLabel);
calcTool3.add(baseTextField);
calcTool3.add(heightLabel);
calcTool3.add(heightTextField);
calcTool3.add(triangleAreaLabel);
calcTool3.add(triangleAreaField);
calcTool3.add(calcButton3);
calcTools = new JPanel(new CardLayout());
calcTools.add(calcTool1, CIRCLEPANEL);
calcTools.add(calcTool2, RECTANGLEPANEL);
calcTools.add(calcTool3, TRIANGLEPANEL);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(calcTools, BorderLayout.CENTER);
}
// class CalcButtonListenerA implements ActionListener
// {
//
// public void actionPerformed(ActionEvent e)
// {
// String radius;
// double circumference;
// double circleArea;
//
// radius = radiusTextField.getText();
// circumference = 2*Double.parseDouble(radius)*Math.PI;
// String circ = String.valueOf(circumference);
// circleArea = Double.parseDouble(radius)* Double.parseDouble(radius)*Math.PI;
// String area = String.valueOf(circleArea);
//
// circumferenceField.setText(circ);
// circleAreaField.setText(area);
//
// }
// }
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(calcTools.getLayout());
cl.show(calcTools, (String)evt.getItem());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Geometry Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GeometryCalculator demo = new GeometryCalculator();
demo.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
UIManager.put("swing.boldMetal", Boolean.FALSE);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
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!
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)