I've built a program (which runs fine), but I really wanted to use JList instead of radio buttons. The problem is, I'm having a horrible time trying to do this and I end up with a mess of errors and a dysfunctional program. If anyone could provide any examples of how lists are properly used in Java, it would be greatly appreciated! I've not posted my program, as I'm not looking for answers, just general advice on JList. Thanks for those who have suggested the tutorial link - it helped out! :)
If anyone could provide any examples of how lists are properly used in Java
Read the JList API and follow the link titled How to Use Lists to the Swing tutorial which contains working examples.
Other comments:
Don't use setBounds() to size/position components. Swing was designed to be used with layout managers for too many reasons to list here. The Swing tutorial also has a section on layout managers.
Don't use a KeyListner. That is an old approach when using AWT. Swing has better API's. In this case you would add a DocumentListener to the Document of the text field. Again the tutorial has a section on how to write a DocumentListener.
Keep the tutorial link handy, it will help solve many problems.
I have done something with your code have look
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class PizzaOrder extends JFrame implements ActionListener, KeyListener, ListSelectionListener {
double smallPizzaPrice = 7.00, mediumPizzaPrice = 9.00,
largePizzaPrice = 11.00;
double sausage = 1.00, ham = 1.00, pineapple = 1.00, mushroom = 1.00,
pepperoni = 1.00;
JLabel lab1, lab2, lab3, toppers, lab4, lab5;
Button button;
JTextField text1, text2;
ButtonGroup group;
JRadioButton small, medium, large;
JCheckBox chk1, chk2, chk3, chk4, chk5;
JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
JList jList1 = new javax.swing.JList();
DefaultListModel modellist=new DefaultListModel();
PizzaOrder() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
lab1 = new JLabel("Name: ");
lab2 = new JLabel("Quantity: ");
lab3 = new JLabel("How hungry are you?");
lab3.setForeground(Color.BLUE);
lab3.setFont(new Font("Arial", Font.BOLD, 14));
toppers = new JLabel("Add some toppings : ");
toppers.setForeground(new Color(0, 0, 205));
toppers.setFont(new Font("Arial", Font.ITALIC, 14));
lab4 = new JLabel("Total: ");
lab4.setForeground(Color.RED);
lab4.setFont(new Font("Arial", Font.BOLD, 14));
lab5 = new JLabel("$0.00");
lab5.setForeground(Color.RED);
text1 = new JTextField(20);
text2 = new JTextField(20);
text2.setText("");
small = new JRadioButton("Small", true);
medium = new JRadioButton("Medium", false);
large = new JRadioButton("Large", false);
group = new ButtonGroup();
group.add(small);
group.add(medium);
group.add(large);
chk1 = new JCheckBox("Mushroom", false);
chk2 = new JCheckBox("Ham", false);
chk3 = new JCheckBox("Pepperoni", false);
chk4 = new JCheckBox("Sausage", false);
chk5 = new JCheckBox("Pineapple", false);
modellist.addElement("Small");
modellist.addElement("Medium");
modellist.addElement("Large");
jList1.setModel(modellist);
button = new Button("Order Now");
small.addActionListener(this);
medium.addActionListener(this);
large.addActionListener(this);
chk1.addActionListener(this);
chk2.addActionListener(this);
chk3.addActionListener(this);
chk4.addActionListener(this);
chk5.addActionListener(this);
text2.addKeyListener(this);
button.addActionListener(this);
jList1.addListSelectionListener(this);
lab1.setBounds(50, 50, 200, 20);
lab2.setBounds(50, 90, 200, 20);
text1.setBounds(200, 50, 200, 20);
text2.setBounds(200, 90, 200, 20);
lab3.setBounds(50, 170, 500, 20);
small.setBounds(300, 170, 100, 20);
medium.setBounds(400, 170, 100, 20);
large.setBounds(500, 170, 100, 20);
toppers.setBounds(50, 200, 300, 20);
chk1.setBounds(50, 230, 200, 20);
chk2.setBounds(50, 260, 200, 20);
chk3.setBounds(50, 290, 200, 20);
chk4.setBounds(50, 320, 200, 20);
chk5.setBounds(50, 350, 200, 20);
lab4.setBounds(50, 550, 400, 40);
lab5.setBounds(200, 550, 500, 40);
jScrollPane1.setBounds(300, 270, 200, 300);
jScrollPane1.setViewportView(jList1);
button.setBounds(50, 600, 100, 20);
add(lab1);
add(lab2);
add(text1);
add(text2);
add(lab3);
add(small);
add(medium);
add(large);
add(toppers);
add(chk1);
add(chk2);
add(chk3);
add(chk4);
add(chk5);
add(lab4);
add(lab5);
add(button);
add(jScrollPane1);
text2.selectAll();
setVisible(true);
setSize(800, 700);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
try {
Integer.parseInt(text2.getText());
} catch (NumberFormatException fe) {
text2.setText("");
}
refreshPrice();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
JOptionPane.showMessageDialog(this, "Hi " + text1.getText() + ", thanks for ordering with us!"
+ "\n\nYour pizza's in the oven. ",
"Orders Confirmed", JOptionPane.INFORMATION_MESSAGE);
}
refreshPrice();
}
private void refreshPrice() {
double price = 0;
int numOfPizzas = Integer.parseInt(text2.getText());
NumberFormat numberForm = NumberFormat.getNumberInstance();
DecimalFormat moneyForm = (DecimalFormat) numberForm;
moneyForm.applyPattern("0.00");
if (small.isSelected()) {
price += smallPizzaPrice * numOfPizzas;
}
if (medium.isSelected()) {
price += mediumPizzaPrice * numOfPizzas;
}
if (large.isSelected()) {
price += largePizzaPrice * numOfPizzas;
}
if (chk1.isSelected()) {
price += mushroom * numOfPizzas;
}
if (chk2.isSelected()) {
price += sausage * numOfPizzas;
}
if (chk3.isSelected()) {
price += pineapple * numOfPizzas;
}
if (chk4.isSelected()) {
price += pepperoni * numOfPizzas;
}
if (chk5.isSelected()) {
price += ham * numOfPizzas;
}
lab5.setText("$" + moneyForm.format(price));
}
public static void main(String[] args) {
#SuppressWarnings("unused")
PizzaOrder order = new PizzaOrder();
}
#Override
public void valueChanged(ListSelectionEvent e) {
double price = 0;
int numOfPizzas = Integer.parseInt(text2.getText());
NumberFormat numberForm = NumberFormat.getNumberInstance();
DecimalFormat moneyForm = (DecimalFormat) numberForm;
moneyForm.applyPattern("0.00");
System.out.println(jList1.getSelectedIndex());
if(jList1.getSelectedIndex()==0) {
price += smallPizzaPrice * numOfPizzas;
}
if(jList1.getSelectedIndex()==1) {
price += mediumPizzaPrice * numOfPizzas;
}
if(jList1.getSelectedIndex()==2) {
price += largePizzaPrice * numOfPizzas;
}
lab5.setText("$" + moneyForm.format(price));
}
}
Related
I have made software in Java that generates random number in range. But it don't work. Sorry for strange language and comments. I have three classes: main, for generating and GUI. When I click button to generate it shows 0 on screen. Please help me.
public class glavnaKlasa {
static public int broj;
public static void main(String[] args) {
GUI guiObject = new GUI();
guiObject.mainGUI();
generisanje generisanjeObject = new generisanje();
broj = generisanjeObject.glavno(guiObject.min, guiObject.max);
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUI {
private JFrame frmNasumicniBroj;
private JTextField textField;
private JTextField textField_1;
private JLabel lblNasumicniBroj;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void mainGUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frmNasumicniBroj.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public int min, max;
private void initialize() {
frmNasumicniBroj = new JFrame();
frmNasumicniBroj.setTitle("Nasumicni broj");
frmNasumicniBroj.getContentPane().setBackground(Color.CYAN);
frmNasumicniBroj.setBounds(100, 100, 400, 300);
frmNasumicniBroj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmNasumicniBroj.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Donja granica: ");
lblNewLabel.setForeground(Color.YELLOW);
lblNewLabel.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNewLabel.setBounds(10, 11, 154, 14);
frmNasumicniBroj.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setBounds(200, 8, 154, 20);
frmNasumicniBroj.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblGornjaGranica = new JLabel("Gornja granica: ");
lblGornjaGranica.setForeground(Color.YELLOW);
lblGornjaGranica.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblGornjaGranica.setBounds(10, 36, 165, 14);
frmNasumicniBroj.getContentPane().add(lblGornjaGranica);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(200, 33, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_1);
lblNasumicniBroj = new JLabel("Nasumicni broj: ");
lblNasumicniBroj.setForeground(Color.YELLOW);
lblNasumicniBroj.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNasumicniBroj.setBounds(10, 144, 180, 14);
frmNasumicniBroj.getContentPane().add(lblNasumicniBroj);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_2.setBounds(200, 141, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_2);
textField_2.setColumns(10);
JButton btnNewButton = new JButton("GENERISI");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
glavnaKlasa glKlasa = new glavnaKlasa();
String brString = Integer.toString(glKlasa.broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
btnNewButton.setBounds(10, 61, 345, 72);
frmNasumicniBroj.getContentPane().add(btnNewButton);
JLabel lblVerzija = new JLabel("Verzija: 1.0");
lblVerzija.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
lblVerzija.setBounds(10, 180, 71, 14);
frmNasumicniBroj.getContentPane().add(lblVerzija);
JLabel label_1 = new JLabel("Autor: Djordje Milanovic");
label_1.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_1.setBounds(10, 205, 141, 14);
frmNasumicniBroj.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Copyright: Alfin Informatics");
label_2.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_2.setBounds(9, 236, 166, 14);
frmNasumicniBroj.getContentPane().add(label_2);
}}
import java.util.Random;
import javax.swing.JOptionPane;
public class generisanje {
public static int glavno(int min, int max){
if (min >= max) {
JOptionPane.showMessageDialog(null, "Maksimalni broj mora biti veci od minimalnog");
}
Random rnd = new Random();
return rnd.nextInt((max - min) + 1) + min;
}
}
This:
glavnaKlasa glKlasa = new glavnaKlasa();
creates the object with empty constructor, your main will not run there, so broj remains uninitialized.
Actually, you don't need to instantiate this class there, just this:
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
int broj = generisanje.glavno(guiObject.min, guiObject.max);
String brString = Integer.toString(broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Also consider working according to Java coding standards ( class name first uppercase and so on, it will be much easier to maintain the code).
I'm trying to make a "Simple" quiz in Java using a JFrame. Basically long story short... When the user clicks the "NEXT" button after question 2, it doesn't show the next question...
How can I get the code to proceed to question 3?
CODE
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class SimpleQuiz implements KeyListener, ActionListener
{
static final int WIDTH = 900, HEIGHT = 600;
static final Font FONT = new Font("Arial", Font.BOLD, 20);
static final Color DARKGREEN = new Color(0, 140, 0);
int correct = 0;
boolean start = false , Q1 = false , Q2 = false, Q3 = false;
JFrame window;
JMenuBar Menu;
JMenu startMenu;
JMenuItem GoAction;
JRadioButton radButton1;
JRadioButton radButton2;
JRadioButton radButton3;
JRadioButton radButton4;
JLabel question1;
JLabel question2;
JLabel question3;
JLabel score;
JButton next1;
JButton next2;
JButton finish;
JCheckBox checkBox1;
JCheckBox checkBox2;
JCheckBox checkBox3;
JCheckBox checkBox4;
JList listBox;
public static void main(String[] args)
{
new SimpleQuiz();
}
public SimpleQuiz()
{
window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(null);
window.setSize(WIDTH, HEIGHT);
window.setTitle("Quiz");
window.getContentPane().setBackground(Color.WHITE);
window.setLocationRelativeTo(null);
window.setResizable(false);
//
//
//Question 1
//
//
radButton1 = new JRadioButton();
radButton1.setFont(new Font("Arial", Font.BOLD, 14));
radButton1.setForeground(Color.BLACK);
radButton1.setSize(160, 30);
radButton1.setText("Los Angeles");
radButton1.setLocation(300, 180);
radButton1.setFocusable(false);
radButton1.setVisible(false);
window.add(radButton1);
radButton2 = new JRadioButton();
radButton2.setFont(new Font("Arial", Font.BOLD, 14));
radButton2.setForeground(Color.BLACK);
radButton2.setSize(160, 30);
radButton2.setText("Detroit");
radButton2.setLocation(300, 210);
radButton2.setFocusable(false);
radButton2.setVisible(false);
window.add(radButton2);
radButton3 = new JRadioButton();
radButton3.setFont(new Font("Arial", Font.BOLD, 14));
radButton3.setForeground(Color.BLACK);
radButton3.setSize(160, 30);
radButton3.setText("Shanghai");
radButton3.setLocation(300, 240);
radButton3.setFocusable(false);
radButton3.setVisible(false);
window.add(radButton3);
radButton4 = new JRadioButton();
radButton4.setFont(new Font("Arial", Font.BOLD, 14));
radButton4.setForeground(Color.BLACK);
radButton4.setSize(160, 30);
radButton4.setText("New York City");
radButton4.setLocation(300, 270);
radButton4.setFocusable(false);
radButton4.setVisible(false);
window.add(radButton4);
question1 = new JLabel();
question1.setSize(550, 30);
question1.setLocation(160, 120);
question1.setFont(new Font("Arial", Font.BOLD, 16));
question1.setText("Which one of these cities is not located in the United states of America:");
question1.setOpaque(true);
question1.setBackground(Color.WHITE);
question1.setForeground(Color.BLACK);
question1.setVisible(false);
window.add(question1);
next1 = new JButton();
next1.setFont(new Font("Arial", Font.BOLD, 28));
next1.setForeground(Color.BLACK);
next1.setSize(160, 30);
next1.setText("NEXT");
next1.setActionCommand("q2");
next1.setLocation(700, 500);
next1.setFocusable(false);
next1.setVisible(false);
next1.addActionListener(this);
window.add(next1);
//
//
//Question 2
//
//
checkBox1 = new JCheckBox();
checkBox1.setFont(new Font("Arial", Font.BOLD, 14));
checkBox1.setForeground(Color.BLACK);
checkBox1.setSize(160, 30);
checkBox1.setText("13");
checkBox1.setLocation(300, 180);
checkBox1.setFocusable(false);
checkBox1.setVisible(false);
window.add(checkBox1);
checkBox2 = new JCheckBox();
checkBox2.setFont(new Font("Arial", Font.BOLD, 14));
checkBox2.setForeground(Color.BLACK);
checkBox2.setSize(160, 30);
checkBox2.setText("79");
checkBox2.setLocation(300, 210);
checkBox2.setFocusable(false);
checkBox2.setVisible(false);
window.add(checkBox2);
checkBox3 = new JCheckBox();
checkBox3.setFont(new Font("Arial", Font.BOLD, 14));
checkBox3.setForeground(Color.BLACK);
checkBox3.setSize(160, 30);
checkBox3.setText("14");
checkBox3.setLocation(300, 240);
checkBox3.setFocusable(false);
checkBox3.setVisible(false);
window.add(checkBox3);
checkBox4 = new JCheckBox();
checkBox4.setFont(new Font("Arial", Font.BOLD, 14));
checkBox4.setForeground(Color.BLACK);
checkBox4.setSize(160, 30);
checkBox4.setText("87");
checkBox4.setLocation(300, 270);
checkBox4.setFocusable(false);
checkBox4.setVisible(false);
window.add(checkBox4);
question2 = new JLabel();
question2.setSize(550, 30);
question2.setLocation(160, 120);
question2.setFont(new Font("Arial", Font.BOLD, 16));
question2.setText("Select the prime number(s):");
question2.setOpaque(true);
question2.setBackground(Color.WHITE);
question2.setForeground(Color.BLACK);
question2.setVisible(false);
window.add(question2);
next2 = new JButton();
next2.setFont(new Font("Arial", Font.BOLD, 28));
next2.setForeground(Color.BLACK);
next2.setSize(160, 30);
next2.setText("EXT");
next2.setActionCommand("q3");
next2.setLocation(700, 500);
next2.setFocusable(false);
next2.setVisible(false);
next2.addActionListener(this);
window.add(next2);
//
//
//Question 3
//
//
listBox = new JList();
listBox.setFont(new Font("Arial", Font.BOLD, 14));
listBox.setForeground(Color.BLACK);
listBox.setSize(160, 30);
listBox.setLocation(300, 210);
listBox.setFocusable(false);
listBox.setVisible(false);
window.add(listBox);
question3 = new JLabel();
question3.setSize(550, 30);
question3.setLocation(160, 120);
question3.setFont(new Font("Arial", Font.BOLD, 16));
question3.setText("Of the people listed, who was not a US President:");
question3.setOpaque(true);
question3.setBackground(Color.WHITE);
question3.setForeground(Color.BLACK);
question3.setVisible(false);
window.add(question3);
finish = new JButton();
finish.setFont(new Font("Arial", Font.BOLD, 28));
finish.setForeground(Color.BLACK);
finish.setSize(160, 30);
finish.setText("FINISH");
finish.setActionCommand("end");
finish.setLocation(700, 500);
finish.setFocusable(false);
finish.setVisible(false);
finish.addActionListener(this);
window.add(finish);
//
//
//End
//
//
score = new JLabel();
score.setSize(550, 30);
score.setLocation(160, 120);
score.setFont(new Font("Arial", Font.BOLD, 16));
score.setText("your score is: " + correct + "/3");
score.setOpaque(true);
score.setBackground(Color.WHITE);
score.setForeground(Color.BLACK);
score.setVisible(false);
window.add(score);
//
//
//Extra
//
//
Menu = new JMenuBar();
startMenu = new JMenu("Start");
Menu.add(startMenu);
GoAction = new JMenuItem("Go");
GoAction.setActionCommand("q1");
GoAction.addActionListener(this);
startMenu.add(GoAction);
//exitMenuItem.addActionListener(this);
window.setVisible(true);
window.setJMenuBar(Menu);
//if (getActionCommand() == "BeginQuiz")
//System.out.println(Q1);
}
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("q1"))
{
start = true;
radButton1.setVisible(true);
radButton2.setVisible(true);
radButton3.setVisible(true);
radButton4.setVisible(true);
question1.setVisible(true);
next1.setVisible(true);
System.out.println("Q1");
}
if (e.getActionCommand().equals("q2"))
{
{
radButton1.setVisible(false);
radButton2.setVisible(false);
radButton3.setVisible(false);
radButton4.setVisible(false);
question1.setVisible(false);
next1.setVisible(false);
System.out.println("Q2");
checkBox1.setVisible(true);
checkBox2.setVisible(true);
checkBox3.setVisible(true);
checkBox4.setVisible(true);
question2.setVisible(true);
next2.setVisible(true);
}
if (e.getActionCommand().equals("q3"))
{
{
next2.setVisible(false);
checkBox1.setVisible(false);
checkBox2.setVisible(false);
checkBox3.setVisible(false);
checkBox4.setVisible(false);
question2.setVisible(false);
System.out.println("Q3");
question3.setVisible(true);
finish.setVisible(true);
}
if (e.getActionCommand().equals("end"))
{
{
question3.setVisible(false);
finish.setVisible(false);
score.setVisible(true);
finish.setVisible(true);
}
}
}
}
}
}
As always, thanks for helping me out!
You've got your if (action command equals q3) if block buried within the previous if block and so it will never be reached when it is in a true state.
e.g. you have something like:
if (e.getActionCommand().equals("q2"))
{
{ // this block is unnecessary
// bunch of stuff in here
}
// this block is buried within the if block above, and so will never be true
if (e.getActionCommand().equals("q3"))
{
{ // again this block is unnesseary
// more bunch of code
}
// again this block is buried within the previous two!
if (e.getActionCommand().equals("end"))
{
To solve the immediate problem, each if block should be at the same block code level and not nested in the prior block.
For example, a simple fix would be to change this:
if (e.getActionCommand().equals("q2")) {
{
radButton1.setVisible(false);
radButton2.setVisible(false);
radButton3.setVisible(false);
radButton4.setVisible(false);
question1.setVisible(false);
next1.setVisible(false);
System.out.println("Q2");
checkBox1.setVisible(true);
checkBox2.setVisible(true);
checkBox3.setVisible(true);
checkBox4.setVisible(true);
question2.setVisible(true);
next2.setVisible(true);
}
if (e.getActionCommand().equals("q3")) {
{
next2.setVisible(false);
checkBox1.setVisible(false);
checkBox2.setVisible(false);
checkBox3.setVisible(false);
checkBox4.setVisible(false);
question2.setVisible(false);
System.out.println("Q3");
question3.setVisible(true);
finish.setVisible(true);
}
if (e.getActionCommand().equals("end")) {
{
question3.setVisible(false);
finish.setVisible(false);
score.setVisible(true);
finish.setVisible(true);
}
}
}
}
to this:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("q1")) {
start = true;
radButton1.setVisible(true);
radButton2.setVisible(true);
radButton3.setVisible(true);
radButton4.setVisible(true);
question1.setVisible(true);
next1.setVisible(true);
System.out.println("Q1");
}
if (e.getActionCommand().equals("q2")) {
radButton1.setVisible(false);
radButton2.setVisible(false);
radButton3.setVisible(false);
radButton4.setVisible(false);
question1.setVisible(false);
next1.setVisible(false);
System.out.println("Q2");
checkBox1.setVisible(true);
checkBox2.setVisible(true);
checkBox3.setVisible(true);
checkBox4.setVisible(true);
question2.setVisible(true);
next2.setVisible(true);
}
if (e.getActionCommand().equals("q3")) {
next2.setVisible(false);
checkBox1.setVisible(false);
checkBox2.setVisible(false);
checkBox3.setVisible(false);
checkBox4.setVisible(false);
question2.setVisible(false);
System.out.println("Q3");
question3.setVisible(true);
finish.setVisible(true);
}
if (e.getActionCommand().equals("end")) {
question3.setVisible(false);
finish.setVisible(false);
score.setVisible(true);
finish.setVisible(true);
}
}
But more importantly your code is very repetitive and mixes data with code in an unhealthy way. I would first concentrate on creating an OOP-compliant Question class, and only after doing that and testing it, building a GUI around this class. Also rather than swap components, consider swapping the data that the components display. This will make extending and debugging your code much easier.
For example, I'd start with this:
public class Question {
private String question;
private String correctAnswer;
private List<String> wrongAnswers = new ArrayList<>();
public Question(String question, String correctAnswer) {
this.question = question;
this.correctAnswer = correctAnswer;
}
public void addWrongAnswer(String wrongAnswer) {
wrongAnswers.add(wrongAnswer);
}
public boolean testAnswer(String possibleAnswer) {
return correctAnswer.equalsIgnoreCase(possibleAnswer);
}
public List<String> getAllRandomAnswers() {
List<String> allAnswers = new ArrayList<>(wrongAnswers);
allAnswers.add(correctAnswer);
Collections.shuffle(allAnswers);
return allAnswers;
}
public String getQuestion() {
return question;
}
public String getCorrectAnswer() {
return correctAnswer;
}
// toString, equals and hashCode need to be done too
}
Then I'd
Create a class to hold an ArrayList<Question>, that could give questions as needed, that could tally responses, correct vs. incorrect.
Create file I/O routines to store questions in a file, perhaps as a simple text file or better as an XML file or best as a database.
Then create a class that creates a JPanel that can display any question and that can get user input.
Then a GUI to hold the above JPanel that can get the Question collection from file, that can test the user.
Ok this is my first multi-class program... The output needs to be in a currency format but when I try I get the error(Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GratuityCalculator.getGratuity(GratuityCalculator.java:186)
So I know where the error is but cant figure out why.
here is the code that throws the error its line 186 if I use the currency.format code I get an error if not no error but no currency either:
public class GratuityCalculator extends JFrame
{
/* declarations */
// color objects
Color black = new Color(0, 0, 0);
Color white = new Color(255, 255, 255);
DecimalFormat currency;
//components
JLabel billAmountJLabel;
JTextField billAmountJTextField;
JLabel gratuityJLabel;
JTextField gratuityJTextField;
JButton enterJButton;
JButton clearJButton;
JButton closeJButton;
// variables
double billAmount;
final double GRATUITY_RATE = .15;
double gratuityAmount;
// objects
CalculateTip calculateTip;// object class
public GratuityCalculator()
{
createUserInterface();
}
public void createUserInterface()
{
Container contentPane = getContentPane();
contentPane.setBackground (Color.white);
contentPane.setLayout(null);
//initialize components
billAmountJLabel = new JLabel();
billAmountJLabel.setBounds(50, 50, 120, 20);
billAmountJLabel.setFont(new Font("Default", Font.PLAIN, 12));
billAmountJLabel.setText("Enter bill amount");
billAmountJLabel.setForeground(black);
billAmountJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(billAmountJLabel);
billAmountJTextField = new JTextField();
billAmountJTextField.setBounds(225, 50, 50, 20);
billAmountJTextField.setFont(new Font("Default", Font.PLAIN, 12));
billAmountJTextField.setHorizontalAlignment(JTextField.CENTER);
billAmountJTextField.setForeground(black);
billAmountJTextField.setBackground(white);
billAmountJTextField.setEditable(true);
contentPane.add(billAmountJTextField);
gratuityJLabel = new JLabel();
gratuityJLabel.setBounds(50, 80, 150, 20);
gratuityJLabel.setFont(new Font("Default", Font.PLAIN, 12));
gratuityJLabel.setText("Gratuity");
gratuityJLabel.setForeground(black);
gratuityJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(gratuityJLabel);
gratuityJTextField = new JTextField();
gratuityJTextField.setBounds(225, 80, 50, 20);
gratuityJTextField.setFont(new Font("Default", Font.PLAIN, 12));
gratuityJTextField.setHorizontalAlignment(JTextField.CENTER);
gratuityJTextField.setForeground(black);
gratuityJTextField.setBackground(white);
gratuityJTextField.setEditable(false);
contentPane.add(gratuityJTextField);
enterJButton = new JButton();
enterJButton.setBounds(20, 300, 100, 20);
enterJButton.setFont(new Font("Default", Font.PLAIN, 12));
enterJButton.setText("Enter");
enterJButton.setForeground(black);
enterJButton.setBackground(white);
contentPane.add(enterJButton);
enterJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
enterJButtonActionPerformed(event);
}
}
);
clearJButton = new JButton();
clearJButton.setBounds(140, 300, 100, 20);
clearJButton.setFont(new Font("Default", Font.PLAIN, 12));
clearJButton.setText("Clear");
clearJButton.setForeground(black);
clearJButton.setBackground(white);
contentPane.add(clearJButton);
clearJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
clearJButtonActionPerformed(event);
}
}
);
closeJButton = new JButton();
closeJButton.setBounds(260, 300, 100, 20);
closeJButton.setFont(new Font("Default", Font.PLAIN, 12));
closeJButton.setText("Close");
closeJButton.setForeground(black);
closeJButton.setBackground(white);
contentPane.add(closeJButton);
closeJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
closeJButtonActionPerformed(event);
}
}
);
setTitle("Gratuity Calculator");
setSize( 400, 400 );
setVisible(true);
}
//main method
public static void main(String[] args)
{
GratuityCalculator application = new GratuityCalculator();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void enterJButtonActionPerformed(ActionEvent event)
{
getBillAmount();
}
public void getBillAmount()
{
try
{
billAmount = Double.parseDouble(billAmountJTextField.getText());
getGratuity();
}
catch(NumberFormatException exception)
{
JOptionPane.showMessageDialog(this,
"Please Enter Bill Amount!",
"Number Format Error", JOptionPane.ERROR_MESSAGE);
billAmountJTextField.setText("");
billAmountJTextField.requestFocusInWindow();
}
}
public void getGratuity()
{
/*
Object class is created and gratuity calculated
*/
calculateTip = new CalculateTip(billAmount, GRATUITY_RATE);
/*
Call object class
*/
gratuityAmount = calculateTip.getGratuity();
gratuityJTextField.setText("" + currency.format(gratuityAmount));
}
public void clearJButtonActionPerformed(ActionEvent event)
{
billAmountJTextField.setText("");
billAmountJTextField.requestFocusInWindow();
gratuityJTextField.setText("");
}
public void closeJButtonActionPerformed(ActionEvent event)
{
GratuityCalculator.this.dispose();
}
}
class CalculateTip
{
// class variables
double firstNumber;
double secondNumber;
/*
The object class constructor receives the two values
from the interface class and the two parameter values
are assigned to the class variables
*/
public CalculateTip(double billAmount, double GRATUITY_RATE)
{
firstNumber = billAmount;
secondNumber = GRATUITY_RATE;
}
/*
This method returns the sum of the values to the class
*/
public double getGratuity()
{
return firstNumber * secondNumber;
}
}
Any help appreciated. let me know if more info is required.
I just started learning programming and am trying to create a program that calculates the income tax at 20%. the program compiles but keeps getting errors. The error states
Exception in thread "main" java.lang.IllegalArgumentException: adding container's parent to itself
I don't understand what to change.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
public class IncomeTax extends JFrame
{
// declarations
Color black = new Color(0, 0, 0);
Color white = new Color(255, 255, 255);
Color light_gray = new Color(192, 192, 192);
DecimalFormat currency;
JLabel grossIncomeJLabel;
JTextField grossIncomeJTextField;
JLabel amountTaxedJLabel;
JTextField amountTaxedJTextField;
JTextField currencyJTextField;
JLabel amountDeductedJLabel;
JTextField amountDeductedJTextField;
JLabel netIncomeJLabel;
JTextField netIncomeJTextField;
JButton enterJButton;
JButton clearJButton;
double grossIncome;
double amountTaxed;
double amountDeducted;
double netIncome;
public IncomeTax()
{
createUserInterface();
}
public void createUserInterface()
{
Container contentPane = getContentPane();
contentPane.setBackground(white);
contentPane.setLayout(null);
// initialize components
// input
grossIncomeJLabel = new JLabel ();
grossIncomeJLabel.setBounds (50, 20, 150, 20);
grossIncomeJLabel.setFont(new Font("Default", Font.PLAIN, 12));
grossIncomeJLabel.setText ("Enter Gross Income:");
grossIncomeJLabel.setForeground(black);
grossIncomeJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(grossIncomeJLabel);
grossIncomeJTextField = new JTextField();
grossIncomeJTextField.setBounds(200, 20, 100, 20);
grossIncomeJTextField.setFont(new Font("Default", Font.PLAIN, 12));
grossIncomeJTextField.setHorizontalAlignment(JTextField.CENTER);
grossIncomeJTextField.setForeground(black);
grossIncomeJTextField.setBackground(white);
grossIncomeJTextField.setEditable(true);
contentPane.add(grossIncomeJTextField);
//outputs
amountTaxedJLabel = new JLabel();
amountTaxedJLabel.setBounds(50, 50, 150, 20);
amountTaxedJLabel.setFont(new Font("Default", Font.PLAIN, 12));
amountTaxedJLabel.setText("Amount Taxed");
amountTaxedJLabel.setForeground(black);
amountTaxedJLabel.setHorizontalAlignment(JLabel.LEFT);
amountTaxedJLabel.add(amountTaxedJLabel);
amountTaxedJTextField = new JTextField();
amountTaxedJTextField.setBounds(200, 50, 100, 20);
amountTaxedJTextField.setFont(new Font("Default", Font.PLAIN, 12));
amountTaxedJTextField.setHorizontalAlignment(JTextField.CENTER);
amountTaxedJTextField.setForeground(black);
amountTaxedJTextField.setBackground(white);
amountTaxedJTextField.setEditable(false);
contentPane.add(amountTaxedJTextField);
amountDeductedJLabel = new JLabel();
amountDeductedJLabel.setBounds(50, 80, 150, 20);
amountDeductedJLabel.setFont(new Font("Default", Font.PLAIN, 12));
amountDeductedJLabel.setText("Amount Deducted:");
amountDeductedJLabel.setForeground(black);
amountDeductedJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(amountDeductedJLabel);
amountDeductedJTextField = new JTextField();
amountDeductedJTextField.setBounds(200, 80, 100, 20);
amountDeductedJTextField.setFont(new Font("Default", Font.PLAIN, 12));
amountDeductedJTextField.setHorizontalAlignment(JTextField.CENTER);
amountDeductedJTextField.setForeground(black);
amountDeductedJTextField.setBackground(white);
amountDeductedJTextField.setEditable(false);
contentPane.add(amountDeductedJTextField);
netIncomeJLabel = new JLabel();
netIncomeJLabel.setBounds(50, 110, 150, 20);
netIncomeJLabel.setFont(new Font("Default", Font.PLAIN, 12));
netIncomeJLabel.setText("Net Income:");
netIncomeJLabel.setForeground(black);
netIncomeJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(netIncomeJLabel);
netIncomeJTextField = new JTextField();
netIncomeJTextField.setBounds(200, 110, 100, 20);
netIncomeJTextField.setFont(new Font("Default", Font.PLAIN, 12));
netIncomeJTextField.setHorizontalAlignment(JTextField.CENTER);
netIncomeJTextField.setForeground(black);
netIncomeJTextField.setBackground(white);
netIncomeJTextField.setEditable(false);
contentPane.add(netIncomeJTextField);
// control
enterJButton = new JButton();
enterJButton.setBounds(50, 210, 100, 20);
enterJButton.setFont(new Font("Default", Font.PLAIN, 12));
enterJButton.setText("Enter");
enterJButton.setForeground(black);
enterJButton.setBackground(white);
contentPane.add(enterJButton);
enterJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
enterJButtonActionPerformed(event);
}
}
);
clearJButton = new JButton();
clearJButton.setBounds(200, 210, 100, 20);
clearJButton.setFont(new Font("Default", Font.PLAIN, 12));
clearJButton.setText("Clear");
clearJButton.setForeground(black);
clearJButton.setBackground(white);
contentPane.add(clearJButton);
clearJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
clearJButtonActionPerformed(event);
}
}
);
// set properties of application’s window
setTitle("Income Tax"); // set title
setSize( 400, 400 ); // set window size
setVisible(true); // display window
}
// main method
public static void main(String[] args)
{
IncomeTax application = new IncomeTax();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void enterJButtonActionPerformed(ActionEvent event)
{
// get input
grossIncome = Double.parseDouble(grossIncomeJTextField.getText());
// process data
final double Tax_Rate = .20;
amountTaxed = Tax_Rate;
amountDeducted = grossIncome * Tax_Rate;
netIncome = grossIncome - amountDeducted;
//display results
currency = new DecimalFormat("$0.00");
amountTaxedJTextField.setText("" + currency.format(amountTaxed));
amountDeductedJTextField.setText("" + currency.format(amountDeducted));
netIncomeJTextField.setText("" + currency.format(netIncome));
}
public void clearJButtonActionPerformed(ActionEvent event)
{
grossIncomeJTextField.setText("");
grossIncomeJTextField.requestFocusInWindow();
amountTaxedJTextField.setText("");
amountDeductedJTextField.setText("");
netIncomeJTextField.setText("");
}
}
Here
amountTaxedJLabel.add(amountTaxedJLabel);
I think you meant
contentPane.add(amountTaxedJLabel);
In the prior, you are adding a view to itself.
In the later, you are adding it to your contentPane.
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);
}
}