I am making a panel project that calls three panels. Panel one holds all information and the other two panels are panels that open up when I press a button. How it works is I call the first panel, press a button, second panel opens. Then in the second panel I plug in a password. If it is correct, a third panel will open. I need to call values from the first panel into the third panel. I know how to use constructors, accessors and mutators, but the values I need are generated in an event when I press a button. I am trying to figure out how to call those values from the event into the third panel. Essentially, the values are counters, sub-total, tax, and total for all transactions of the duration of the program. Here is my code.
Main Class:
import javax.swing.*;
public class AppleRegister {
public static void main(String[] args)
{
double subTotalp2 = 0, taxP2 = 0, realTotalp2 = 0;
JFrame frame = new JFrame("Apple Crazy Cola Cash (Apple IIC) Register");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AppleRegisterPanel panel = new AppleRegisterPanel
(subTotalp2, taxP2, realTotalp2);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
First Panel:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class AppleRegisterPanel extends JPanel
{
private JButton button1, button2, button3, button4, button5, button6;
private JLabel label1, label2, label3, label4, label5, label6, label7;
private JTextField text, text1, text2, text3, text4, text5, text6, text7, text8;
private JTextArea area ;
private JPanel panel, panel2, panel3, panel4;
private int counter, counter2, counter3, counter4, counterp21, counterp22,
counterp23, counterp24;
private String string;
private final double MD_TAX = 0.06;
private double subTotal, realTotal, tax, subTotalp2, realTotalp2, taxP2;
private double num100, num50, num20, num10, num5, num1, num25cents, num10cents,
num5cents, num1cents;
public AppleRegisterPanel(double subTotalp2, double taxP2, double realTotalp2)
{
this.subTotalp2 = subTotalp2;
this.taxP2 = taxP2;
this.realTotalp2 = realTotalp2;
setLayout(new BorderLayout());
text = new JTextField(10);
text1 = new JTextField(5);
text2 = new JTextField(5);
text3 = new JTextField(5);
text4 = new JTextField(5);
text5 = new JTextField(10);
text6 = new JTextField(10);
text7 = new JTextField(10);
text8 = new JTextField(10);
area = new JTextArea();
button1 = new JButton("Child");
button2 = new JButton("Medium");
button3 = new JButton("Large");
button4 = new JButton("Ex Large");
button5 = new JButton("Close Out Register");
button6 = new JButton("Complete Transaction");
panel = new JPanel();
panel.setPreferredSize(new Dimension(240,250));
panel.setBackground(Color.cyan);
add(panel, BorderLayout.WEST);
panel.add(button1);
button1.addActionListener(new TempListener2());
panel.add(text1);
panel.add(Box.createRigidArea(new Dimension(0,20)));
panel.add(button2);
button2.addActionListener(new TempListener2());
panel.add(text2);
panel.add(Box.createRigidArea(new Dimension(0,20)));
panel.add(button3);
button3.addActionListener(new TempListener2());
panel.add(text3);
panel.add(Box.createRigidArea(new Dimension(0,20)));
panel.add(button4);
button4.addActionListener(new TempListener2());
panel.add(text4);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel2 = new JPanel();
label6 = new JLabel("Change");
panel2.setPreferredSize(new Dimension(270,250));
panel2.setBackground(Color.cyan);
add(panel2, BorderLayout.EAST);
panel2.add(button5);
button5.addActionListener(new TempListener());
panel2.add(label6);
panel2.add(area);
panel2.add(button6);
button6.addActionListener(new TempListener1());
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
panel3 = new JPanel();
label1 = new JLabel("Apple Crazy Cola Cash (Apple IIC) Register ");
label7 = new JLabel(" By Robert Burns");
panel3.setPreferredSize(new Dimension(50,50));
panel3.setBackground(Color.cyan);
add(panel3, BorderLayout.NORTH);
panel3.add(label1);
panel3.add(label7);
panel4 = new JPanel();
label1 = new JLabel("Sub-Total");
label2 = new JLabel("Tax");
label3 = new JLabel("Total");
label4 = new JLabel("Payment");
label5 = new JLabel("Change Owed");
panel4.setPreferredSize(new Dimension(140,250));
panel4.setBackground(Color.cyan);
add(panel4, BorderLayout.CENTER);
panel4.add(label1);
panel4.add(text);
panel4.add(label2);
panel4.add(text5);
panel4.add(label3);
panel4.add(text6);
panel4.add(label4);
panel4.add(text7);
text7.addActionListener(new TempListener3());
panel4.add(label5);
panel4.add(text8);
}
private class TempListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == button5)
{
JFrame frame3 = new JFrame("Apple Crazy Cola Cash (Apple
IIC) Register");
frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AppleRegisterPanel3 panel = new AppleRegisterPanel3();
frame3.getContentPane().add(panel);
frame3.pack();
frame3.setVisible(true);
}
}
}
private class TempListener1 implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == button6)
{
counter = 0;
text1.setText(Integer.toString(counter));
counter2 = 0;
text2.setText(Integer.toString(counter2));
counter3 = 0;
text3.setText(Integer.toString(counter3));
counter4 = 0;
text4.setText(Integer.toString(counter4));
subTotal = 0;
text.setText(Double.toString(subTotal));
tax = 0;
text5.setText(Double.toString(tax));
realTotal = 0;
text6.setText(Double.toString(realTotal));
text7.setText("");
text8.setText("");
}
}
}
private class TempListener2 implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
DecimalFormat df = new DecimalFormat("#.##");
if (event.getSource() == button1)
{
counter++;
string = text1.getText();
text1.setText(Integer.toString(counter));
subTotal += counter * 0.90;
string = text.getText();
text.setText(df.format(subTotal));
tax += subTotal * MD_TAX;
string = text5.getText();
text5.setText(df.format(tax));
realTotal += subTotal + tax;
string = text6.getText();
text6.setText(df.format(realTotal));
counterp21++;
subTotalp2 += counterp21 * 0.90;
taxP2 += subTotalp2 * MD_TAX;
realTotalp2 += subTotalp2 * taxP2;
}
if (event.getSource() == button2)
{
counter2++;
string = text2.getText();
text2.setText(Integer.toString(counter2));
subTotal += counter2 * 1.40;
string = text.getText();
text.setText(df.format(subTotal));
tax += subTotal * MD_TAX;
string = text5.getText();
text5.setText(df.format(tax));
realTotal += subTotal + tax;
string = text6.getText();
text6.setText(df.format(realTotal));
counterp22++;
subTotalp2 += counterp22 * 1.40;
taxP2 += subTotalp2 * MD_TAX;
realTotalp2 += subTotalp2 * taxP2;
}
if (event.getSource() == button3)
{
counter3++;
string = text3.getText();
text3.setText(Integer.toString(counter3));
subTotal += counter3 * 1.75;
string = text.getText();
text.setText(df.format(subTotal));
tax += subTotal * MD_TAX;
string = text5.getText();
text5.setText(df.format(tax));
realTotal += subTotal + tax;
string = text6.getText();
text6.setText(df.format(realTotal));
counterp23++;
subTotalp2 += counterp23 * 1.75;
taxP2 += subTotalp2 * MD_TAX;
realTotalp2 += subTotalp2 * taxP2;
}
if (event.getSource() == button4)
{
counter4++;
string = text4.getText();
text4.setText(Integer.toString(counter4));
subTotal += counter4 * 2.00;
string = text.getText();
text.setText(df.format(subTotal));
tax += subTotal * MD_TAX;
string = text5.getText();
text5.setText(df.format(tax));
realTotal += subTotal + tax;
string = text6.getText();
text6.setText(df.format(realTotal));
counterp24++;
subTotalp2 += counterp24 * 2.00;
taxP2 += subTotalp2 * MD_TAX;
realTotalp2 += subTotalp2 * taxP2;
}
}
}
If you scroll down to TempListner2 and see the variables subTotalp2, taxP2, realTotalp2; those are the variables I need to carry over. You'll see that I made the constructor have those variables in it so I can call the methods over in the third panel, but no dice. Comes up 0.0 when I open the third panel. Not sure if it is because it is in a void event or not. I'll post part of the third panel here where I am trying to call the constructor from the first panel and inset the values into the third.
Third Panel:
public AppleRegisterPanel2()
{
AppleRegisterPanel p = new AppleRegisterPanel(subTotalp2, taxP2,
realTotalp2);
this.subTotalp2 = subTotalp2;
this.taxP2 = taxP2;
this.realTotalp2 = realTotalp2;
subTotalp2 = p.getSubTotal();
taxP2 = p.getTax();
realTotalp2 = p.getTotal();
You'll see here that I am trying a weird ass way to call the values.
One problem is that you're opening another JFrame from a JFrame, when you should instead be displaying a modal JDialog. The reason for this is that you cannot advance your program until the user enters the appropriate information, and so the 2nd window should be modal which will prevent interaction with the underlying window until the dialog window has been completely dealt with. If you do this, and place your JPanel into a modal JDialog, then you can easily query the results from the 2nd JPanel because you will know in your code exactly when it's been dealt with -- your main GUI code resumes exactly from where you set the modal dialog visible.
For example:
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WindowCommunication {
private static void createAndShowUI() {
JFrame frame = new JFrame("WindowCommunication");
frame.getContentPane().add(new MyFramePanel());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// let's be sure to start Swing on the Swing event thread
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyFramePanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton openDialogeBtn = new JButton("Open Dialog");
// here my main gui has a reference to the JDialog and to the
// MyDialogPanel which is displayed in the JDialog
private MyDialogPanel dialogPanel = new MyDialogPanel();
private JDialog dialog;
public MyFramePanel() {
openDialogeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openTableAction();
}
});
field.setEditable(false);
field.setFocusable(false);
add(field);
add(openDialogeBtn);
}
private void openTableAction() {
// lazy creation of the JDialog
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
// this line starts *after* the modal dialog has been disposed
// **** here's the key where I get the String from JTextField in the GUI held
// by the JDialog and put it into this GUI's JTextField.
field.setText(dialogPanel.getFieldText());
}
}
class MyDialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton okButton = new JButton("OK");
public MyDialogPanel() {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonAction();
}
});
add(field);
add(okButton);
}
// to allow outside classes to get the text held by the JTextField
public String getFieldText() {
return field.getText();
}
// This button's action is simply to dispose of the JDialog.
private void okButtonAction() {
// win is here the JDialog that holds this JPanel, but it could be a JFrame or
// any other top-level container that is holding this JPanel
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
win.dispose();
}
}
}
Related
I have spent many hours digging around the web and cannot seem to find a straightforward answer or method to add a dropdown selection into my main panel that houses the various text fields, in this case, I am trying to add a paint color selection to the panel so that color can then be used as a variable in determining cost.
The closest I have come so far is having a combo box popup in a new window but then was unable to retrieve the selection.
package paintestimator;
import java.lang.String;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.PopupMenu;
import javax.swing.JComboBox;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PaintEstimator extends JFrame
{
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
//Josh
public PaintEstimator()
{
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
JButton ChoiceA = new JButton("Paint Color");
//JComboBox vendorBTN = (new JComboBox());
ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
//box to show chosen color
//mainPanel.add(new JLabel("Color Chosen"));
// mainPanel.add(sColor);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add( new JLabel("Select a Color"));
mainPanel.add (ChoiceA);
// mainPanel.add(sColor);
// Select<String> select = new Select<>();
//select.setLabel("Sort by");
//select.setItems("Most recent first", "Rating: high to low",
// "Rating: low to high", "Price: high to low", "Price: low to high");
//select.setValue("Most recent first");
// mainPanel.add(select);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
// mainPanel.add(ChoiceA);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
//Josh
class CalcChangeBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n); // still need refine decimal point to #.0
(one decimal place)
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f)
{
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// clear text fields and set focus
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
class ChoiceAListener implements ActionListener
{
public void actionPreformed (ActionEvent e)
{
}
public static void main(String[] args)
{
PaintEstimator window = new PaintEstimator();
window.setVisible(true);
}
}
Below is the combo box I was able to create:
public static void main(String[] args)
{
String[] optionsToChoose =
{
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
JFrame jFrame = new JFrame();
JComboBox<String> jComboBox = new JComboBox<>(optionsToChoose);
jComboBox.setBounds(80, 50, 140, 20);
JButton jButton = new JButton("Done");
jButton.setBounds(100, 100, 90, 20);
JLabel jLabel = new JLabel();
jLabel.setBounds(90, 100, 400, 100);
jFrame.add(jButton);
jFrame.add(jComboBox);
jFrame.add(jLabel);
jFrame.setLayout(null);
jFrame.setSize(350, 250);
jFrame.setVisible(true);
jButton.addActionListener((ActionEvent e) ->
{
String selectedColor = "You selected " +
jComboBox.getItemAt(jComboBox.getSelectedIndex());
jLabel.setText(selectedColor);
});
}
Start by reading through How to Use Combo Boxes (and it wouldn't hurt to look over some the examples)
Start by creating an instance field for the combobox...
public class PaintEstimator extends JFrame {
//...
private JComboBox<String> colorChoice = new JComboBox<>();
//...
Next, create a ComboBoxModel to hold the values you want to present and replace the ChoiceA button with the combobox...
mainPanel.add(new JLabel("Select a Color"));
//mainPanel.add(ChoiceA);
// mainPanel.add(sColor);
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
And then in your ActionListener, get the selected value...
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
Runnable example...
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new PaintEstimator();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintEstimator extends JFrame {
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
private JComboBox<String> colorChoice = new JComboBox<>();
public PaintEstimator() {
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
//ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add(new JLabel("Select a Color"));
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class CalcChangeBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n);
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f) {
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
}
}
There is 3 panels which I created as seen in the image. The first panel is the "From" panel, second is "To" panel, and third is the buttons panel. So the question is, how can I put a new line for the "Enter Temperature: [ ]" so that it will be under neath the radio buttons? I am very new to Java swing/awt please bear with me.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class TemperatureConversion extends JFrame{
// component
JTextField txtFromTemp, txtToTemp;
JLabel lblFromTemp, lblToTemp;
JRadioButton radFromCelsius, radFromFahrenheit, radFromKelvin;
JRadioButton radToCelsius, radToFahrenheit, radToKelvin;
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFromTemp, pnlButton;
ButtonGroup bgFrom, bgTo;
JButton btnConvert, btnExit;
// constructor
public TemperatureConversion(){
super("Temperature");
// assign objects
radFromCelsius = new JRadioButton("Celsius", true);
radFromFahrenheit = new JRadioButton("Fahrenheit");
radFromKelvin = new JRadioButton("Kelvin");
lblFromTemp = new JLabel("Enter Temperature: ");
pnlFromTemp = new JPanel();
btnConvert = new JButton("Convert");
btnExit = new JButton("Exit");
pnlButton = new JPanel();
txtFromTemp = new JTextField(3);
lblToTemp = new JLabel("Comparable Temperature: ");
txtToTemp = new JTextField(3);
// register the button to a listener
btnExit.addActionListener(new MyButtonListener());
btnConvert.addActionListener(new MyButtonListener());
// make the multiple choice exclusive but not a container
bgFrom = new ButtonGroup();
bgFrom.add(radFromCelsius);
bgFrom.add(radFromFahrenheit);
bgFrom.add(radFromKelvin);
// radio buttons
radToCelsius = new JRadioButton("Celsius");
radToFahrenheit = new JRadioButton("Fahrenheit", true);
radToKelvin = new JRadioButton("Kelvin");
// make the multiple choice exclusive
bgTo = new ButtonGroup();
bgTo.add(radToCelsius);
bgTo.add(radToFahrenheit);
bgTo.add(radToKelvin);
pnlFromRadioButton = new JPanel();
pnlToRadioButton = new JPanel();
// decorate the panel
pnlFromRadioButton.setBorder(BorderFactory.createTitledBorder("From"));
pnlToRadioButton.setBorder(BorderFactory.createTitledBorder("To"));
// add radiobutton to panel
pnlFromRadioButton.add(radFromCelsius);
pnlFromRadioButton.add(radFromFahrenheit);
pnlFromRadioButton.add(radFromKelvin);
pnlToRadioButton.add(radToCelsius);
pnlToRadioButton.add(radToFahrenheit);
pnlToRadioButton.add(radToKelvin);
// add button to panel
pnlButton.add(btnConvert);
pnlButton.add(btnExit);
// add label and txt field to panel
pnlFromRadioButton.add(lblFromTemp);
pnlFromRadioButton.add(txtFromTemp);
pnlToRadioButton.add(lblToTemp);
txtToTemp.setEditable(false);
pnlToRadioButton.add(txtToTemp);
// add panels to the frame
add(pnlFromRadioButton, BorderLayout.NORTH);
add(pnlToRadioButton, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
// private inner class to handle button event
private class MyButtonListener implements ActionListener {
// must override actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
if (radFromCelsius.isSelected())
System.out.print("exit");
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
Nest more JPanels and use layout managers
For instance, in the JPanel where you want two lines, give it a BoxLayout oriented along the BoxLayout.PAGE_AXIS, and then add two more JPanels to this BoxLayout-using, a top JPanel with the radio buttons and bottom JPanel with the JLabel and JTextField (or whatever else you want in it).
Side note: this would be a great place to use an enum one called TempScale that had three values: CELSIUS, FAHRENHEIT, KELVIN. You could even give the enum the formulas for conversion to and from Kelvin.
For example:
import java.awt.Component;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class TempConversion2 extends JPanel {
private ToFromPanel fromPanel = new ToFromPanel("From", true);
private ToFromPanel toPanel = new ToFromPanel("To", false);
private ButtonPanel buttonPanel = new ButtonPanel(fromPanel, toPanel);
public TempConversion2() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(fromPanel);
add(toPanel);
add(buttonPanel);
}
private static void createAndShowGui() {
TempConversion2 mainPanel = new TempConversion2();
JFrame frame = new JFrame("Temp Convert");
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());
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel {
public ButtonPanel(ToFromPanel fromPanel, ToFromPanel toPanel) {
add(new JButton(new ConvertAction("Convert", fromPanel, toPanel)));
add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
}
}
#SuppressWarnings("serial")
class ConvertAction extends AbstractAction {
private ToFromPanel fromPanel;
private ToFromPanel toPanel;
public ConvertAction(String name, ToFromPanel fromPanel, ToFromPanel toPanel) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
this.fromPanel = fromPanel;
this.toPanel = toPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
String text = fromPanel.getText();
try {
double fromTemp = Double.parseDouble(text.trim());
TempScale fromScale = fromPanel.getTempScalesPanel().getSelectedTempScale();
double kelvinValue = fromScale.convertToKelvin(fromTemp);
TempScale toScale = toPanel.getTempScalesPanel().getSelectedTempScale();
double toValue = toScale.convertFromKelvin(kelvinValue);
String toValueString = String.format("%.2f", toValue);
toPanel.setText(toValueString);
} catch (NumberFormatException e1) {
Component parentComponent = fromPanel;
String message = "Text must be a valid number: " + text;
String title = "Invalid Text Entered";
int messageType = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(parentComponent, message, title, messageType);
fromPanel.setText("");
}
}
}
#SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
#SuppressWarnings("serial")
class ToFromPanel extends JPanel {
private String title;
private TempScalesPanel tempScalesPanel = new TempScalesPanel();
private JTextField tempTextField = new JTextField(3);
public ToFromPanel(String title, boolean textFieldEnabled) {
this.title = title;
tempTextField.setFocusable(textFieldEnabled);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
bottomPanel.add(new JLabel("Temperature:"));
bottomPanel.add(Box.createHorizontalStrut(8));
bottomPanel.add(tempTextField);
setBorder(BorderFactory.createTitledBorder(title));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(tempScalesPanel);
add(bottomPanel);
}
public String getTitle() {
return title;
}
public TempScalesPanel getTempScalesPanel() {
return tempScalesPanel;
}
public String getText() {
return tempTextField.getText();
}
public void setText(String text) {
tempTextField.setText(text);
}
}
#SuppressWarnings("serial")
class TempScalesPanel extends JPanel {
private ButtonGroup buttonGroup = new ButtonGroup();
private Map<ButtonModel, TempScale> buttonTempMap = new HashMap<>();
public TempScalesPanel() {
for (TempScale tempScale : TempScale.values()) {
JRadioButton radioButton = new JRadioButton(tempScale.getName());
add(radioButton);
buttonGroup.add(radioButton);
buttonTempMap.put(radioButton.getModel(), tempScale);
// set first button as selected by default
if (buttonGroup.getSelection() == null) {
buttonGroup.setSelected(radioButton.getModel(), true);
}
}
}
public TempScale getSelectedTempScale() {
ButtonModel model = buttonGroup.getSelection();
return buttonTempMap.get(model);
}
}
This is the enum that I was talking about. Note that if you change the enum, and for instance add another temperature scale element, the program will automatically include it in the GUI and in the calculations. God I love Java and OOP.
public enum TempScale {
CELSIUS("Celsius", 1.0, -273.15),
FAHRENHEIT("Fahrenheit", 5.0 / 9.0, -459.67),
KELVIN("Kelvin", 1.0, 0.0);
private TempScale(String name, double ratioToKelvin, double absZero) {
this.name = name;
this.ratioToKelvin = ratioToKelvin;
this.absZero = absZero;
}
private String name;
private double ratioToKelvin;
private double absZero;
public String getName() {
return name;
}
public double getRatioToKelvin() {
return ratioToKelvin;
}
public double getAbsZero() {
return absZero;
}
public double convertToKelvin(double value) {
return (value - absZero) * ratioToKelvin;
}
public double convertFromKelvin(double kelvinValue) {
return (kelvinValue / ratioToKelvin) + absZero;
}
}
Always consider posting an MCVE.
For example you layout can be simplified and demonstrated with :
import java.awt.BorderLayout;
import java.awt.Label;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TemperatureConversion extends JFrame{
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFromTemp, pnlButton;
// constructor
public TemperatureConversion(){
pnlFromRadioButton = new JPanel();
pnlFromRadioButton.add(new Label("From Panel"));
pnlToRadioButton = new JPanel();
pnlToRadioButton.add(new Label("To Panel"));
pnlButton = new JPanel();
pnlButton.add(new Label("Buttons Panel"));
// add panels to the frame
add(pnlFromRadioButton, BorderLayout.NORTH);
add(pnlToRadioButton, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
Suppose you want to an "Enter Temperature: [ ]" label to show in a different "line" under From buttons, your constructor will change to :
public TemperatureConversion(){
//set a layout manger. You could use grid layout
//GridLayout gridLayout = new GridLayout(4, 1);
//Or BoxLayout
BoxLayout boxLayout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS); // top to bottom
setLayout(boxLayout);
pnlFromRadioButton = new JPanel();
pnlFromRadioButton.add(new Label("From Panel"));
//create a panel to hold the desired label
pnlFromTemp = new JPanel();
pnlFromTemp.add(new JLabel("Enter Temperature: [ ]"));//add label
pnlToRadioButton = new JPanel();
pnlToRadioButton.add(new Label("To Panel"));
pnlButton = new JPanel();
pnlButton.add(new Label("Buttons Panel"));
// add panels to the frame
//the panel will show in the order added
add(pnlFromRadioButton);
add(pnlFromTemp);
add(pnlToRadioButton);
add(pnlButton);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Sorry I am new to forums and am not familiar with posting etiquette for codes #c0der. But using GridLayout solved my problem and I want to show you what I did, it is a big mess but here it is. Here is my bizarre code but don't know how to reduce it any further. This is how it is suppose to look as I wanted and because now I understand what you mean by "Nest more JPanels and use layout managers" #Hovercraft Full of Eels:
my temperature program
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class TemperatureConversion extends JFrame {
// component
JTextField txtFromTemp, txtToTemp;
JLabel lblFromTemp, lblToTemp, lblToTempbox;
JRadioButton radFromCelsius, radFromFahrenheit, radFromKelvin;
JRadioButton radToCelsius, radToFahrenheit, radToKelvin;
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFrom, pnlTo, pnlButton;
JPanel pnlEnterTemp, pnlComparableTemp;
ButtonGroup bgFrom, bgTo;
JButton btnConvert, btnExit;
// constructor
public TemperatureConversion() {
super("Temperature");
// assign objects
radFromCelsius = new JRadioButton("Celsius", true);
radFromFahrenheit = new JRadioButton("Fahrenheit");
radFromKelvin = new JRadioButton("Kelvin");
lblFromTemp = new JLabel("Enter Temperature: ");
pnlFrom = new JPanel();
btnConvert = new JButton("Convert");
btnExit = new JButton("Exit");
pnlButton = new JPanel();
txtFromTemp = new JTextField(3);
lblToTemp = new JLabel("Comparable Temperature: ");
txtToTemp = new JTextField(3);
pnlTo = new JPanel();
pnlEnterTemp = new JPanel();
pnlComparableTemp = new JPanel();
pnlFromRadioButton = new JPanel();
pnlToRadioButton = new JPanel();
// register the button to a listener
btnExit.addActionListener(new MyButtonListener());
btnConvert.addActionListener(new MyButtonListener());
// make the multiple choice exclusive but not a container
bgFrom = new ButtonGroup();
bgFrom.add(radFromCelsius);
bgFrom.add(radFromFahrenheit);
bgFrom.add(radFromKelvin);
// radio buttons
radToCelsius = new JRadioButton("Celsius");
radToFahrenheit = new JRadioButton("Fahrenheit", true);
radToKelvin = new JRadioButton("Kelvin");
// make the multiple choice exclusive
bgTo = new ButtonGroup();
bgTo.add(radToCelsius);
bgTo.add(radToFahrenheit);
bgTo.add(radToKelvin);
pnlFrom.setLayout(new GridLayout(2, 1));
pnlFrom.add(pnlFromRadioButton);
pnlFrom.add(pnlEnterTemp);
pnlTo.setLayout(new GridLayout(2, 1));
pnlTo.add(pnlToRadioButton);
pnlTo.add(pnlComparableTemp);
// decorate the panel
pnlFrom.setBorder(BorderFactory.createTitledBorder("From"));
pnlTo.setBorder(BorderFactory.createTitledBorder("To"));
// add radiobutton to panel
pnlFromRadioButton.add(radFromCelsius);
pnlFromRadioButton.add(radFromFahrenheit);
pnlFromRadioButton.add(radFromKelvin);
pnlToRadioButton.add(radToCelsius);
pnlToRadioButton.add(radToFahrenheit);
pnlToRadioButton.add(radToKelvin);
// add button to panel
pnlButton.add(btnConvert);
pnlButton.add(btnExit);
// add label and txt field to panel
pnlEnterTemp.add(lblFromTemp);
pnlEnterTemp.add(txtFromTemp);
pnlComparableTemp.add(lblToTemp);
txtToTemp.setEditable(false);
pnlComparableTemp.add(txtToTemp);
// add panels to the frame
add(pnlFrom, BorderLayout.NORTH);
add(pnlTo, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
// private inner class to handle button event
private class MyButtonListener implements ActionListener {
// must override actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
if (radFromCelsius.isSelected() && radToFahrenheit.isSelected()) {
int strInput = Integer.parseInt(txtFromTemp.getText());
int celsius = strInput * 9 / 5 + 32;
txtToTemp.setText(Integer.toString(celsius));
} else if (radFromCelsius.isSelected() && radToCelsius.isSelected() ||
radFromFahrenheit.isSelected() && radToFahrenheit.isSelected() ||
radFromKelvin.isSelected() && radToKelvin.isSelected()) {
txtToTemp.setText(txtFromTemp.getText());
} else if (radToCelsius.isSelected() && radFromFahrenheit.isSelected()) {
int strInput = Integer.parseInt(txtFromTemp.getText());
int fahrenheit = (strInput - 32) * 5 / 9;
txtToTemp.setText(Integer.toString(fahrenheit));
} else if (radFromKelvin.isSelected() && radToCelsius.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double celsius = strInput - 273.15;
txtToTemp.setText(Double.toString(celsius));
} else if (radFromKelvin.isSelected() && radToFahrenheit.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double fahrenheit = strInput - 459.67;
txtToTemp.setText(Double.toString(fahrenheit));
} else if (radFromCelsius.isSelected() && radToKelvin.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double celsius = strInput + 273.15;
txtToTemp.setText(Double.toString(celsius));
} else if (radFromFahrenheit.isSelected() && radToKelvin.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double fahrenheit = strInput + 255.37;
txtToTemp.setText(Double.toString(fahrenheit));
}
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
By the way #Hovercraft Full Of Eels, your solution is way more efficient and advanced than my level of thinking. I am newbie to programming in general so bear with me on my messy code and organization lol. I have barely dipped my feet into OOP. I do have a sense of how you used enum for TempScale and I thank you for your suggestion. I will keep these in my notes as references.
EDITED
I've probably just stared at the screen for WAYYY too long but I feel the need to submit this question prior to going to sleep incase my delirium remains true...
The problem I'm having is I'm trying to get an int/double from the JTextField textField and convert it to a(n) int/double to use later in a listener, after retrieving it from a listener... ListenForText implements KeyListener, specifically KeyTyped, to obtain, through toString(), and store it in a String txtFldAmnt. After which I will store the result of Integer.parseInt(txtFldAmnt) into fldAmnt (fldAmnt = Integer.pareseInt(txtFldAmnt)) LINE 99 if copied to an editor. Once it's converted into an int I want to be able to manipulate it and then use it again, at LINE 173, to display, in a new window, the fldAmnt. Honestly, I don't really care about whether it's an int or String displayed, but I know a String is required for JTextField. What magic am I missing? Answers are always welcome but I prefer a chance to learn. Also, as I'm fairly new to Java, off topic pointers, criticism, and better ways to implement this code is greatly welcomed :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame{
/**
* wtf is the serial version UID = 1L
*/
private static final long serialVersionUID = 1L;
private JButton wdBtn;
private JButton dpBtn;
private JButton xferBtn;
private JButton balBtn;
private JRadioButton chkRadio;
private JRadioButton savRadio;
private JTextField textField;
private static String txtFldAmnt;
private static int fldAmnt = 0;
private static Double chkBal = 0.00;
private static Double savBal = 0.00;
public static void main(String[] args){
new GUI();
}
public GUI() {
//default location and size
this.setSize(300,182);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("ATM Machine");
//add buttons
wdBtn = new JButton("Withdraw");
dpBtn = new JButton("Deposit");
xferBtn = new JButton("Transfer");
balBtn = new JButton("Show Balance");
chkRadio = new JRadioButton("Checking");
chkRadio.setSelected(false);
savRadio = new JRadioButton("Savings");
savRadio.setSelected(false);
textField = new JTextField("", 20);
final JLabel textLabel = new JLabel("Enter amount: ");
textField.setToolTipText("Enter amount");
//Listener class to pass button listeners
ListenForButton lForButton = new ListenForButton();
wdBtn.addActionListener(lForButton);
dpBtn.addActionListener(lForButton);
xferBtn.addActionListener(lForButton);
balBtn.addActionListener(lForButton);
chkRadio.addActionListener(lForButton);
savRadio.addActionListener(lForButton);
ListenForText textFieldListener = new ListenForText();
textField.addKeyListener(textFieldListener);
//Configure layouts
JPanel PANEL = new JPanel();
PANEL.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2,2, 5, 10));
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,2,10,10));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(2,1));
//add buttons to their panels
panel1.add(wdBtn);
panel1.add(dpBtn);
panel1.add(xferBtn);
panel1.add(balBtn);
panel2.add(chkRadio);
panel2.add(savRadio);
panel3.add(textLabel);
panel3.add(textField);
PANEL.add(panel1);
PANEL.add(panel2);
PANEL.add(panel3);
this.add(PANEL);
//this.setAlwaysOnTop(true);
this.setVisible(true);
}
//implement listeners
private class ListenForText implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
txtFldAmnt = (e.toString());
fldAmnt = Integer.parseInt(txtFldAmnt);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e){
//maybe do case/switch statements
if (e.getSource() == wdBtn) {
JFrame newFrame = new JFrame("Withdraw Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Withdraw Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == dpBtn) {
JFrame newFrame = new JFrame("Deposit Title");
/*
* Set the newFrame.setSize(300,182); to this comment in the if statement to place
* the window directly over current window
*/
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Deposit Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == xferBtn) {
JFrame newFrame = new JFrame("Transfer Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Transfer Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == balBtn){
JFrame newFrame = new JFrame("Balance Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JTextField newLbl = new JTextField(Integer.toString(fldAmnt));
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
}
}
}
-cheers
EDITED BELOW
Thank for the answers, and I'm sorry for the horrible description... but I found a work around, thoguh I'm not sure if it's appropriate.
with the above example:
fldAmnt = Integer.pareseInt(txtFldAmnt)
i just added a .getText() //Though I rewrote the entire source code
fldAmnt = Integer.pareseInt(txtFldAmnt.getText())
it's worked for me for my entire program.
I wish I didn't have to post my entire code below but I haven't decided on a great place to store all of my code yet.
(SUGGESTIONS ARE WELCOME :D)
but here it is:
import javax.swing.;
import java.awt.GridLayout;
import java.awt.event.;
import javax.swing.border.*;
public class ATM extends JFrame{
//buttons needed
JButton wBtn;
JButton dBtn;
JButton xBtn;
JButton bBtn;
//radios needed
JRadioButton cRadio;
JRadioButton sRadio;
//Text field needed
JTextField txt;
JLabel txtLabel;
static int withdraw = 0;
Double amount = 0.00;
Double cBal = 100.00;
Double sBal = 100.00;
double number1, number2, totalCalc;
public static void main(String[] args){
new Lesson22();
}
public ATM(){
this.setSize(400, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("My Third Frame");
wBtn = new JButton("Withdraw");
dBtn = new JButton("Deposit");
xBtn = new JButton("Transfer");
bBtn = new JButton("Show Balance");
cRadio = new JRadioButton("Checking");
sRadio = new JRadioButton("Savings");
txtLabel = new JLabel("Amount: $");
txt = new JTextField("", 10);
JPanel thePanel = new JPanel();
// Create an instance of ListenForEvents to handle events
ListenForButton lForButton = new ListenForButton();
wBtn.addActionListener(lForButton);
dBtn.addActionListener(lForButton);
xBtn.addActionListener(lForButton);
bBtn.addActionListener(lForButton);
// How to add a label --------------------------
// Creates a group that will contain radio buttons
// You do this so that when 1 is selected the others
// are deselected
ButtonGroup operation = new ButtonGroup();
// Add radio buttons to the group
operation.add(cRadio);
operation.add(sRadio);
// Create a new panel to hold radio buttons
JPanel operPanel = new JPanel();
JPanel btnPanel1 = new JPanel();
JPanel btnPanel2 = new JPanel();
btnPanel1.setLayout(new GridLayout(1,2));
btnPanel2.setLayout(new GridLayout(1,2));
Border btnBorder = BorderFactory.createEmptyBorder();
btnPanel1.setBorder(btnBorder);
btnPanel1.add(wBtn);
btnPanel1.add(dBtn);
btnPanel2.setBorder(btnBorder);
btnPanel2.add(xBtn);
btnPanel2.add(bBtn);
Border operBorder = BorderFactory.createBevelBorder(1);
// Set the border for the panel
operPanel.setBorder(operBorder);
// Add the radio buttons to the panel
operPanel.add(cRadio);
operPanel.add(sRadio);
// Selects the add radio button by default
cRadio.setSelected(true);
JPanel txtPanel = new JPanel();
txtPanel.add(txtLabel);
txtPanel.add(txt);
thePanel.add(btnPanel1);
thePanel.add(btnPanel2);
thePanel.add(operPanel);
thePanel.add(txtPanel);
thePanel.setLayout(new GridLayout(4,2));
this.add(thePanel);
this.setVisible(true);
txt.requestFocus();
}
private class ListenForButton implements ActionListener{
// This method is called when an event occurs
public void actionPerformed(ActionEvent e){
/******************************************************
* THIS IS FOR CHECKING
*****************************************************/
// Check if the source of the event was the button
if(cRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
cBal -= amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel cLabel = new JLabel(Double.toString(cBal));
JLabel CLBL = new JLabel("Checking: ");
panel.add(CLBL);
panel.add(cLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
amount = Double.parseDouble(txt.getText());
cBal += amount;
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (sBal >= 0 && sBal >= amount){
cBal += amount;
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
/******************************************************
* THIS IS FOR SAVINGS
*****************************************************/
if(sRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
if(sBal >= 0 && sBal >= amount){
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel sLabel = new JLabel(Double.toString(sBal));
JLabel SLBL = new JLabel("Savings: ");
panel.add(SLBL);
panel.add(sLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
try{
amount = Double.parseDouble(txt.getText());
sBal += amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (cBal >= 0 && cBal >= amount){
sBal += amount;
cBal -= amount;
}
else if (cBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
...and by the way can anyone explain this warning message:
The serializable class ATM does not declare a static final serialVersionUID field of type long
If not simply don't bother. I'll keep researching into it when I have time.
This is still not complete, but thank you all for your help!
KeyListener on any JTextComponent is a bad idea.
To monitor changes to a text component, use a DocumentListener, to filter the content that a text component can handle, use a DocumentFilter. See Listening for Changes on a Document, Implementing a Document Filter and DocumentFilter Examples for more details.
In your case, it'd probably better to use a JSpinner or JFormattedTextField as they are designed to handle (amongst other things) numbers
See How to Use Spinners and How to Use Formatted Text Fields for more details
I am looking for help to debug this program that I have written there are, no errors but the goal is to create a frame with three panels inside of it each of which has a titled border. I am having difficulty because my prompt requires of me to make 2 constructors and 2 classes so when I call the DailySales class in main I feel it doesn't include the other class.
So basically how can I make the panels show up while still keeping two classes and two constructors and how would I add titled borders to each of the JPanels, sorry but I'm having difficulty with the Oracle tutorial.
import java.awt.*;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DailySales extends JPanel {
final int lPizzaPrice = 12;
final int mPizzaPrice = 9;
final int sPizzaPrice = 6;
final int bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza;
String mPizza;
String sPizza;
String bSticks;
int largePizza;
int mediumPizza;
int smallPizza;
int breadSticks;
int totalLargePizza;
int totalMediumPizza;
int totalSmallPizza;
int totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
private FlowLayout dailyFlow;
private Container container;
JLabel lPizzaLabel = new JLabel("Large Pizza");//creating labels
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");//Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(dailyFlow);
subPanel1.add(lPizzaLabel, largeField);
subPanel1.add(mPizzaLabel, mediumField);
subPanel1.add(sPizzaLabel, smallField);
subPanel1.add(bSticksLabel, breadField);
subPanel1.setSize(100, 100);
subPanel2.setLayout(dailyFlow);
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel3.setLayout(dailyFlow);
subPanel3.add(totalSalesLabel, totalSalesField);
subPanel3.add(totalTaxLabel, totalTaxField);
subPanel3.add(netSalesLabel, netSalesField);
subPanel3.add(dailyCostLabel, dailyCostField);
subPanel3.add(profitLabel, profitField);
top.setBackground(Color.red);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
totalSalesField.setEditable(false);//making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() //creating a constructor
{
/**
* The constructor with all the layout informations and operators
*
*
* Also adding all labels, textfields, and buttons to frame. making the
* total field uneditable
*/
JFrame frame = new JFrame();
frame.add(subPanel1);
frame.add(subPanel2);
frame.add(subPanel3);
frame.add(top);
frame.setSize(600, 450);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {//initial button removes all entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {//update button calculates all the inputs and displays everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice * largePizza);
totalMediumPizza = (mPizzaPrice * mediumPizza);
totalSmallPizza = (sPizzaPrice * smallPizza);
totalBreadSticks = (bSticksPrice * breadSticks);
totalLargeField.setText("" + totalLargePizza);
totalMediumField.setText("" + totalMediumPizza);
totalSmallField.setText("" + totalSmallPizza);
totalBreadField.setText("" + totalBreadSticks);
totalSales = (totalLargePizza + totalMediumPizza + totalSmallPizza + totalBreadSticks);
totalTax = (totalSales * tax);
netSales = (totalSales - totalTax);
profit = (netSales - dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit > 0) {
profitLabel.setText("Profit of ");
} else if (profit < 0) {
profitLabel.setText("Loss of ");
} else if (profit == 0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {//close button closes the program when clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
There's still a lot you can do to make this better, but this works.
public class DailySales extends JPanel {
final int lPizzaPrice = 12, mPizzaPrice = 9, sPizzaPrice = 6, bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza, mPizza, sPizza, bSticks;
int largePizza, mediumPizza, smallPizza, breadSticks, totalLargePizza,
totalMediumPizza, totalSmallPizza, totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
JLabel lPizzaLabel = new JLabel("Large Pizza");
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");// Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(new GridLayout(4, 2));
subPanel1.add(lPizzaLabel);
subPanel1.add(largeField);
subPanel1.add(mPizzaLabel);
subPanel1.add(mediumField);
subPanel1.add(sPizzaLabel);
subPanel1.add(smallField);
subPanel1.add(bSticksLabel);
subPanel1.add(breadField);
subPanel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
// subPanel2.setLayout(new BoxLayout(subPanel2, BoxLayout.Y_AXIS)); // Same as next line
subPanel2.setLayout(new GridLayout(4, 1));
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
subPanel3.setLayout(new GridLayout(5, 2));
subPanel3.add(totalSalesLabel);
subPanel3.add(totalSalesField);
subPanel3.add(totalTaxLabel);
subPanel3.add(totalTaxField);
subPanel3.add(netSalesLabel);
subPanel3.add(netSalesField);
subPanel3.add(dailyCostLabel);
subPanel3.add(dailyCostField);
subPanel3.add(profitLabel);
subPanel3.add(profitField);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
top.setBackground(Color.YELLOW);
totalSalesField.setEditable(false);// making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() // creating a constructor
{
/**
* The constructor with all the layout informations and operators Also
* adding all labels, textfields, and buttons to frame. making the total
* field uneditable
*/
new GUI();
JPanel mainPanel = new JPanel(new GridLayout(2, 2));
mainPanel.add(subPanel1);
mainPanel.add(subPanel2);
mainPanel.add(subPanel3);
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearButton);
buttonPanel.add(calculateButton);
buttonPanel.add(exitButton);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(top, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(600, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {// initial button
// removes all
// entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {// update button
// calculates
// all the
// inputs and
// displays
// everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice*largePizza);
totalMediumPizza = (mPizzaPrice*mediumPizza);
totalSmallPizza = (sPizzaPrice*smallPizza);
totalBreadSticks = (bSticksPrice*breadSticks);
totalLargeField.setText(""+totalLargePizza);
totalMediumField.setText(""+totalMediumPizza);
totalSmallField.setText(""+totalSmallPizza);
totalBreadField.setText(""+totalBreadSticks);
totalSales = (totalLargePizza+totalMediumPizza+totalSmallPizza+totalBreadSticks);
totalTax = (totalSales*tax);
netSales = (totalSales-totalTax);
profit = (netSales-dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit>0) {
profitLabel.setText("Profit of ");
} else if (profit<0) {
profitLabel.setText("Loss of ");
} else if (profit==0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {// close button
// closes the
// program when
// clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
Very new to Java here. How do I use a JRadioButton to set two different text fields? The three buttons are:
1. 7 at 5.35%
2. 15 at 5.5%
3. 30 at 5.75%
Choice 1 sets field1 to 7 and field2 to 5.35
Choice 2 sets field1 to 15 and field2 to 5.5
Choice 3 sets field1 to 30 and field2 to 5.75
What's the fastest and easiest way to write this code? Seems easy enough, but I'm having a hell of a time with the JRadioButtons.
Thanks.
EDIT: Here's the code. Looks like I'm almost there, however, I still can't get the radio buttons to put the data in the fields. Says I need to change the type to int, but if I do that it's not an enterable field anymore...
//import all needed functionality
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.*;
public class ScrofaniWk3Alt extends JApplet{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* #param args
*/
// Declare variables and put code application logic here
String userInput = null;
JLabel loanAmountLabel = new JLabel("Loan Amount: ");
JTextField loanAmount = new JTextField();
double[] ratesList = {0.0535, 0.055, 0.0575};
JLabel rateLabel=new JLabel("Interest Rate: ");
JTextField rate=new JTextField();
String[] yearsList = {"7","15","30"};
JLabel yearsLabel=new JLabel("Years of Payment: ");
JTextField years=new JTextField();
JRadioButton sevenButton = new JRadioButton("7");
JRadioButton fifteenButton = new JRadioButton("15");
JRadioButton thirtyButton = new JRadioButton("30");
JLabel payLabel=new JLabel("Monthly Payment: ");
JLabel payment=new JLabel();
JButton calculate=new JButton("Calculate");
JButton clear=new JButton("Clear");
JButton quit=new JButton("Quit");
JTextArea payments=new JTextArea();
JScrollPane schedulePane=new JScrollPane(payments);
Container mortCalc = getContentPane();
public void init() {
//Configure the radio buttons to input data into fields
sevenButton.setActionCommand("Radio1");
fifteenButton.setActionCommand("Radio2");
thirtyButton.setActionCommand("Radio3");
ButtonGroup chooseYears = new ButtonGroup();
chooseYears.add(sevenButton);
chooseYears.add(fifteenButton);
chooseYears.add(thirtyButton);
}
public void actionPerformed(ActionEvent e) {
if ("Radio1".equals(e.getActionCommand())) {
years = 7;
rate = 5.35;
}
if ("Radio2".equals(e.getActionCommand())) {
years = 15;
rate = 5.5;
}
if ("Radio3".equals(e.getActionCommand())) {
years = 30;
rate = 5.75;
}
calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Perform the calculation
double yearsCalc=Integer.parseInt(years.getText())*12;
double rateCalc=Double.parseDouble(rate.getText())/12;
double principalCalc=Double.parseDouble(loanAmount.getText());
double monthlyPayment=principalCalc*Math.pow(1+rateCalc,yearsCalc)*rateCalc/(Math.pow(1+rateCalc,yearsCalc)-1);
DecimalFormat df = new DecimalFormat("$###,###.##");
payment.setText(df.format(monthlyPayment));
// Perform extra calculations to show the loan amount after each subsequent payoff
double principal=principalCalc;
int month;
StringBuffer buffer=new StringBuffer();
buffer.append("Month\tAmount\tInterest\tBalance\n");
for (int f=0; f<yearsCalc; f++) {
month=f+1;
double interest=principal*rateCalc;
double balance=principal+interest-monthlyPayment;
buffer.append(month+"\t"); buffer.append(new String(df.format(principal))+"\t");
buffer.append(new String(df.format(interest))+"\t"); buffer.append(new String(df.format(balance))+"\n");
principal=balance;
}
payments.setText(buffer.toString());
} catch(Exception ex) {
System.out.println(ex);
}
}
});
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loanAmount.setText(""); payment.setText(""); payments.setText("");
}
});
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
//Config GUI
JPanel panelMort=new JPanel();
panelMort.setLayout(new GridLayout(5,2));
panelMort.add(loanAmountLabel);
panelMort.add(loanAmount);
panelMort.add(new Label());
panelMort.add(sevenButton);
panelMort.add(fifteenButton);
panelMort.add(thirtyButton);
panelMort.add(yearsLabel);
panelMort.add(years);
panelMort.add(rateLabel);
panelMort.add(rate);
panelMort.add(payLabel);
panelMort.add(payment);
JPanel buttons=new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
buttons.add(calculate); buttons.add(clear); buttons.add(quit);
JPanel panelMort2=new JPanel();
panelMort2.setLayout(new BoxLayout(panelMort2, BoxLayout.Y_AXIS));
panelMort2.add(panelMort); panelMort2.add(buttons);
mortCalc.add(BorderLayout.NORTH, panelMort2);
mortCalc.add(BorderLayout.CENTER, schedulePane);
}
public static void main(String[] args) {
JApplet applet = new ScrofaniWk3Alt();
JFrame frameMort = new JFrame("ScrofaniWk3Alt");
frameMort.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameMort.getContentPane().add(applet);
frameMort.setSize(500,1000);
frameMort.setResizable(true);
frameMort.setVisible(true);
applet.init();
applet.start();
}
}
Read the section from the Swing tutorial on How to Use Radio Buttons. Basically you add an ActionListener to each button and then set the value in the text fields.
If you need more help then post your SSCCE that shows what you have attempted after reading the tutorial.
// put these where you define your buttons
radio1.setActionCommand("RADIO1");
radio2.setActionCommand("RADIO2");
radio3.setActionCommand("RADIO3");
// add this to your actionPerformed method
public void actionPerformed(ActionEvent e) {
if ("RADIO1".equals(e.getActionCommand())) {
field1 = 7;
field2 = 5.35;
}
if ("RADIO2".equals(e.getActionCommand())) {
field1 = 15;
field2 = 5.5;
}
if ("RADIO3".equals(e.getActionCommand())) {
field1 = 30;
field2 = 5.75;
}
}