I am trying to create a GUI app were the user inputs an, item name, price, and discount rate. The button should calculate the two numbers and display the discount price. I am stuck on the action listener and making it preform the action/calculation correctly.
I am a pretty novice Java developer, so any guidance is greatly appriciated. If someone could just provide a little insight in the right direction. I am pretty sure i'm heading in the right direction just not sure what I'm missing to make it work properly. My code is error free, compiles, and runs fine.
/*
*
*
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* @author Ash
*/
public class myGUI extends JFrame {
public myGUI() {
super("Retail Calculator");
setLookAndFeel();
JFrame frame = new JFrame();
FlowLayout flow = new FlowLayout();
frame.setLayout(flow);
frame.setSize(350, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = getContentPane();
JPanel panel1 = new JPanel();
JLabel dlabel = new JLabel("Item Department:");
String[] department = {"Women", "Men", "Boys", "Girls", "Infant"};
JComboBox dept = new JComboBox(department);
panel1.add(dlabel);
panel1.add(dept);
dept.setSelectedIndex(2);
JPanel panel2 = new JPanel(new GridLayout(0, 2));
JLabel item = new JLabel("Item name:");
JTextField itemfield = new JTextField(10);
panel2.add(item);
panel2.add(itemfield);
JPanel panel3 = new JPanel(new GridLayout(0, 2));
JLabel price = new JLabel("Item price:");
final JTextField pricefield = new JTextField(8);
panel3.add(price);
panel3.add(pricefield);
JPanel panel4 = new JPanel(new GridLayout(0, 2));
JLabel discount = new JLabel("Item Discount:");
final JTextField discountfield = new JTextField(8);
panel4.add(discount);
panel4.add(discountfield);
JPanel panel5 = new JPanel(new FlowLayout());
final JButton calc = new JButton("Calculate Discount");
calc.setEnabled(true);
calc.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
double p= Double.parseDouble(pricefield.getText());
double d= Double.parseDouble(discountfield.getText());
double sum=0;
while(p < sum && d < sum){
sum=p*d;
calc.setText(sum);
}
}
});
panel5.add(calc);
container.add(panel2, BorderLayout.NORTH);
container.add(panel3, BorderLayout.CENTER);
container.add(panel4, BorderLayout.SOUTH);
frame.add(panel1);
frame.add(container);
frame.add(panel5);
frame.setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException exc) {
}
}
public static void main(String[] args) {
myGUI g = new myGUI();
}
}