I have a half complete coding which basically comes down to a gui interface. The problem is that I don't know how to get it working as ticket vending machine with fixed rates and fixed amount of cash being able to put in.
So, far, I've done up to calculating total where nomatter what I do, it always comes up with a £0.00 as the totalamount answer.
I am in desperate need of help. This is very frustrating. Below is the code for the TicketCalculation Class
import java.awt.*;
import java.text.*;
import java.awt.event.*;
import javax.swing.*;
public class TicketCalculation extends JFrame implements ActionListener {
DecimalFormat pounds = new DecimalFormat("£#,##0.00");
//creating and naming buttons and textfields
private JButton twentypenceBtn = new JButton("20p");
private JButton fiftypenceBtn = new JButton("50p");
private JButton onepoundBtn = new JButton("£1");
private JButton twopoundsBtn = new JButton("£2");
private JButton fivepoundsBtn = new JButton("£5");
private JButton tenpoundsBtn = new JButton("£10");
private JButton twentypoundsBtn = new JButton("£20");
private JButton C = new JButton("Calculate");
private JButton frontBtn = new JButton("<<Front Stalls>>");
private JButton private1Btn = new JButton("<<Private Box>>");
private JButton middleBtn = new JButton("<<Middle Stalls>>");
private JButton backBtn = new JButton("<<Back Stalls>>");
private JButton calcBtn = new JButton("Calculate Bill");
private JTextField tickettypeTxt = new JTextField(14);
private JTextField stalltypeTxt = new JTextField(25);
private JTextField amountticketsTxt = new JTextField(14);
private JTextField totalamountTxt = new JTextField(10);
private JTextField amountdueTxt = new JTextField(13);
private JTextField amountpaidTxt = new JTextField(10);
//creating labels
private JLabel pickstall = new JLabel();
private JLabel tictype = new JLabel ();
private JLabel amontic = new JLabel();
private JLabel ttamon = new JLabel();
private JLabel amondue = new JLabel();
private JLabel amonpaid = new JLabel();
private JLabel label5 = new JLabel();
private JLabel spacing6 = new JLabel();
private JLabel spacing7 = new JLabel();
private JLabel spacing8 = new JLabel();
private JLabel spacing9 = new JLabel();
private JLabel spacing10 = new JLabel();
//image icon declarations
private ImageIcon paycount = new ImageIcon(getClass().getResource("paycount.jpg"));
double middleprice;
double privateprice;
double backprice;
double frontprice;
double type;
int number;
public static void main(String[] args){
new TicketCalculation();
}
public TicketCalculationt(){
setLayout(new BorderLayout());
setSize(650,750);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//naming labels
pickstall = new JLabel("==> Pick a Stall Type: ");
tictype = new JLabel ("==> Price of a Ticket: £");
amontic = new JLabel("==> Amount of Tickets: ");
ttamon = new JLabel("==> Total Amount: ");
amondue = new JLabel("==> Amount Due: £");
amonpaid = new JLabel("==> Amount Paid: £");
label5 = new JLabel(paycount);
spacing6 = new JLabel(" ");
spacing7 = new JLabel(" ");
spacing8 = new JLabel(" ");
spacing9 = new JLabel(" ");
spacing10 = new JLabel(" ");
//setting font for buttons, textfields and labels
pickstall.setFont(new Font("Rockwell", Font.BOLD, 20));
frontBtn.setFont(new Font("System", Font.BOLD, 22));
middleBtn.setFont(new Font("System", Font.BOLD, 22));
backBtn.setFont(new Font("System", Font.BOLD, 22));
private1Btn.setFont(new Font("System", Font.BOLD, 22));
tictype.setFont(new Font("Rockwell", Font.BOLD, 20));
amontic.setFont(new Font("Rockwell", Font.BOLD, 20));
ttamon.setFont(new Font("Rockwell", Font.BOLD, 20));
amondue.setFont(new Font("Rockwell", Font.BOLD, 20));
amonpaid.setFont(new Font("Rockwell", Font.BOLD, 20));
stalltypeTxt.setFont(new Font("Verdana", Font.BOLD, 20));
tickettypeTxt.setFont(new Font("Verdana", Font.BOLD, 20));
amountticketsTxt.setFont(new Font("Verdana", Font.BOLD, 20));
totalamountTxt.setFont(new Font("Verdana", Font.BOLD, 20));
amountdueTxt.setFont(new Font("Verdana", Font.BOLD, 20));
amountpaidTxt.setFont(new Font("Verdana", Font.BOLD, 20));
twentypenceBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
fiftypenceBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
onepoundBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
twopoundsBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
fivepoundsBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
tenpoundsBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
twentypoundsBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
C.setFont(new Font("Serif", Font.BOLD, 28));
stalltypeTxt.setEditable(false);
tickettypeTxt.setEditable(false);
totalamountTxt.setEditable(false);
amountdueTxt.setEditable(false);
amountpaidTxt.setEditable(false);
//positioning all buttons, textfields and labels
JPanel top = new JPanel();
top.add(label5);
add("North", top);
JPanel mid = new JPanel();
mid.add(pickstall);
mid.add(stalltypeTxt);
mid.add(spacing6);
mid.add(private1Btn);
mid.add(frontBtn);
mid.add(middleBtn);
mid.add(backBtn);
mid.add(tictype);
mid.add(tickettypeTxt);
mid.add(spacing7);
mid.add(amontic);
mid.add(amountticketsTxt);
mid.add(spacing8);
mid.add(ttamon);
mid.add(totalamountTxt);
mid.add(calcBtn);
mid.add(spacing10);
mid.add(amonpaid);
mid.add(amountpaidTxt);
mid.add(spacing9);
mid.add(twentypenceBtn);
mid.add(fiftypenceBtn);
mid.add(onepoundBtn);
mid.add(twopoundsBtn);
mid.add(fivepoundsBtn);
mid.add(tenpoundsBtn);
mid.add(twentypoundsBtn);
mid.add(amondue);
mid.add(amountdueTxt);
mid.add(C);
add("Center", mid);
calcBtn.addActionListener(this);
private1Btn.addActionListener(this);
frontBtn.addActionListener(this);
middleBtn.addActionListener(this);
backBtn.addActionListener(this);
twentypenceBtn.addActionListener(this);
fiftypenceBtn.addActionListener(this);
onepoundBtn.addActionListener(this);
twopoundsBtn.addActionListener(this);
fivepoundsBtn.addActionListener(this);
tenpoundsBtn.addActionListener(this);
twentypoundsBtn.addActionListener(this);
C.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
// event handler for the buttons
if (e.getSource() == private1Btn)
{
stalltypeTxt.setText("Private Stall Location is Chosen");
tickettypeTxt.setText("30.85");
}
else if (e.getSource() == frontBtn)
{
stalltypeTxt.setText("Front Stall Location is Chosen");
tickettypeTxt.setText("15.00");
}
else if (e.getSource() == middleBtn)
{
stalltypeTxt.setText("Middle Stall Location is Chosen");
tickettypeTxt.setText("10.20");
}
else if (e.getSource() == backBtn)
{
stalltypeTxt.setText("Back Stall Location is Chosen");
tickettypeTxt.setText("5.70");
}
else if (e.getSource() == tickettypeTxt)
{
type = Double.parseDouble(tickettypeTxt.getText());
}
else if (e.getSource() == amountticketsTxt)
{
number = Integer.parseInt(amountticketsTxt.getText());
}
else if (e.getSource() == calcBtn)
{
Workings c = new Workings();
w.setType(type);
w.setNumber(number);
double total = w.calculateBill();
totalamountTxt.setText(pounds.format(total));
}
}
}
with a halfway done auxiliary class called Workings
public class Workings {
// private instance variables
private double type, number;
// public no-argument constructor
public Workings() { }
// public constructor with four arguments
public Workings(double t, int n)
{
type = t;
number = n;
}
// public 'set' methods
public void setType(double t) { type = t; }
public void setNumber(int n) { number = n; }
// public method to calculate the bill
public double calculateBill()
{
double total = type * number ;
return total;
}
}
The ActionListener is only triggered on a JTextField when the user hits the Enter key on the keyboard while in that field. This is unintuitive, so I would say it's a big no-no to use ActionListener for that.
Instead, use a FocusListener to get the "user left the text field" events from the text fields. That should pick up the data entered and then it should work.
Here's your problem
else if (e.getSource() == tickettypeTxt)
{
type = Double.parseDouble(tickettypeTxt.getText());
}
else if (e.getSource() == amountticketsTxt)
{
number = Integer.parseInt(amountticketsTxt.getText());
}
else if (e.getSource() == calcBtn)
{
Workings c = new Workings();
w.setType(type);
w.setNumber(number);
double total = w.calculateBill();
totalamountTxt.setText(pounds.format(total));
}
Delete the first two else ifs and just do this
else if (e.getSource() == calcBtn)
{
type = Double.parseDouble(tickettypeTxt.getText());
number = Integer.parseInt(amountticketsTxt.getText());
Workings c = new Workings();
w.setType(type);
w.setNumber(number);
double total = w.calculateBill();
totalamountTxt.setText(pounds.format(total));
}
Related
Where to enter the if condition in javax.swing?
I’m creating a registration form and want to add the following conditions to the form:
• Name: can not be less than 3 letters.
• Address1 and address2: Both addresses should not be the same.
• Age: not less than 18 years.
• Height: not less than 130.
• Weight: not less than 30
But I do not know where to enter the if condition.
package com.signupform;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame
extends JFrame
implements ActionListener {
private Container c;
private JLabel title;
private JLabel name;
private JTextField tname;
private JLabel age;
private JTextField tage;
private JLabel height;
private JTextField theight;
private JLabel weight;
private JTextField tweight;
private JLabel address1;
private JTextField taddress1;
private JLabel add2;
private JTextField tadd2;
private JButton sub;
private JTextArea tout;
public MyFrame()
{
setTitle("Registration Form");
setBounds(300, 90, 900, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
getContentPane().setBackground(Color.lightGray);
c = getContentPane();
c.setLayout(null);
title = new JLabel("Registration Form");
title.setFont(new Font("Arial", Font.PLAIN, 30));
title.setBounds(300,30,300,30);
c.add(title);
name = new JLabel("Name");
name.setFont(new Font("Arial", Font.PLAIN, 20));
name.setBounds(50,100,100,20);
c.add(name);
tname = new JTextField();
tname.setFont(new Font("Arial", Font.PLAIN, 15));
tname.setBounds(150,100,190,20);
c.add(tname);
age = new JLabel("Age");
age.setFont(new Font("Arial", Font.PLAIN, 20));
age.setBounds(50,150,100,20);
c.add(age);
tage = new JTextField();
tage.setFont(new Font("Arial", Font.PLAIN, 15));
tage.setBounds(150,150,60,20);
c.add(tage);
height = new JLabel("Height");
height.setFont(new Font("Arial", Font.PLAIN, 20));
height.setBounds(50,200,100,20);
c.add(height);
theight = new JTextField();
theight.setFont(new Font("Arial", Font.PLAIN, 15));
theight.setBounds(150,200,60,20);
c.add(theight);
weight = new JLabel("Weight");
weight.setFont(new Font("Arial", Font.PLAIN, 20));
weight.setBounds(50,250,100,20);
c.add(weight);
tweight = new JTextField();
tweight.setFont(new Font("Arial", Font.PLAIN, 15));
tweight.setBounds(150,250,60,20);
c.add(tweight);
address1 = new JLabel("Address 1");
address1.setFont(new Font("Arial", Font.PLAIN, 20));
address1.setBounds(50,300,100,20);
c.add(address1);
taddress1 = new JTextField();
taddress1.setFont(new Font("Arial", Font.PLAIN, 15));
taddress1.setBounds(150,300,450,30);
c.add(taddress1);
add2 = new JLabel("Address 2");
add2.setFont(new Font("Arial", Font.PLAIN, 20));
add2.setBounds(50,350,100,20);
c.add(add2);
tadd2 = new JTextField();
tadd2.setFont(new Font("Arial", Font.PLAIN, 15));
tadd2.setBounds(150,350,450,30);
c.add(tadd2);
sub = new JButton("Submit");
sub.setFont(new Font("Arial", Font.PLAIN, 15));
sub.setBounds(150,420,100,30);
sub.addActionListener(this);
c.add(sub);
tout = new JTextArea();
tout.setFont(new Font("Arial", Font.PLAIN, 15));
tout.setBounds(500,80,300,200);
tout.setLineWrap(true);
tout.setEditable(false);
c.add(tout);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sub) {
String data1 = "Name : " + tname.getText() + "\n"
+ "Age : " + tage.getText() + "\n";
String data2 = "Height : " + theight.getText() + "\n"
+ "Weight : " + tweight.getText() + "\n";
String data3 = "Address 1 : " + taddress1.getText() + "\n"
+ "Address 2 : " + tadd2.getText();
tout.setText(data1 + data2 + data3 );
tout.setEditable(false);
}
}
}
class Registration {
public static void main(String[] args) throws Exception
{
MyFrame f = new MyFrame();
}
}
If statements can be placed inside actionPerformed() method.
In your case You can do,
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sub) {
if(Integer.parseInt(tname.getText().length()) > 3 &&
address1.getText() != address2.getText())
}
}
and goes...
I'm writing this code for university, to read the user input and calculate the charges (its a hospital bill)
But when I press calculate the JTextArea displays 0 as value
I'm very much a newbie so any guidance would be appreciated
the code is:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HospitalChargesCalculator extends JFrame implements ActionListener{
private JLabel hospitalStayLabel;
private JLabel medicationLabel;
private JLabel surgicalFeesLabel;
private JLabel labFeesLabel;
private JLabel rehabLabel;
private JLabel totalLabel;
private JTextField hospitalStayTF;
private JTextField medicationTF;
private JTextField surgicalFeesTF;
private JTextField labFeesTF;
private JTextField rehabTF;
private JTextArea totalChargesTA;
private JButton calculateB;
private JButton exitB;
public static final int WIDTH = 500;
public static final int HEIGHT = 350;
static int totalStayCharge;
static int totalMisc;
static int totalCharges;
static int totalDays;
static int totalMedication;
static int totalSurgical;
static int totalLab;
static int totalRehab;
public HospitalChargesCalculator() {
setTitle("Hospital Charges");
Container c = getContentPane();
setSize(WIDTH, HEIGHT);
c.setLayout(null);
hospitalStayLabel = new JLabel(" Number of days spent in hospital: ",
SwingConstants.LEFT);
medicationLabel = new JLabel(" Total Medication Charges: ",
SwingConstants.LEFT);
surgicalFeesLabel = new JLabel(" Total sugical charges : ",
SwingConstants.LEFT);
labFeesLabel = new JLabel(" Total lab fees: ",
SwingConstants.LEFT);
rehabLabel = new JLabel(" Total Rehab charges: ",
SwingConstants.LEFT);
totalLabel = new JLabel(" Total Charges: ",
SwingConstants.LEFT);
calculateB = new JButton("Calculate");
calculateB.addActionListener(this);
exitB = new JButton("Exit");
exitB.addActionListener(this);
hospitalStayTF = new JTextField();
medicationTF = new JTextField();
surgicalFeesTF = new JTextField();
labFeesTF = new JTextField();
rehabTF = new JTextField();
totalChargesTA = new JTextArea();
hospitalStayLabel.setSize(250, 30);
hospitalStayTF.setSize(200, 30);
medicationLabel.setSize(200, 30);
medicationTF.setSize(200, 30);
surgicalFeesLabel.setSize(200, 30);
surgicalFeesTF.setSize(200, 30);
labFeesLabel.setSize(200, 30);
labFeesTF.setSize(200, 30);
rehabLabel.setSize(200, 30);
rehabTF.setSize(200,30);
totalLabel.setSize(200, 30);
totalChargesTA.setSize(200,30);
calculateB.setSize(100, 30);
exitB.setSize(100, 30);
hospitalStayLabel.setLocation(30, 25);
hospitalStayTF.setLocation(250, 25);
medicationLabel.setLocation(30, 60);
medicationTF.setLocation(250, 60);
surgicalFeesLabel.setLocation(30, 95);
surgicalFeesTF.setLocation(250, 95);
labFeesLabel.setLocation(30, 130);
labFeesTF.setLocation(250, 130);
rehabLabel.setLocation(30, 165);
rehabTF.setLocation(250, 165);
totalLabel.setLocation(30, 250);
totalChargesTA.setLocation(250, 250);
calculateB.setLocation(70, 205);
exitB.setLocation(300, 205);
c.add(hospitalStayLabel);
c.add(hospitalStayTF);
c.add(medicationLabel);
c.add(medicationTF);
c.add(surgicalFeesLabel);
c.add(surgicalFeesTF);
c.add(labFeesLabel);
c.add(labFeesTF);
c.add(rehabLabel);
c.add(rehabTF);
c.add(totalLabel);
c.add(totalChargesTA);
c.add(calculateB);
c.add(exitB);
hospitalStayTF.addActionListener(this);
medicationTF.addActionListener(this);
surgicalFeesTF.addActionListener(this);
labFeesTF.addActionListener(this);
rehabTF.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformedGet(ActionEvent g)
{
totalDays = Integer.parseInt(hospitalStayTF.getText());
totalMedication = Integer.parseInt(medicationTF.getText());
totalSurgical = Integer.parseInt(surgicalFeesTF.getText());
totalLab = Integer.parseInt(labFeesTF.getText());
totalRehab = Integer.parseInt(rehabTF.getText());
}
public int CalcStayCharges()
{
int dailyCharge = 350;
totalStayCharge = totalDays * dailyCharge;
return totalStayCharge;
}
public int CalcMiscCharges()
{
totalMisc = (totalMedication + totalSurgical + totalLab + totalRehab);
return totalMisc;
}
public int CalcTotalCharges()
{
totalCharges = (totalStayCharge + totalMisc);
return totalCharges;
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Calculate"))
{
totalChargesTA.setText(String.valueOf(totalCharges));
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
public static void main(String[] args)
{
HospitalChargesCalculator hospCalc = new HospitalChargesCalculator();
}
}
if you press the button you simply execute actionPerformed(ActionEvent e), which only does totalChargesTA.setText(String.valueOf(totalCharges));. In order to get a value you should use any of your calculalationmethods before using the setText method.
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Calculate"))
{
totalCharges = CalcTotalCharges();
totalChargesTA.setText(String.valueOf(totalCharges));
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
it might be that you need to call some of the other methods aswell, if they are calculating the values that are used inside of CalcTotalCharges.
I cant comment yet, so here as an answer.
As said you dont actually call the function to calculate your total charges with totalChargesTA.setText(String.valueOf(totalCharges)); but instead try to directly access the variable totalCharges of your method CalcTotalCharges() (the method you should be calling here), this is only possible because you declared all your variables as static int so you can access them even in parts of your code where you dont actually want to access them.
Dont declare all your variables static, and you would have seen the error of not calling the methods. Think about which variables need to be static and reduce it to those.
Also dont declare all your variables you are going to use in just that one function in your class, inistead declare them in that function, so that you avoid the same error as with your static declarations.
-- Also, additionaly the answer provided by Subin Thomas that shows the principal error in your code, his solution wont work because he mixed up some of the functions and you also have to fix the function:
public int CalcTotalCharges()
{
totalCharges = (totalStayCharge + totalMisc);
return totalCharges;
}
Where you have the same kind of error to:
public int CalcTotalCharges()
{
totalCharges = (CalcStayCharges() + CalcMiscCharges());
return totalCharges;
}
EDIT: Actually you also have another error in the way you retrieve the values from you input textfields. Why did you use the method public void actionPerformedGet(ActionEvent g) ?
This wont work with your ActionListener. Instead copy the code in this function to your actionPerformed Method. Then it will actually work. For completeness here the working code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HospitalChargesCalculator extends JFrame implements ActionListener{
private JLabel hospitalStayLabel;
private JLabel medicationLabel;
private JLabel surgicalFeesLabel;
private JLabel labFeesLabel;
private JLabel rehabLabel;
private JLabel totalLabel;
private JTextField hospitalStayTF;
private JTextField medicationTF;
private JTextField surgicalFeesTF;
private JTextField labFeesTF;
private JTextField rehabTF;
private JTextArea totalChargesTA;
private JButton calculateB;
private JButton exitB;
public static final int WIDTH = 500;
public static final int HEIGHT = 350;
int totalDays;
int totalMedication;
int totalSurgical;
int totalLab;
int totalRehab;
public HospitalChargesCalculator() {
setTitle("Hospital Charges");
Container c = getContentPane();
setSize(WIDTH, HEIGHT);
c.setLayout(null);
hospitalStayLabel = new JLabel(" Number of days spent in hospital: ",
SwingConstants.LEFT);
medicationLabel = new JLabel(" Total Medication Charges: ",
SwingConstants.LEFT);
surgicalFeesLabel = new JLabel(" Total sugical charges : ",
SwingConstants.LEFT);
labFeesLabel = new JLabel(" Total lab fees: ",
SwingConstants.LEFT);
rehabLabel = new JLabel(" Total Rehab charges: ",
SwingConstants.LEFT);
totalLabel = new JLabel(" Total Charges: ",
SwingConstants.LEFT);
calculateB = new JButton("Calculate");
calculateB.addActionListener(this);
exitB = new JButton("Exit");
exitB.addActionListener(this);
hospitalStayTF = new JTextField();
medicationTF = new JTextField();
surgicalFeesTF = new JTextField();
labFeesTF = new JTextField();
rehabTF = new JTextField();
totalChargesTA = new JTextArea();
hospitalStayLabel.setSize(250, 30);
hospitalStayTF.setSize(200, 30);
medicationLabel.setSize(200, 30);
medicationTF.setSize(200, 30);
surgicalFeesLabel.setSize(200, 30);
surgicalFeesTF.setSize(200, 30);
labFeesLabel.setSize(200, 30);
labFeesTF.setSize(200, 30);
rehabLabel.setSize(200, 30);
rehabTF.setSize(200,30);
totalLabel.setSize(200, 30);
totalChargesTA.setSize(200,30);
calculateB.setSize(100, 30);
exitB.setSize(100, 30);
hospitalStayLabel.setLocation(30, 25);
hospitalStayTF.setLocation(250, 25);
medicationLabel.setLocation(30, 60);
medicationTF.setLocation(250, 60);
surgicalFeesLabel.setLocation(30, 95);
surgicalFeesTF.setLocation(250, 95);
labFeesLabel.setLocation(30, 130);
labFeesTF.setLocation(250, 130);
rehabLabel.setLocation(30, 165);
rehabTF.setLocation(250, 165);
totalLabel.setLocation(30, 250);
totalChargesTA.setLocation(250, 250);
calculateB.setLocation(70, 205);
exitB.setLocation(300, 205);
c.add(hospitalStayLabel);
c.add(hospitalStayTF);
c.add(medicationLabel);
c.add(medicationTF);
c.add(surgicalFeesLabel);
c.add(surgicalFeesTF);
c.add(labFeesLabel);
c.add(labFeesTF);
c.add(rehabLabel);
c.add(rehabTF);
c.add(totalLabel);
c.add(totalChargesTA);
c.add(calculateB);
c.add(exitB);
hospitalStayTF.addActionListener(this);
medicationTF.addActionListener(this);
surgicalFeesTF.addActionListener(this);
labFeesTF.addActionListener(this);
rehabTF.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public int CalcStayCharges()
{
int dailyCharge = 350;
int totalStayCharge = totalDays * dailyCharge;
return totalStayCharge;
}
public int CalcMiscCharges()
{
int totalMisc = (totalMedication + totalSurgical + totalLab + totalRehab);
return totalMisc;
}
public int CalcTotalCharges()
{
int totalCharges = (CalcStayCharges() + CalcMiscCharges());
return totalCharges;
}
public void actionPerformed(ActionEvent e)
{
totalDays = Integer.parseInt(hospitalStayTF.getText());
totalMedication = Integer.parseInt(medicationTF.getText());
totalSurgical = Integer.parseInt(surgicalFeesTF.getText());
totalLab = Integer.parseInt(labFeesTF.getText());
totalRehab = Integer.parseInt(rehabTF.getText());
if (e.getActionCommand().equals("Calculate"))
{
totalChargesTA.setText(CalcTotalCharges()+"");
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
public static void main(String[] args)
{
HospitalChargesCalculator hospCalc = new HospitalChargesCalculator();
}
}
I've been working at this problem for hours now, with no results. I cannot seem to get the applet to display properly when viewing the HTML page OR when running the applet through Eclipse. It is always blank. I've been searching for a long time now and decided just to ask.
Here's the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet{
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public JPanel createContentPane(){
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
//posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
topicGUI.add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150,25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
postPanel.add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70,15);
username.setHorizontalAlignment(0);
postPanel.add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40,15);
topic.setHorizontalAlignment(0);
postPanel.add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70,15);
paragraph.setHorizontalAlignment(0);
postPanel.add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
postPanel.add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
postPanel.add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane (paragraphArea);
scrollParagraph.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
postPanel.add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal + "/n" + paragraphArea + "/n";
}
});
postPanel.add(submitButton);
setVisible(true);
return topicGUI;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("");
Topics display = new Topics();
frame.setContentPane(display.createContentPane());
frame.setSize(500, 270);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
In order to run as an applet, you need to override the init method. You don't need a main method. Just add all you components inside the init method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet {
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public void init() {
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
// posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150, 25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70, 15);
username.setHorizontalAlignment(0);
add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40, 15);
topic.setHorizontalAlignment(0);
add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70, 15);
paragraph.setHorizontalAlignment(0);
add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane(paragraphArea);
scrollParagraph
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal
+ "/n" + paragraphArea + "/n";
}
});
add(submitButton);
}
}
I am having a lot of issues with this application. I have been at this all day and cannot get this figured out. I have a Java application that is for a class. The issue that I am having is trying to get the JRadioButtons assigned to variables in the array then passing them into the formula. If someone could help I would appreciate it a lot.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JRadioButton;
public class MortgageCalculatorGUI8 extends JFrame {
JPanel panel1 = new JPanel();
double Principal;
double [] Interest = {5.35, 5.5, 5.75};
double temp_Interest;
int [] Length = {7, 15, 30};
int temp_Length;
boolean ok = false;
public MortgageCalculatorGUI8(){
getContentPane ().setLayout (null);
setSize (400,400);
panel1.setLayout (null);
panel1.setBounds (0, 0, 2000, 800);
add (panel1);
JLabel mortgageLabel = new JLabel("Mortgage Amount $", JLabel.LEFT);
mortgageLabel.setBounds (15, 15, 150, 30);
panel1.add (mortgageLabel);
final JTextField mortgageText = new JTextField(10);
mortgageText.setBounds (130, 15, 150, 30);
panel1.add (mortgageText);
JLabel termLabel = new JLabel("Mortgage Term (Years)", JLabel.LEFT);
termLabel.setBounds (340, 40, 150, 30);
panel1.add (termLabel);
JTextField termText = new JTextField(3);
termText.setBounds (340, 70, 150, 30);
panel1.add (termText);
JLabel intRateLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
intRateLabel.setBounds (340, 94, 150, 30);
panel1.add (intRateLabel);
JTextField intRateText = new JTextField(5);
intRateText.setBounds (340, 120, 150, 30);
panel1.add (intRateText);
JLabel mPaymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
mPaymentLabel.setBounds (550, 40, 150, 30);
panel1.add (mPaymentLabel);
JTextField mPaymentText = new JTextField(10);
mPaymentText.setBounds (550, 70, 150, 30);
panel1.add (mPaymentText);
// JLabel paymentLabel = new JLabel ("Payment #");
// JLabel balLabel = new JLabel (" Balance");
// JLabel ytdPrincLabel = new JLabel (" Principal");
// JLabel ytdIntLabel = new JLabel (" Interest");
JTextArea textArea = new JTextArea(10, 31);
textArea.setBounds (550, 100, 150, 30);
panel1.add (textArea);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds (450, 200, 300, 150);
panel1.add (scroll);
public void rbuttons(){
JLabel tYears = new JLabel("Years of Loan Amount");
tYears.setBounds (30, 35, 150, 30);
panel1.add (tYears);
JRadioButton b7Yr = new JRadioButton("7 Years",false);
b7Yr.setBounds (30, 58, 150, 30);
panel1.add (b7Yr);
JRadioButton b15Yr = new JRadioButton("15 Years",false);
b15Yr.setBounds (30, 80, 150, 30);
panel1.add (b15Yr);
JRadioButton b30Yr = new JRadioButton("30 Years",false);
b30Yr.setBounds (30, 101, 150, 30);
panel1.add (b30Yr);
JLabel tInterest = new JLabel("Interest Rate Of the Loan");
tInterest.setBounds (175, 35, 150, 30);
panel1.add(tInterest);
JRadioButton b535Int = new JRadioButton("5.35% Interest",false);
b535Int.setBounds (178, 58, 150, 30);
panel1.add (b535Int);
JRadioButton b55Int = new JRadioButton("5.5% Interest",false);
b55Int.setBounds (178, 80, 150, 30);
panel1.add (b55Int);
JRadioButton b575Int = new JRadioButton("5.75% Interest",false);
b575Int.setBounds (178, 101, 150, 30);
panel1.add (b575Int);
}
JButton calculateButton = new JButton("CALCULATE");
calculateButton.setBounds (30, 400, 120, 30);
panel1.add (calculateButton);
calculateButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(e.getSource () == b7Yr){
b7Yr = Length[0];
}
if(e.getSource () == b15Yr){
b15Yr = Length[1];
}
if(e.getSource () == b30Yr){
b30Yr = Length[2];
}
if(e.getSource () == b535Int){
b535Int = Interest[0];
}
if(e.getSource () == b55Int){
b55Int = Interest[1];
}
if(e.getSource () == b575Int){
b575Int = Interest[2];
}
double Principal;
// double [] Interest;
// int [] Length;
double M_Interest = Interest /(12*100);
double Months = Length * 12;
Principal = Double.parseDouble (mortgageText.getText());
double M_Payment = Principal * ( M_Interest / (1 - (Math.pow((1 + M_Interest), - Months))));
NumberFormat Money = NumberFormat.getCurrencyInstance();
}
});
JButton clearButton = new JButton("CLEAR");
clearButton.setBounds (160, 400, 120, 30);
panel1.add (clearButton);
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
mortgageText.setText (null);
b7Yr.setSelected (false);
b15Yr.setSelected (false);
b30Yr.setSelected (false);
b535Int.setSelected (false);
b55Int.setSelected (false);
b575Int.setSelected (false);
}
});
JButton exitButton = new JButton("EXIT");
exitButton.setBounds (290, 400, 120, 30);
panel1.add (exitButton);
exitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args) {
MortgageCalculatorGUI8 frame = new MortgageCalculatorGUI8();
frame.setBounds (400, 200, 800, 800);
frame.setTitle ("Mortgage Calculator 1.0.4");
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
frame.setVisible (true);
}
}
Shoot, I'll show you in an example of what I meant in my last comment:
Myself, I'd create an array of JRadioButtons as a class field for each group that I used as well as a ButtonGroup object for each cluster of JRadioButtons. Then in my calculate JButton's ActionListener, I'd get the selected radiobutton by either looping through the radio button array or from the ButtonGroups getSelection method (note though that this returns a ButtonModel object or null if nothing is selected).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InfoFromRadioBtns extends JPanel {
private static final long serialVersionUID = 1L;
private int[] foobars = {1, 2, 5, 10, 20};
private JRadioButton[] foobarRButtons = new JRadioButton[foobars.length];
private ButtonGroup foobarBtnGroup = new ButtonGroup();
public InfoFromRadioBtns() {
// jpanel to hold one set of radio buttons
JPanel radioBtnPanel = new JPanel(new GridLayout(0, 1));
radioBtnPanel.setBorder(BorderFactory
.createTitledBorder("Choose a Foobar"));
// iterate through the radio button array creating buttons
// and adding them to the radioBtnPanel and the
// foobarBtnGroup ButtonGroup
for (int i = 0; i < foobarRButtons.length; i++) {
// string for radiobutton to dislay -- just the number
String buttonText = String.valueOf(foobars[i]);
JRadioButton radiobtn = new JRadioButton("foobar " + buttonText);
radiobtn.setActionCommand(buttonText); // one way to find out which
// button is selected
radioBtnPanel.add(radiobtn); // add radiobutton to its panel
foobarBtnGroup.add(radiobtn); // add radiobutton to its button group
// add to array
foobarRButtons[i] = radiobtn;
}
// one way to get the selected JRadioButton
JButton getRadioChoice1 = new JButton("Get Radio Choice 1");
getRadioChoice1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel seletedModel = foobarBtnGroup.getSelection();
if (seletedModel != null) {
String actionCommand = seletedModel.getActionCommand();
System.out.println("selected foobar: " + actionCommand);
} else {
System.out.println("No foobar selected");
}
}
});
// another way to get the selected JRadioButton
JButton getRadioChoice2 = new JButton("Get Radio Choice 2");
getRadioChoice2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String actionCommand = "";
for (JRadioButton foobarRButton : foobarRButtons) {
if (foobarRButton.isSelected()) {
actionCommand = foobarRButton.getActionCommand();
}
}
if (actionCommand.isEmpty()) {
System.out.println("No foobar selected");
} else {
System.out.println("selected foobar: " + actionCommand);
}
}
});
JPanel jBtnPanel = new JPanel();
jBtnPanel.add(getRadioChoice1);
jBtnPanel.add(getRadioChoice2);
// make main GUI use a BordeLayout
setLayout(new BorderLayout());
add(radioBtnPanel, BorderLayout.CENTER);
add(jBtnPanel, BorderLayout.PAGE_END);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("InfoFromRadioBtns");
frame.getContentPane().add(new InfoFromRadioBtns());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Whatever you do, don't try to copy and paste any of this code into your program, because it simply isn't going to work that way (on purpose). It was posted only to illustrate the concepts that I've discussed above.
I would extend JRadioButton to create a class capable of holding the variables you want. You can do this as an inner class to keep things simple.
private double pctinterest;
private int numyears; // within scope of your containing class
private class RadioButtonWithYears extends JRadioButton {
final private int years;
private int getYears() { return years; }
public RadioButtonWithYears(int years) {
super(years + " years",false);
this.years = years;
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
numyears = getYears();
}
});
}
}
// elsewhere
RadioButtonWithYears b7Yr = new RadioButtonWithYears(7);
RadioButtonWithYears b15Yr = new RadioButtonWithYears(15);
RadioButtonWithYears b30Yr = new RadioButtonWithYears(30);
// then later
double M_Interest = java.lang.Math.pow((pctinternet / 100)+1, numyears);
Update: It isn't too far gone to salvage. I have incorporated the ButtonGroup as per Eels suggestion, and made the GUI part of it work (although you'll have to fix the layout) and marked where you need to sort out the calculation.
package stack.swing;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JRadioButton;
public class MortgageCalculatorGUI8 extends JFrame {
JPanel panel1 = new JPanel();
Integer Principal;
boolean ok = false;
private BigDecimal temp_Interest;
private int temp_Length; // within scope of your containing class
private class JRadioButtonWithYears extends JRadioButton {
final private int years;
private int getYears() { return years; }
public JRadioButtonWithYears(int years) {
super(years + " years",false);
this.years = years;
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
temp_Length = getYears();
}
});
}
}
private class JRadioButtonWithPct extends JRadioButton {
final private BigDecimal pct;
private BigDecimal getPct() { return pct; }
public JRadioButtonWithPct(String pct) {
super(pct + "%",false);
this.pct = new BigDecimal(pct);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
temp_Interest = getPct();
}
});
}
}
public MortgageCalculatorGUI8() {
getContentPane ().setLayout (null);
setSize (400,400);
panel1.setLayout (null);
panel1.setBounds (0, 0, 2000, 800);
add (panel1);
JLabel mortgageLabel = new JLabel("Mortgage Amount $", JLabel.LEFT);
mortgageLabel.setBounds (15, 15, 150, 30);
panel1.add (mortgageLabel);
final JTextField mortgageText = new JTextField(10);
mortgageText.setBounds (130, 15, 150, 30);
panel1.add (mortgageText);
JLabel termLabel = new JLabel("Mortgage Term (Years)", JLabel.LEFT);
termLabel.setBounds (340, 40, 150, 30);
panel1.add (termLabel);
JTextField termText = new JTextField(3);
termText.setBounds (340, 70, 150, 30);
panel1.add (termText);
JLabel intRateLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
intRateLabel.setBounds (340, 94, 150, 30);
panel1.add (intRateLabel);
JTextField intRateText = new JTextField(5);
intRateText.setBounds (340, 120, 150, 30);
panel1.add (intRateText);
JLabel mPaymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
mPaymentLabel.setBounds (550, 40, 150, 30);
panel1.add (mPaymentLabel);
JTextField mPaymentText = new JTextField(10);
mPaymentText.setBounds (550, 70, 150, 30);
panel1.add (mPaymentText);
// JLabel paymentLabel = new JLabel ("Payment #");
// JLabel balLabel = new JLabel (" Balance");
// JLabel ytdPrincLabel = new JLabel (" Principal");
// JLabel ytdIntLabel = new JLabel (" Interest");
JTextArea textArea = new JTextArea(10, 31);
textArea.setBounds (550, 100, 150, 30);
panel1.add (textArea);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds (450, 200, 300, 150);
panel1.add (scroll);
// jpanel to hold one set of radio buttons
JPanel yearsPanel = new JPanel(new GridLayout(0, 1));
yearsPanel.setBorder(BorderFactory
.createTitledBorder("Years of Loan Amount"));
yearsPanel.setBounds(30, 55, 150, 150);
panel1.add (yearsPanel);
final ButtonGroup yearsGroup = new ButtonGroup();
int years[] = { 7, 15, 30 };
for (int i = 0; i < years.length; i++) {
JRadioButtonWithYears radiobtn = new JRadioButtonWithYears(years[i]);
yearsPanel.add(radiobtn); // add radiobutton to its panel
yearsGroup.add(radiobtn); // add radiobutton to its button group
}
// jpanel to hold one set of radio buttons
JPanel pctPanel = new JPanel(new GridLayout(0, 1));
pctPanel.setBorder(BorderFactory
.createTitledBorder("Interest Rate Of the Loan"));
pctPanel.setBounds(175, 55, 180, 150);
panel1.add (pctPanel);
final ButtonGroup pctGroup = new ButtonGroup();
String pct[] = { "5.35", "5.5", "5.75" };
for (int i = 0; i < pct.length; i++) {
JRadioButtonWithPct radiobtn = new JRadioButtonWithPct(pct[i]);
pctPanel.add(radiobtn); // add radiobutton to its panel
pctGroup.add(radiobtn); // add radiobutton to its button group
}
final JButton calculateButton = new JButton("CALCULATE");
calculateButton.setBounds (30, 400, 120, 30);
panel1.add (calculateButton);
calculateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double M_Interest = temp_Interest.doubleValue() /(12*100);
double Months = temp_Length * 12;
Principal = Integer.parseInt(mortgageText.getText());
double M_Payment = Principal * ( M_Interest / (1 - (Math.pow((1 + M_Interest), - Months))));
NumberFormat Money = NumberFormat.getCurrencyInstance();
/** MORE STUFF TO HAPPEN HERE */
}
});
JButton clearButton = new JButton("CLEAR");
clearButton.setBounds (160, 400, 120, 30);
panel1.add (clearButton);
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mortgageText.setText (null);
yearsGroup.clearSelection();
pctGroup.clearSelection();
}
});
JButton exitButton = new JButton("EXIT");
exitButton.setBounds (290, 400, 120, 30);
panel1.add (exitButton);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
MortgageCalculatorGUI8 frame = new MortgageCalculatorGUI8();
frame.setBounds (400, 200, 800, 800);
frame.setTitle ("Mortgage Calculator 1.0.4");
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
frame.setVisible (true);
}
}
I was wondering if it is in JAVA to write the calculated data to a text file. My JAVA code is a GUI based gpa calculator. I just want to add a JButton & ActionListener that will write the Class Name, GPA Points, and calculated GPA to a .txt file.
Here is my JFrame Driver Code:
import javax.swing.JFrame;
public class Driver00
{
public static void main(String[] args)
{
/*
* Create a frame (outside box) and write what text
* will be displayed as the frame title
*/
JFrame frame = new JFrame("PHILIP MCQUITTY");
// give frame a size
frame.setSize(520, 375);
// set location on the computer screen will frame appear
frame.setLocation(400, 166);
// use this so when you press X in corner, frame will close
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add your panel to the frame. name must match Panel class name
frame.setContentPane(new GpaCalc());
// frame.setResizable(false);
// always include
frame.setVisible(true);
}
}
Here is my JPanel Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GpaCalc extends JPanel {
private JLabel GPALabel, c1, c2, c3, c4, c5, c6, c7, g1, g2, g3, g4, g5, g6, g7;
private JTextField Class1, Class2, Class3, Class4, Class5, Class6, Class7, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6, Grade7;
private double GPA1, GPA2, GPA3, GPA4, GPA5, GPA6, GPA7, GPA, BigDec;
public GpaCalc() {
setLayout(new FlowLayout());
// Class Labels
GPALabel = new JLabel("0.00000000000000");
GPALabel.setFont(new Font("Times New Roman", Font.BOLD, 60));
GPALabel.setForeground(Color.red);
c1 = new JLabel("Block 1");
c1.setFont(new Font("Times New Roman", Font.BOLD, 20));
c1.setForeground(Color.black);
c2 = new JLabel("Block 2");
c2.setFont(new Font("Times New Roman", Font.BOLD, 20));
c2.setForeground(Color.black);
c3 = new JLabel("Block 3");
c3.setFont(new Font("Times New Roman", Font.BOLD, 20));
c3.setForeground(Color.black);
c4 = new JLabel("Block 4");
c4.setFont(new Font("Times New Roman", Font.BOLD, 20));
c4.setForeground(Color.black);
c5 = new JLabel("Block 5");
c5.setFont(new Font("Times New Roman", Font.BOLD, 20));
c5.setForeground(Color.black);
c6 = new JLabel("Block 6");
c6.setFont(new Font("Times New Roman", Font.BOLD, 20));
c6.setForeground(Color.black);
c7 = new JLabel("Block 7");
c7.setFont(new Font("Times New Roman", Font.BOLD, 20));
c7.setForeground(Color.black);
// Grade Labels
g1 = new JLabel("GPA Points");
g1.setFont(new Font("Times New Roman", Font.BOLD, 20));
g1.setForeground(Color.black);
g2 = new JLabel("GPA Points");
g2.setFont(new Font("Times New Roman", Font.BOLD, 20));
g2.setForeground(Color.black);
g3 = new JLabel("GPA Points");
g3.setFont(new Font("Times New Roman", Font.BOLD, 20));
g3.setForeground(Color.black);
g4 = new JLabel("GPA Points");
g4.setFont(new Font("Times New Roman", Font.BOLD, 20));
g4.setForeground(Color.black);
g5 = new JLabel("GPA Points");
g5.setFont(new Font("Times New Roman", Font.BOLD, 20));
g5.setForeground(Color.black);
g6 = new JLabel("GPA Points");
g6.setFont(new Font("Times New Roman", Font.BOLD, 20));
g6.setForeground(Color.black);
g7 = new JLabel("GPA Points");
g7.setFont(new Font("Times New Roman", Font.BOLD, 20));
g7.setForeground(Color.black);
// Class Textfields
Class1 = new JTextField("Enter Class Name", 10);
Class1.setHorizontalAlignment(SwingConstants.CENTER);
Class2 = new JTextField("Enter Class Name", 10);
Class2.setHorizontalAlignment(SwingConstants.CENTER);
Class3 = new JTextField("Enter Class Name", 10);
Class3.setHorizontalAlignment(SwingConstants.CENTER);
Class4 = new JTextField("Enter Class Name", 10);
Class4.setHorizontalAlignment(SwingConstants.CENTER);
Class5 = new JTextField("Enter Class Name", 10);
Class5.setHorizontalAlignment(SwingConstants.CENTER);
Class6 = new JTextField("Enter Class Name", 10);
Class6.setHorizontalAlignment(SwingConstants.CENTER);
Class7 = new JTextField("Enter Class Name", 10);
Class7.setHorizontalAlignment(SwingConstants.CENTER);
// Grade Textfields
Grade1 = new JTextField("0.0", 10);
Grade1.setHorizontalAlignment(SwingConstants.CENTER);
Grade2 = new JTextField("0.0", 10);
Grade2.setHorizontalAlignment(SwingConstants.CENTER);
Grade3 = new JTextField("0.0", 10);
Grade3.setHorizontalAlignment(SwingConstants.CENTER);
Grade4 = new JTextField("0.0", 10);
Grade4.setHorizontalAlignment(SwingConstants.CENTER);
Grade5 = new JTextField("0.0", 10);
Grade5.setHorizontalAlignment(SwingConstants.CENTER);
Grade6 = new JTextField("0.0", 10);
Grade6.setHorizontalAlignment(SwingConstants.CENTER);
Grade7 = new JTextField("0.0", 10);
Grade7.setHorizontalAlignment(SwingConstants.CENTER);
// Button(s)
JButton Calculate = new JButton("Calculate");
Calculate.addActionListener(new Listener());
JButton Reset = new JButton("Reset Fields");
Reset.addActionListener(new Listener2());
// Add(s)
add(GPALabel);
add(c1);
add(Class1);
add(Grade1);
add(g1);
add(c2);
add(Class2);
add(Grade2);
add(g2);
add(c3);
add(Class3);
add(Grade3);
add(g3);
add(c4);
add(Class4);
add(Grade4);
add(g4);
add(c5);
add(Class5);
add(Grade5);
add(g5);
add(c6);
add(Class6);
add(Grade6);
add(g6);
add(c7);
add(Class7);
add(Grade7);
add(g7);
add(Calculate);
add(Reset);
}
// Action Listener(s)
private class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
GPA1 = Double.parseDouble(Grade1.getText());
GPA2 = Double.parseDouble(Grade2.getText());
GPA3 = Double.parseDouble(Grade3.getText());
GPA4 = Double.parseDouble(Grade4.getText());
GPA5 = Double.parseDouble(Grade5.getText());
GPA6 = Double.parseDouble(Grade6.getText());
GPA7 = Double.parseDouble(Grade7.getText());
GPA = (GPA1 + GPA2 + GPA3 + GPA4 + GPA5 + GPA6 + GPA7) / 7;
GPALabel.setText("" + GPA);
}
}
private class Listener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
Class1.setText("Enter Class Name");
Class2.setText("Enter Class Name");
Class3.setText("Enter Class Name");
Class4.setText("Enter Class Name");
Class5.setText("Enter Class Name");
Class6.setText("Enter Class Name");
Class7.setText("Enter Class Name");
Grade1.setText("0.0");
Grade2.setText("0.0");
Grade3.setText("0.0");
Grade4.setText("0.0");
Grade5.setText("0.0");
Grade6.setText("0.0");
Grade7.setText("0.0");
GPALabel.setText("0.00000000000000");
}
}
}
check java I/O api. Below is an example of writing data to file.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./output.txt"));
writer.write("your data here");
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
PrintWriter pw = new PrintWriter(new FileWriter("c:\\output.txt");
pw.println("The value is: " + x);
pw.close();
import java.io.*;
class code{
public static void main(String args[]){
try{
File r = new File("C:\\hello.txt");
FileWriter pw = new FileWriter(r);
PrintWriter pr = new PrintWriter(pw);
pr.println("Hello world");
}catch(IOException e){}
}
}