java GUI JLabel - java

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).

Related

How do I get a variable collected from a JTextField and give it to a getter method?

Very new to using Java and spent hours looking for a solution, but I cannot find out how to get the input collected by a JTextField with a button and ActionListener then be used for a getter method that can receive idNum so I can use the input in another class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Staff extends JFrame implements ActionListener {
private staffBooking staffBooking = new staffBooking();
String weekArray[] = { "Week1", "Week2" };
String dayArray[] = { "Monday" , "Tuesday", "Wednesday", "Thursday", "Friday" };
JPanel panel = new JPanel();
JLabel weekLabel = new JLabel("Week: ", SwingConstants.RIGHT);
JLabel dayLabel = new JLabel("Day: ", SwingConstants.RIGHT);
JLabel idLabel = new JLabel("ID: ", SwingConstants.RIGHT);
static JTextField id = new JTextField("",2);
JComboBox weekDrop = new JComboBox(weekArray);
JComboBox dayDrop = new JComboBox(dayArray);
JButton button = new JButton("Submit");
private static int idNum;
public Staff() {
setTitle("Staff");
setSize(250,250);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4, 2));
add(weekLabel);
add(weekDrop);
add(dayLabel);
add(dayDrop);
add(idLabel);
add(id);
add(panel);
add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(id.getText().equals("")==false) {
if (e.getSource() == button) {
staffBooking.setEnabled(true);
staffBooking.setVisible(true);
idNum = Integer.parseInt(id.getText());
}
}
}
});
}
public static int getID() {
return idNum;
}
}
I believe what you are trying to do is something like this:
import javax.swing.*;
import javax.swing.SwingConstants;
public class Staff extends JFrame /*implements ActionListener*/ {
private final JPanel panel = new JPanel();
private final JLabel idLabel = new JLabel("ID: ", SwingConstants.RIGHT);
private final JTextField id = new JTextField("",5);
private final JButton button = new JButton("Submit");
private int idNum;
public Staff() {
StaffBooking staffBooking = new StaffBooking(this);
setTitle("Staff");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setLocationRelativeTo(null);
panel.add(idLabel);
panel.add(id);
panel.add(button);
add(panel);
button.addActionListener(e -> {
if(! id.getText().isEmpty()) {
idNum = Integer.parseInt(id.getText());
staffBooking.setVisible(true);
}
});
pack();
setVisible(true);
}
public int getID() {
return idNum;
}
public static void main(String[] args) {
new Staff();
}
}
class StaffBooking extends JDialog {
public StaffBooking(Staff staff) {
JPanel panel = new JPanel();
JLabel idLabel = new JLabel(" ");
JButton button = new JButton("Show ID");
button.addActionListener(e -> {
idLabel.setText(String.valueOf(staff.getID()));
});
panel.add(button);
panel.add(idLabel);
add(panel);
setLocationRelativeTo(null);
pack();
}
}
Using a setter in StaffBooking would be better in this case:
public class Staff extends JFrame /*implements ActionListener*/ {
private final JPanel panel = new JPanel();
private final JLabel idLabel = new JLabel("ID: ", SwingConstants.RIGHT);
private final JTextField id = new JTextField("",5);
private final JButton button = new JButton("Submit");
public Staff() {
StaffBooking staffBooking = new StaffBooking();
setTitle("Staff");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setLocationRelativeTo(null);
panel.add(idLabel);
panel.add(id);
panel.add(button);
add(panel);
button.addActionListener(e -> {
if(! id.getText().isEmpty()) {
int idNum = Integer.parseInt(id.getText());
staffBooking.setID(idNum);
staffBooking.setVisible(true);
}
});
pack();
setVisible(true);
}
public static void main(String[] args) {
new Staff();
}
}
class StaffBooking extends JDialog {
private int idNum;
public StaffBooking() {
JPanel panel = new JPanel();
JLabel idLabel = new JLabel(" ");
JButton button = new JButton("Show ID");
button.addActionListener(e -> {
idLabel.setText(String.valueOf(idNum));
});
panel.add(button);
panel.add(idLabel);
add(panel);
setLocationRelativeTo(null);
pack();
}
public void setID(int idNum) {
this.idNum = idNum;
}
}
A further improvement oof the structure can be achieved by using a model class, shared between Staff and StaffBooking:
public class Staff extends JFrame /*implements ActionListener*/ {
private final JPanel panel = new JPanel();
private final JLabel idLabel = new JLabel("ID: ", SwingConstants.RIGHT);
private final JTextField id = new JTextField("",5);
private final JButton button = new JButton("Submit");
public Staff() {
Model model = new Model();
StaffBooking staffBooking = new StaffBooking(model);
setTitle("Staff");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setLocationRelativeTo(null);
panel.add(idLabel);
panel.add(id);
panel.add(button);
add(panel);
button.addActionListener(e -> {
if(! id.getText().isEmpty()) {
int idNum = Integer.parseInt(id.getText());
model.setID(idNum);
staffBooking.setVisible(true);
}
});
pack();
setVisible(true);
}
public static void main(String[] args) {
new Staff();
}
}
class StaffBooking extends JDialog {
public StaffBooking(Model model) {
JPanel panel = new JPanel();
JLabel idLabel = new JLabel(" ");
JButton button = new JButton("Show ID");
button.addActionListener(e -> {
idLabel.setText(String.valueOf(model.getID()));
});
panel.add(button);
panel.add(idLabel);
add(panel);
setLocationRelativeTo(null);
pack();
}
}
class Model{
private int idNum;
public int getID() {
return idNum;
}
public void setID(int idNum) {
this.idNum = idNum;
}
}

JLabel not appearing in JPanel

I made a JFrame with JTextField, JPanel and a button in which the user inputs a value and after clicking the button, it will generate multiple labels based on the users input, but the JLabel doesnt appear. am i doing it wrong?
this is the coding for the button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String s = jTextField1.getText();
int noSub = Integer.valueOf(s);
addData(noSub);
}
and this is the method to add JLabel.
public void addData(int a){
jPanel1.removeAll();
int num = a;
JLabel jLabel[] = new JLabel[num];
for(int i=0;i<num;i++){
jLabel[i]=new JLabel();
jLabel[i] = new JLabel("Label "+i);
jPanel1.add(jLabel[i]);
jPanel1.revalidate();
jPanel1.repaint();
}
jPanel1.updateUI();
}
Made a simple working example here:
public class Sample extends JFrame{
private JTextField inputField;
private JPanel outputPanel;
private Sample() {
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel form = new JPanel(new GridBagLayout());
inputField = new JTextField(3);
JButton submitBtn = new JButton("Enter");
form.add(inputField);
form.add(submitBtn);
mainPanel.add(form, BorderLayout.NORTH);
outputPanel = new JPanel();
mainPanel.add(outputPanel);
submitBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = inputField.getText();
int noSub = Integer.valueOf(text);
addData(noSub);
}
void addData(int data){
outputPanel.removeAll();
JLabel jLabel[] = new JLabel[data];
for(int i=0;i<data;i++){
jLabel[i] = new JLabel("Label "+i);
outputPanel.add(jLabel[i]);
}
outputPanel.revalidate();
outputPanel.repaint();
// No need to call outputPanel.updateUI()
}
});
setSize(400,500);
add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Sample();
}
}

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();
}
}

Using an ActionListener to output results of calculations with Geometric Calculator

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();
}
});
}
}

Java UI, trying to go to next page upon clicking button

I have a simple GUI with 3 radio buttons and a button. I want the user to select a radio option, then upon clicking the button the user will be directed to a different Java UI depending upon which radio button they selected. Here is my method:
private void btnContinueActionPerformed(java.awt.event.ActionEvent evt)
{
if(rbCSV.isSelected())
{
}
else if(rbExcel.isSelected())
{
}
else if(rbDatabase.isSelected())
{
}
else
{
}
}
I am new to Java Swing, and not sure of the syntax that will allow me to direct the user to the next page. Sort of like a Wizard, I guess. Any help would be awesome! Thanks!
Recommendations:
Read the How to Use Radio Buttons tutorial
Read the How to Use CardLayout tutorial
Learn how to use a ButtonGroup, since you'll only want one button to be selected at a time
public final class RadioButtonDemo {
private static CardPanel cards;
private static Card cardOne;
private static Card cardTwo;
private static Card cardThree;
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("RB Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
cards = new CardPanel();
frame.getContentPane().add(cards);
frame.getContentPane().add(new ControlPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createCards(){
cardOne = new Card(
"Card 1",
new JLabel("This is card one"),
Color.PINK);
cardTwo = new Card(
"Card 2",
new JLabel("This is card two"),
Color.YELLOW);
cardThree = new Card(
"Card 3",
new JLabel("This is card three"),
Color.CYAN);
}
private static final class Card extends JPanel{
private final String name;
public Card(
final String name,
final JComponent component,
final Color c){
super();
this.name = name;
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setBackground(c);
add(component);
}
public final String getName(){
return name;
}
}
private static final class CardPanel extends JPanel{
public CardPanel(){
super(new CardLayout());
createCards();
add(cardOne, cardOne.getName());
add(cardTwo, cardTwo.getName());
add(cardThree, cardThree.getName());
}
}
private static final class ControlPanel extends JPanel{
private static JRadioButton showCardOneButton;
private static JRadioButton showCardTwoButton;
private static JRadioButton showCardThreeButton;
private static JButton showButton;
public ControlPanel(){
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(createJRadioButtonPanel());
add(createJButtonPanel());
}
private final JPanel createJRadioButtonPanel(){
final JPanel panel = new JPanel();
showCardOneButton = new JRadioButton(cardOne.getName());
showCardOneButton.setSelected(true);
showCardTwoButton = new JRadioButton(cardTwo.getName());
showCardThreeButton = new JRadioButton(cardThree.getName());
ButtonGroup group = new ButtonGroup();
group.add(showCardOneButton);
group.add(showCardTwoButton);
group.add(showCardThreeButton);
panel.add(showCardOneButton);
panel.add(showCardTwoButton);
panel.add(showCardThreeButton);
return panel;
}
private final JPanel createJButtonPanel(){
final JPanel panel = new JPanel();
showButton = new JButton("Show");
showButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
CardLayout cl = (CardLayout) cards.getLayout();
if(showCardOneButton.isSelected()){
cl.show(cards, showCardOneButton.getText());
}
else if(showCardTwoButton.isSelected()){
cl.show(cards, showCardTwoButton.getText());
}
else if(showCardThreeButton.isSelected()){
cl.show(cards, showCardThreeButton.getText());
}
}
});
panel.add(showButton);
return panel;
}
}
}
JPanel panelCSV, panelExcel, panelDatabase;
CardLayout cardLayout = new CardLayout();
JPanel pagePanel = new JPanel(cardLayout);
pagePanel.add(panelCSV, "CSV");
pagePanel.add(panelExcel, "Excel");
pagePanel.add(panelDatabase, "Database");
public void btnContinueActionPerformed(ActionEvent e) {
if ( rbCSV.isSelected() ) {
cardLayout.show(pagePanel, "CSV");
} else if ( rbExcel.isSelected() ) {
cardLayout.show(pagePanel, "Excel");
} else if ( rbDatabase.isSelected() ) {
cardLayout.show(pagePanel, "Database");
} else {
// ....
}
}

Categories

Resources