Running as a test application in Eclipse:
` //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 ScrofaniWk3 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();
JComboBox chooseYears = new JComboBox(yearsList);
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() {
//This makes the chooseYears function
chooseYears.setSelectedIndex(0);
chooseYears.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent choose) {
JComboBox cb = (JComboBox)choose.getSource();
String termYear = (String)cb.getSelectedItem();
years.setText(termYear);
int index=0;
switch (Integer.parseInt(termYear)) {
case 7: index=0; break;
case 15: index=1; break;
case 30: index=2; break;
}
rate.setText(ratesList[index]+"");
}
});
calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Perform the calculation
double rateCalc=Double.parseDouble(rate.getText())/12;
double principalCalc=Double.parseDouble(loanAmount.getText());
double yearsCalc=Integer.parseInt(years.getText())*12;
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(yearsLabel); panelMort.add(years);
panelMort.add(new Label()); panelMort.add(chooseYears);
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, panelMort);
mortCalc.add(BorderLayout.CENTER, schedulePane);
}
public static void main(String[] args) {
JApplet applet = new ScrofaniWk3();
JFrame frameMort = new JFrame("ScrofaniWk3");
frameMort.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameMort.getContentPane().add(applet);
frameMort.setSize(500,1000);
frameMort.setResizable(true);
frameMort.setVisible(true);
applet.init();
applet.start();
}
}`
Add
mortCalc.add(BorderLayout.SOUTH, buttons);
after
mortCalc.add(BorderLayout.NORTH, panelMort);
mortCalc.add(BorderLayout.CENTER, schedulePane);
You've got to simply check where you eventually add the buttons or the containers that hold the buttons.
Check which JPanel you add your JButtons to -- buttons
Then check what you add buttons to -- panelMort2
Then check what you add panelMort2 to -- nothing.
This is nothing more than basic logic.
Related
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.
I'm currently making our project and I'm having problem reseting JLabel back to "0". Here's the code
main code snippet (check note 1 for frame disposal method used):
import javax.swing.*; //import library
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class draft_main //class name
{
public static void main(String[] args)
{ //method name
JFrame f0 = new JFrame("POS"); //frame
JPanel p0 = new JPanel(); //panel inside the frame
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
JPanel p6 = new JPanel();
JPanel p7 = new JPanel();
JLabel l0 = new JLabel("Amount:"); //label inside the panel
JLabel l1 = new JLabel("0");
JLabel l2 = new JLabel("Menu Code: ");
JLabel l3 = new JLabel("--Menu--");
JTextField tf0 = new JTextField("", 12); //user input for menu code
JButton b0 = new JButton("Checkout"); //buttons
JButton b1 = new JButton("Cancel");
JButton b2 = new JButton("Exit");
JButton b4 = new JButton("Accept");
JButton b7 = new JButton("Remove");
JOptionPane jop = new JOptionPane(); //JOptionPane
JTextField tf1 = new JTextField("1. Hot Pockets Pizza", 20); //list of menu
JTextField tf2 = new JTextField("2. Burger with Fries", 20);
JTextField tf3 = new JTextField("3. Sticky Rice (Bico)", 20);
ArrayList<String> ar = new ArrayList<String>(); //list of array
try{
b4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) //what the accept button does
{
String order = tf0.getText(), tots="", temp="";
int o = Integer.parseInt(order);
int tot=0;
switch(o) //menu choice
{
case 1 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+250; tots = Integer.toString(tot); l1.setText(tots); ar.add("Hot Pockets Pizza"); break;
case 2 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+65; tots = Integer.toString(tot); l1.setText(tots); ar.add("Burger with Fries"); break;
case 3 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+12; tots = Integer.toString(tot); l1.setText(tots); ar.add("Sticky Rice (Bico)"); break;
default : jop.showMessageDialog(null, "Menu code not listed in menu", "Error", jop.INFORMATION_MESSAGE); break;
}
}
});
b0.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) //what the checkout button does
{
JFrame f1 = new JFrame("Checkout");
JFrame f2 = new JFrame("Order");
JPanel p8 = new JPanel();
JPanel p9 = new JPanel();
JPanel p10 = new JPanel();
JPanel p11 = new JPanel();
JPanel p12 = new JPanel();
JPanel p13 = new JPanel();
JPanel p14 = new JPanel();
JLabel l5 = new JLabel("Order list");
JLabel l6 = new JLabel(/*convert ArrayList to String then put here*/);
JLabel l4 = new JLabel("Cash");
JTextField tf4 = new JTextField("", 14);
JButton b5 = new JButton("Accept");
JButton b6 = new JButton("Cancel");
JButton b7 = new JButton("Ok");
b5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String cas = l1.getText(), in = tf4.getText();
int cash = Integer.parseInt(cas), inp = Integer.parseInt(in), cahs=0;
if(cash>inp)
{
jop.showMessageDialog(null, "Insufficient funds", "Lacking cash? Work for it.", jop.INFORMATION_MESSAGE);
}
else if(cash<inp)
{
cahs = inp - cash;
jop.showMessageDialog(null, "Change: " +cahs+". Thank you");
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
else if(cash==inp)
{
jop.showMessageDialog(null, "Thank you.", "Thank you.", jop.INFORMATION_MESSAGE);
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
}
});
b6.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
});
b7.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f2.dispatchEvent(new WindowEvent(f2, WindowEvent.WINDOW_CLOSING));
}
});
p9.add(l0);
p9.add(l1);
p10.add(l4);
p10.add(tf4);
p11.add(b5);
p11.add(b6);
p12.add(l5);
p12.add(l6);
p13.add(b7);
p14.add(p12);
p14.add(p13);
p8.add(p10);
p8.add(p11);
p8.add(p9);
f1.add(p8);
f1.pack();
f1.setSize(240,170);
f1.setLocationRelativeTo(null);
f1.setResizable(false);
f1.setDefaultCloseOperation(f1.DISPOSE_ON_CLOSE);
f1.setVisible(true);
f2.add(p14);
f2.pack();
f2.setSize(270,100);
f2.setResizable(false);
f2.setLocationRelativeTo(null);
f2.setDefaultCloseOperation(f2.DISPOSE_ON_CLOSE);
f2.setVisible(true);
}
});
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
l1.setText("0");
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f0.dispose();
}
});
}
catch(Exception e)
{
jop.showMessageDialog(null, "Error");
}
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
p4.add(tf1);
p5.add(tf2);
p6.add(tf3);
p7.add(l3);
p3.add(l2);
p3.add(tf0);
p3.add(b4);
p1.add(l0);
p1.add(l1);
p2.add(b0);
p2.add(b1);
p2.add(b2);
p0.add(p3);
p0.add(p1);
p0.add(p2);
p0.add(p7);
p0.add(p4);
p0.add(p5);
p0.add(p6);
f0.add(p0);
f0.pack();
f0.setSize(303,280);
f0.setLocationRelativeTo(null);
f0.setResizable(false);
f0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f0.setVisible(true);
}
}
what happens is when the main window opens it asks for which from the menu did a guy order then it displays the price. During checkout the user will be asked to input amount of cash given and gives change if there's any. After then the checkout frame is then "properly" disposed (so as I think so), exposing the main frame. However the JLabel does not seem to update when I place another order or clear the current order and it bothers me since the main frame is supposed to be fully interactive until the main frame is closed.
note #1: I have used different methods on how to dispose the 2nd and 3rd frame which pops up since I thought it may have been because of the dispose(); does not really destroys the frame but let's it run in the background.
note #2: yes the program is not finished yet, but those don't matter for now for those will just be some minor features of the application.
You've several problems with this code, but the major ones that I see (and I haven't gone through all of it yet, so there may be more)
First and foremost, those JFrame sub-windows shouldn't be JFrames at all, but rather should be modal JDialogs. The reason for this is this gives you complete control over program flow when these dialogs are used, since you'll then know that the main program flow will be put on hold while the modal dialog is visible, and then the flow will resume as soon as the dialog is no longer visible. This way you can query the state of the dialog after it has been dealt with, and then use this information to update your GUI.
Your amount is shown in the l1 variable, and this will never change unless you specifically call setText(...) on this variable. You don't seem to be doing it when the order has been processed. Again modal dialogs will help you with this.
Your variable naming is bad. Instead of using meaningless letters and numbers for names, use names that make sense and that make your code self-commenting. So for instance, instead of l1, use amountLabel or something similar.
Your code is one huge god class with everything stuffed into the static main method, and this makes for a debugging nightmare. Java is an object-oriented language, and if used properly OOP techniques can help you reduce program complexity making your code easier for yourself and for us to understand. Start OOP-ifying your program and you'll see immediate dividends.
And I found your bug -- you're adding the l1 JLabel to another container, and so it is effectively being removed from the original JFrame. If you minimize your original GUI and then restore it, you'll see the amount l1 JLabel disappear.
Here's some sample code not yet done, but to give you an idea about adding OOP to the program:
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Draft2 extends JPanel {
private List<MyItem> selectedItems = new ArrayList<>();
private NumberFormat formatter = NumberFormat.getCurrencyInstance();
private double total;
private JLabel totalAmountLabel = new JLabel(formatter.format(total));
private DefaultComboBoxModel<MyItem> comboModel = new DefaultComboBoxModel<>();
private JComboBox<MyItem> menuCombo = new JComboBox<>(comboModel);
public Draft2() {
// monospaced to make names and price line up
menuCombo.setFont(new Font(Font.MONOSPACED, Font.BOLD, 12));
// fill the JComboBox with items
comboModel.addElement(new MyItem("Baseball", 21.5));
comboModel.addElement(new MyItem("Bat", 50.8));
comboModel.addElement(new MyItem("Football", 22.26));
// create a JPanel to hold selection components and add components
JPanel selectionPanel = new JPanel();
selectionPanel.add(new JLabel("Menu:"));
selectionPanel.add(menuCombo);
selectionPanel.add(new JButton(new AcceptAction("Accept", KeyEvent.VK_A)));
// create a JPanel to hold the total amount information
JPanel totalAmountPanel = new JPanel();
totalAmountPanel.add(new JLabel("Total Amount:"));
totalAmountPanel.add(totalAmountLabel);
// create a JPanel to hold buttons, uses grid layout with a single row
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
btnPanel.add(new JButton(new CheckOutAction("Check Out", KeyEvent.VK_C)));
btnPanel.add(new JButton(new CancelAction("Cancel", KeyEvent.VK_N)));
btnPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(selectionPanel);
add(Box.createVerticalStrut(5)); // so don't crowd things
add(totalAmountPanel);
add(Box.createVerticalStrut(5));
add(btnPanel);
}
public void setTotalAmount(double total) {
totalAmountLabel.setText(formatter.format(total));
}
private class AcceptAction extends AbstractAction {
public AcceptAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
MyItem myMenuItem = (MyItem) menuCombo.getSelectedItem();
if (myMenuItem == null) {
return; // nothing selected, get out
}
selectedItems.add(myMenuItem);
double total = 0.0;
for (MyItem myItem : selectedItems) {
total += myItem.getCost();
}
setTotalAmount(total);
}
}
private class CheckOutAction extends AbstractAction {
public CheckOutAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Finish....
// open JDialog or JOptionPane
}
}
private class CancelAction extends AbstractAction {
public CancelAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Finish...
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("My GUI Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Draft2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
class MyItem {
private NumberFormat formatter = NumberFormat.getCurrencyInstance();
private String name;
private double cost;
public MyItem(String name, double cost) {
this.name = name;
this.cost = cost;
}
public String getName() {
return name;
}
public double getCost() {
return cost;
}
#Override
public String toString() {
return String.format("%-10s %s", name, formatter.format(cost));
}
}
I'm getting an InputMismatchException when I press the "next" button.
Here is the code for the panel that has the button:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PanelSampleYard extends JPanel
{
private JLabel label;
private DisplaySampleYard display;
int times = 0;
public PanelSampleYard()
{
setLayout(new BorderLayout());
setPreferredSize(new Dimension(200, 125));
label = new JLabel("Green and Grow Mowing Company", SwingConstants.CENTER);
add(label, BorderLayout.NORTH);
display = new DisplaySampleYard();
add(display, BorderLayout.CENTER);
JPanel subpanel = new JPanel();
subpanel.setLayout(new FlowLayout());
JButton next = new JButton("Next");
JButton quit = new JButton("Quit");
next.addActionListener(new Listener1());
quit.addActionListener(new Listener2());
subpanel.add(next);
subpanel.add(quit);
add(subpanel, BorderLayout.SOUTH);
}
private class Listener1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
display.next(display.contents(times));
times++;
}
}
private class Listener2 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
And the code for the display that is inside the panel:
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class DisplaySampleYard extends JPanel
{
private JLabel label;
private JTextField last, first, size, cost, total;
double sum = 0;
int index = 0;
public DisplaySampleYard()
{
setLayout(new GridLayout(5,2));
last = new JTextField("");
add(new JLabel("Last Name:"));
add(last);
first = new JTextField("");
add(new JLabel("First Name:"));
add(first);
size = new JTextField("");
add(new JLabel("Lawn Size:"));
add(size);
cost = new JTextField("");
add(new JLabel("Total Cost:"));
add(cost);
total = new JTextField("");
add(new JLabel("Running Total:"));
add(total);
}
public void next(Customer c)
{
last.setText(c.getLastName()+"");
first.setText(c.getFirstName()+"");
size.setText(c.getSize()+"");
cost.setText(c.getCost()+"");
sum = sum + c.getCost();
total.setText(""+sum);
}
public Customer contents(int index)
{
Scanner infile = new Scanner("greenGrow.txt");
int reps = infile.nextInt();
Customer[] array = new Customer[reps];
for(int x = 0; x<reps; x++)
{
array[x].setLastName(infile.next());
array[x].setFirstName(infile.next());
array[x].setSize(infile.nextInt());
}
return array[index];
}
}
The data file that the Scanner is reading from contains:
5
Jeffers
Tom
5000
Smith
Sam
10000
Nevar
Tina
15000
Kim
Lisa
20000
Black
Kim
30000
What's wrong with my code? Thanks in advance!
P.S. There are a few more classes, but I don't think they are causing this problem
When you use Scanner read file, you should construct by File type parameter, it will scan values from the specified file. like:
new Scanner(new File("greenGrow.txt"));
If construct by String, the Scanner will scan values from the specified String
public class StatsGUI extends JFrame implements ActionListener {
JLabel label;
JLabel label2;
JTextField input;
JTextField output;
JButton getButton;
JButton exitButton;
public StatsGUI()
{
JPanel panel = new JPanel();
label = new JLabel("Enter number");
panel.add(label);
input = new JTextField(10);
input.addActionListener(this);
panel.add(input);
label2 = new JLabel("Statistics");
output = new JTextField(10);
output.setEditable(false);
panel.add(output);
getButton = new JButton("Go");
getButton.addActionListener(this);
panel.add(getButton);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
panel.add(exitButton);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == exitButton)
{
System.exit(0);
}
else
{
String text = input.getText();
output.setText(text + "COUNTER");
}
}
public static void main(String[] args)
{
}
This is my simple GUI program. I have placed all buttons and other gadgets within the constructor. However, I am not sure what I should be putting inside my main in order to get my GUI to actually show up. I am sure I am missing something incredibly simple here however I am not sure what. Help would be much appreciated.
You are not that far from getting things to work. Just a few things to know:
Your UI should be started on the Event dispatching thread (EDT)
You actually need to add your panels/components to your frame
You need to pack() your Window/Frame
You need to make it visible
(Design stuff, optional but when you are at it, why not just fix that as well), no need to extend JFrame, so let's just drop that.
So eventually, taking these advices into consideration leads you to something like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class StatsGUI implements ActionListener {
JLabel label;
JLabel label2;
JTextField input;
JTextField output;
JButton getButton;
JButton exitButton;
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitButton) {
System.exit(0);
} else {
String text = input.getText();
output.setText(text + "COUNTER");
}
}
public void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
label = new JLabel("Enter number");
panel.add(label);
input = new JTextField(10);
input.addActionListener(this);
panel.add(input);
label2 = new JLabel("Statistics");
output = new JTextField(10);
output.setEditable(false);
panel.add(output);
getButton = new JButton("Go");
getButton.addActionListener(this);
panel.add(getButton);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
panel.add(exitButton);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new StatsGUI().initUI();
}
});
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class StatsGUI extends JFrame implements ActionListener {
JLabel label;
JLabel label2;
JTextField input;
JTextField output;
JButton getButton;
JButton exitButton;
public StatsGUI()
{
JPanel panel = new JPanel();
label = new JLabel("Enter number");
panel.add(label);
input = new JTextField(10);
input.addActionListener(this);
panel.add(input);
label2 = new JLabel("Statistics");
output = new JTextField(10);
output.setEditable(false);
panel.add(output);
getButton = new JButton("Go");
getButton.addActionListener(this);
panel.add(getButton);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
panel.add(exitButton);
add(panel);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == exitButton)
{
System.exit(0);
}
else
{
String text = input.getText();
output.setText(text + "COUNTER");
}
}
public static void main(String[] args)
{
StatsGUI s= new StatsGUI();
s.setVisible(true);
s.setSize(1000,1000);
}
}
You are not calling a contructor .call costructor like 'StatsGUI s= new StatsGUI();' or 'new StatsGUI();' .
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;
}
}