So in my code, I have 2 JTextField inputs that need input for the rest of the program to work. Both of them contain variables that cannot be left empty for the rest of the program to work. The problem is that whenever you enter something into the text field, you have to press enter in the end and that process is not that straightforward in the program as you are not able to see whether or not you have already pressed enter without looking into the console.
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame2.setTitle("Multiplayer");
frame2.setVisible(true);
JLabel labelM = new JLabel("Geben sie eine Höhstzahl ein:");
JTextField hZahl = new JTextField();
JLabel labelN= new JLabel("Mit wie vielen Rateversuchen wollen sie spielen?");
JTextField rVers = new JTextField();
JButton b = new JButton("Submit");
Now I want the JButton b to press enter for both text field hZahl and rVers when pushed. How do I achieve that?
This is what button bdoes so far:
ActionListener buttonlistener3 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if((arr[0] > 0) && (arr[1] > 0)){
frame3.setTitle("1 Player Game");
frame3.setVisible(true);
JLabel labelB = new JLabel("Erraten sie die Zahl:");
JTextField rVers1 = new JTextField();
labelB.setBounds(50, 105, 400, 70);
rVers1.setBounds(45, 150, 100, 30);
frame3.add(labelB);
frame3.add(rVers1);
rVers1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.out.println("Rateversuch: " + rVers1.getText());
int r = Integer.parseInt(rVers1.getText());
arr[2] = r;
System.out.println("werte " + arr[1] +" " + arr[3] +" " + r);
if(arr[1] == 1){
JLabel lv = new JLabel("Letzer Versuch!");
lv.setBounds(50, 50, 400, 70);
lv.setForeground(Color.red);
frame4.add(lv);
}
tru = arr[3] == arr[2];
if(r < arr[3]){
labelB.setText("Die Gesuchte Zahl ist größer.");
rVers1.setText("");
arr[1] = arr[1] -1;
}
if(r > arr[3]){
labelB.setText("Die Gesuchte Zahl ist kleiner.");
rVers1.setText("");
arr[1] = arr[1] -1;
}
if(tru){
frame4.setVisible(true);
JLabel cor = new JLabel("Richtig!");
JLabel win = new JLabel("Sie haben Gewonnen");
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.green);
frame4.add(cor);
frame4.add(win);
}
if(arr[1] == 0){
frame4.setVisible(true);
JLabel cor = new JLabel("Falsch!");
JLabel win = new JLabel("Die Zahl war: " + arr[3]);
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.green);
frame4.add(cor);
frame4.add(win);
}
if(arr[1] == 0){
frame4.setVisible(true);
JLabel cor = new JLabel("Falsch!");
JLabel win = new JLabel("Die Zahl war: " + arr[3]);
cor.setBounds(50, 50, 300, 100);
win.setBounds(50, 150, 300, 70);
Font labelFont = cor.getFont();
String labelText = cor.getText();
cor.setForeground(Color.red);
win.setForeground(Color.red);
frame4.add(cor);
frame4.add(win);
}
System.out.println("werte neu " + arr[1] +" " + arr[3] +" " + r);
}
});
}
}
};
b.addActionListener(buttonlistener3);
}
};
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm writing a simple program where I have multiple JFrame windows but when I use multiple they stack and I've tried to set their visibility to false that isn't working so I'm trying to simulate a close so the frames don't stack on top of each other but I don't know what to use since my program isn't a window.
public void close(){
WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
on the this I keep getting a error of
incompatible types: Program1 cannot be converted to Window
If someone has a better way of doing this please let me know I cant find a better way that's working for me.
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
//http://vignette4.wikia.nocookie.net/bioshock/images/b/ba/Monu_Island-Skyline01.png/revision/latest?cb=20130521042740
public class Program1 {
public String welcome() {
Date date = new Date();
File music = new File("BioShock_Infinite_-_BioShock_Infinite_-_After_Youv.wav");
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(music));
clip.start();
} catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) {
}
JFrame welcomeJFrame = new JFrame("Welcome to Daimeon's ESCAPE!");
JLabel backgroundImageJLabel = new JLabel();
backgroundImageJLabel.setIcon(new ImageIcon("Monu_Island-Skyline01.png"));
JLabel gameNameJLabel = new JLabel("An Escape from Monument Island!");
JLabel welcomeJLabel = new JLabel("Welcome to Daimeon's Escape Game.");
JLabel currentDateJLabel = new JLabel("" + date.toString() + "");
JPanel Panel = new JPanel();
welcomeJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
currentDateJLabel.setBounds(400, 700, 800, 60);
currentDateJLabel.setFont(new Font("Andes", Font.BOLD, 60));
currentDateJLabel.setHorizontalAlignment(JLabel.CENTER);
gameNameJLabel.setBounds(350, 15, 900, 60);
gameNameJLabel.setForeground(Color.red);
gameNameJLabel.setFont(new Font("Andes", Font.BOLD, 60));
gameNameJLabel.setHorizontalAlignment(JLabel.CENTER);
welcomeJLabel.setBounds(450, 75, 700, 35);
welcomeJLabel.setFont(new Font("Andes", Font.BOLD, 30));
welcomeJLabel.setHorizontalAlignment(JLabel.CENTER);
Panel.add(backgroundImageJLabel);
backgroundImageJLabel.add(gameNameJLabel);
backgroundImageJLabel.add(welcomeJLabel);
backgroundImageJLabel.add(currentDateJLabel);
welcomeJFrame.add(Panel);
welcomeJFrame.setSize(1828, 1080);
welcomeJFrame.setLocationRelativeTo(null);
welcomeJFrame.setVisible(true);
String name = "";
name = getUsers_Name(name);
gretting(name);
return name;
}
public String getUsers_Name(String name) {
return name = JOptionPane.showInputDialog(null, "Hey there please sign-in with your name:");
}
public void gretting(String name) {
JOptionPane.showMessageDialog(null, "Well howdy there " + name + " welcome to the website."
+ "\nHeres a run down of what this is all about.");
JOptionPane.showMessageDialog(null,
name + "\n you are stuck in the Monument on Monument island trying to escape"
+ "\n from songbrid and from the sherpards men, both are trying to kill"
+ " you.");
JOptionPane.showMessageDialog(null,
"\t \t \t Basic Registration Fees\n" + "$2.50 : Dont run before you can walk "
+ "( Ages 0 - 4 )\n" + "$5.00 : Felling courageous " + "( Ages 4 - 12 )\n"
+ "$7.50 : Wont be a walk in the park " + "( Ages 13 - 17 )\n"
+ "$9.75 : Expert " + "( Ages 18+ )\n" + "$1.25 : Additional Items "
+ "( Lock Pick, Silver Eagle or Creature )",
"Fees", JOptionPane.WARNING_MESSAGE, null);
JOptionPane.showMessageDialog(null,
"Hey " + name + ",\n" + "Please continue to start\n" + "registration",
"Please Continue", JOptionPane.WARNING_MESSAGE, null);
}
public void start_regstration(ArrayList users_Information) {
int[] user_number_information = new int[5];
int addons = 0;
double[] user_dep_amount = new double[5];
users_Information.add(get_user_alias(users_Information));
users_Information.add(get_user_gender(users_Information));
users_Information.add(get_user_atrological_sign(users_Information));
user_number_information[0] = get_user_birth_year(users_Information);
user_dep_amount[0] = get_int_player_dep_amount(users_Information);
user_number_information[2] = get_addon_1(users_Information);
user_number_information[3] = get_addon_2(users_Information);
user_number_information[4] = get_addon_3(users_Information);
confirm(users_Information, user_number_information);
compute_total_addons(user_number_information);
feature_recipt(users_Information, user_number_information);
pre_total_reg_fee_recipt(users_Information, user_number_information);
user_number_information[1] = get_players_age(user_number_information);
user_dep_amount[1] = players_age_reg_fee(user_number_information);
user_dep_amount[2] = daimeons_round_to_penny(user_number_information);
final_player_fee_amount(users_Information, user_dep_amount);
exit_m();
}
public String get_user_alias(ArrayList users_Information) {
String alias;
alias = (String) JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(0) + " what is your alias?", "Alias",
JOptionPane.QUESTION_MESSAGE, null, null, "Captain");
return alias;
}
public String get_user_gender(ArrayList users_Information) {
String user_gender;
user_gender = (String) JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(1) + " what is your gender?", "Gender",
JOptionPane.QUESTION_MESSAGE, null, null, "Male");
return user_gender;
}
public String get_user_atrological_sign(ArrayList users_Information) {
close();
String astro_sign;
astro_sign = (String) JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(1) + " what's your astrological sign?",
"Astrological Sign", JOptionPane.QUESTION_MESSAGE, null, null, "Gemini");
return astro_sign;
}
public int get_user_birth_year(ArrayList users_Information) {
int bY;
String input = JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(1) + " what is your birth year?");
bY = Integer.parseInt(input);
return bY;
}
public double get_int_player_dep_amount(ArrayList users_Information) {
double user_dep;
Object input = JOptionPane.showInputDialog(null,
"Hey " + users_Information.get(1) + " how much would you like to deposit?",
"Deposit", JOptionPane.QUESTION_MESSAGE, null, null, "1234.56");
user_dep = Double.parseDouble((String) input);
return user_dep;
}
public int get_addon_1(ArrayList users_Information) {
return 1;
}
public int extraFeatureTreasure( String alias )
{
//Title bar
JFrame getExtraFeaturesJFrame = new JFrame("User's Extra Features" );
//Set background
JLabel backgroundImageJLabel = new JLabel( );
backgroundImageJLabel.setIcon( new ImageIcon( "VV.jpg" ) );
//Treasure
JLabel treasureJLabel = new JLabel( );
//Creatures
JLabel creature1JLabel = new JLabel( );
JLabel creature2JLabel = new JLabel( );
//Key
JLabel keyJLabel = new JLabel( );
//Second panel
JPanel theSecondPanel = new JPanel( );
getExtraFeaturesJFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
treasureJLabel.setIcon( new ImageIcon( "lovee.gif" ) );
creature1JLabel.setIcon( new ImageIcon( "gun.gif" ) );
creature2JLabel.setIcon( new ImageIcon( "creature2.gif" ) );
keyJLabel.setIcon( new ImageIcon( "fashionkey.jpg" ) );
//Extra feature price label
JLabel extraFeatureTextJLabel = new JLabel( "Extra Features : $1.25 ea" );
//Treasure
JLabel treasureTextJLabel = new JLabel( "Treasure" );
JLabel treasureDescriptionText0JLabel = new JLabel( "Extra treasures are some of the" );
JLabel treasureDescriptionText1JLabel = new JLabel( "latest fashion trends!" );
//Creature
JLabel creature1TextJLabel = new JLabel( "The Guy With The Gun" );
JLabel creature2TextJLabel = new JLabel( "Unfashionable Shopaholics" );
JLabel creature1TextDescription0JLabel = new JLabel( "Beware of the creatures!" );
JLabel creature1TextDescription1JLabel = new JLabel( "if you encounter then at any point" );
JLabel creature1TextDescription2JLabel = new JLabel( "you will lose all your precious shops" );
//Key
JLabel keyTextJLabel = new JLabel( "Fashion Key" );
JLabel keyTextDescription0JLabel = new JLabel( "Fashion keys are the most" );
JLabel keyTextDescription1JLabel = new JLabel( "special features in this game" );
JLabel keyTextDescription2JLabel = new JLabel( "since they add the final touch" );
JLabel keyTextDescription3JLabel = new JLabel( "to your perfect outfit" );
//Extra feature label characteristics
extraFeatureTextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 40 ) );
extraFeatureTextJLabel.setForeground( new Color( 250, 150, 200 ));
extraFeatureTextJLabel.setHorizontalAlignment( JLabel.CENTER );
//Extra feature label characteristics
treasureTextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 25 ) );
treasureDescriptionText0JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
treasureDescriptionText1JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
//Extra feature label characteristics
creature1TextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 25 ) );
creature1TextDescription0JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
creature1TextDescription1JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
creature1TextDescription2JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
//Extra feature label characteristics
creature2TextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 25 ) );
//Extra feature label characteristics
keyTextJLabel.setFont( new Font( "Cooper Black", Font.BOLD, 25 ) );
keyTextDescription0JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
keyTextDescription1JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
keyTextDescription2JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
keyTextDescription3JLabel.setFont( new Font( "Cooper Black", Font.BOLD, 20 ) );
//Extra feature label characteristics
extraFeatureTextJLabel.setBounds( 450,1,700,40 );
treasureTextJLabel.setBounds( 400,315,500,50 );
treasureJLabel.setBounds( 200,35,500,300 );
treasureDescriptionText0JLabel.setBounds( 200,345,500,50 );
treasureDescriptionText1JLabel.setBounds( 200,365,500,50 );
keyTextJLabel.setBounds( 1195,284,500,50 );
keyJLabel.setBounds( 1132,45,400,250 );
keyTextDescription0JLabel.setBounds( 770,20,400,250 );
keyTextDescription1JLabel.setBounds( 770,40,400,250 );
keyTextDescription2JLabel.setBounds( 770,60,400,250 );
keyTextDescription3JLabel.setBounds( 770,80,400,250 );
creature1TextJLabel.setBounds( 300,645,500,50 );
creature2TextJLabel.setBounds( 980,645,545,50 );
creature1TextDescription0JLabel.setBounds( 200,675,500,50 );
creature1TextDescription1JLabel.setBounds( 200,695,500,50 );
creature1TextDescription2JLabel.setBounds( 200,715,500,50 );
creature1JLabel.setBounds( 200,390,500,300 );
creature2JLabel.setBounds( 897,377,500,300 );
//Add all labels to the pannel
theSecondPanel.add(backgroundImageJLabel);
backgroundImageJLabel.add(extraFeatureTextJLabel);
backgroundImageJLabel.add(treasureTextJLabel);
backgroundImageJLabel.add(treasureJLabel);
backgroundImageJLabel.add(treasureDescriptionText0JLabel);
backgroundImageJLabel.add(treasureDescriptionText1JLabel);
backgroundImageJLabel.add(creature1TextJLabel);
backgroundImageJLabel.add(creature1JLabel);
backgroundImageJLabel.add(creature2TextJLabel);
backgroundImageJLabel.add(creature2JLabel);
backgroundImageJLabel.add(creature1TextDescription0JLabel);
backgroundImageJLabel.add(creature1TextDescription1JLabel);
backgroundImageJLabel.add(creature1TextDescription2JLabel);
backgroundImageJLabel.add(keyTextJLabel);
backgroundImageJLabel.add(keyJLabel);
backgroundImageJLabel.add(keyTextDescription0JLabel);
backgroundImageJLabel.add(keyTextDescription1JLabel);
backgroundImageJLabel.add(keyTextDescription2JLabel);
backgroundImageJLabel.add(keyTextDescription3JLabel);
//Add panel to the frame
getExtraFeaturesJFrame.add(theSecondPanel);
getExtraFeaturesJFrame.setSize ( 1280, 900 );
getExtraFeaturesJFrame.setLocationRelativeTo( null );
getExtraFeaturesJFrame.setVisible( true );
//Ask for user's amount to deposit, output changes from a String to an Object
//Image 2
Object getTreasures = JOptionPane.showInputDialog( null,
"Dear " + alias + "\u2661,\n"
+"Please enter the number of treasures\n"
+"you wish to acquire",
"\u2661Number of Treasures\u2661",
JOptionPane.PLAIN_MESSAGE,
icon, null,
"0");
//TypeCast, converts returned Object to a string
getUserTreasures = (String)getTreasures;
//Converts returned String to an int
numberOfTreasures = Integer.parseInt( getUserTreasures );
return numberOfTreasures;
}
public int get_addon_2(ArrayList users_Information) {
return 2;
}
public int get_addon_3(ArrayList users_Information) {
return 3;
}
public void confirm(ArrayList users_Information, int[] user_number_information) {
}
public double compute_total_addons(int[] user_number_information) {
return 1.0;
}
public void feature_recipt(ArrayList users_Information, int[] user_number_information) {
}
public void pre_total_reg_fee_recipt(ArrayList users_Information,
int[] user_number_information) {
}
public int get_players_age(int[] user_number_information) {
return 1;
}
public double players_age_reg_fee(int[] user_number_information) {
return 1.0;
}
public double daimeons_round_to_penny(int[] user_number_information) {
return 1.0;
}
public void final_player_fee_amount(ArrayList users_Information, double[] user_dep_amount) {
}
public void exit_m() {
System.exit(0);
}
public void close() {
// TODO: Fix:
// WindowEvent winClosingEvent = new WindowEvent(this,
// WindowEvent.WINDOW_CLOSING);
// Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
public static void main(String[] args) {
Program1 methods = new Program1();
ArrayList<String> users_Information = new ArrayList<>();
users_Information.add(methods.welcome());
methods.start_regstration(users_Information);
methods.extraFeatureTreasure();
}
}
You didn't put enough information and explanation to your exact problem but here is what I can help you with :
To make a JFrame close when you click on the OS provided close button (at the top right corner usually) this will work for you (put it in the class that controlls your JFrame which also extends JFrame class ) :
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
To close a JFrame on an a specific event use :
this.dispose();
To make a JFrame invisible use this :
this.setVisible(false);
i cannot figure out how to get my code to tell when the button is pressed. i was taught poorly, just FYI so any help will need to be greatly detailed. also, i am new to the site so if the post isnt formatted correctly i am sorry.
public static void main(String[] args) {
final JFrame frame = new JFrame("JSlider Demo");
final double odd = 50;
final double bet = 1;
boolean auto = false;
double cash = 5.00;
int cash1 = 0;
JLabel jLabel1 = new JLabel("your cash: " + cash);
JButton b1 = new JButton("GO!");
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
// create odds slider
JSlider odds = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
odds.setMinorTickSpacing(5);
odds.setMajorTickSpacing(25);
odds.setPaintTicks(true);
odds.setPaintLabels(true);
odds.setLabelTable(odds.createStandardLabels(100));
//Create the label table for the odds slider
Hashtable labelTable1 = new Hashtable();
labelTable1.put( new Integer( 50 ), new JLabel("Odds") );
labelTable1.put( new Integer( 0 ), new JLabel("0") );
labelTable1.put( new Integer( 100 ), new JLabel("100") );
odds.setLabelTable( labelTable1 );
odds.setPaintLabels(true);
// create auto bet count slider
JSlider count = new JSlider(JSlider.HORIZONTAL, 1, 101, 1);
count.setMinorTickSpacing(5);
count.setMajorTickSpacing(20);
count.setPaintTicks(true);
count.setPaintLabels(true);
count.setLabelTable(count.createStandardLabels(50));
//Create the label table for auto bet count
Hashtable labelTable3 = new Hashtable();
labelTable3.put( new Integer( 50 ), new JLabel("Auto-bet count") );
labelTable3.put( new Integer( 1 ), new JLabel("1") );
labelTable3.put( new Integer( 101 ), new JLabel("100") );
count.setLabelTable( labelTable3 );
count.setPaintLabels(true);
// create auto bet speed slider
JSlider speed = new JSlider(JSlider.HORIZONTAL, 0, 4, 0);
speed.setMinorTickSpacing(20);
speed.setMajorTickSpacing(1);
speed.setPaintTicks(true);
speed.setPaintLabels(true);
speed.setLabelTable(speed.createStandardLabels(50));
//Create the label table for speed
Hashtable labelTable4 = new Hashtable();
labelTable4.put( new Integer( 2 ), new JLabel("Auto-bet speed") );
labelTable4.put( new Integer( 0 ), new JLabel("1(BPS)") );
labelTable4.put( new Integer( 4 ), new JLabel("5(BPS)") );
speed.setLabelTable( labelTable4 );
speed.setPaintLabels(true);
//sets the GUI
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 200);
frame.getContentPane().add(odds);
frame.getContentPane().add(count);
frame.getContentPane().add(speed);
frame.getContentPane().add(b1);
frame.getContentPane().add(jLabel1);
frame.setVisible(true);
}
Did you tried addActionListener method? For example;
JButton b1 = new JButton("GO!");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// execute this method when the button is pressed
}
});
Docs: https://docs.oracle.com/javase/8/docs/api/java/awt/event/ActionListener.html
You could make your class in which your main method exists, implement ActionListener, and then override the actionPerformed method. For example:
public class A implements ActionListener {
JButton b1 = new JButton("Hello");
b1.addActionListener(this);
public void actionPerformed(ActionEvent e) {
if (e.getSource == b1) {
// do stuff when button b1 is clicked.
}
}
...
}
You can do this for all the buttons in the class. I'm not sure which way of doing this is recommended though, thought I'd add it anyway. :)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I populate jcombobox from a textfile?
OK, I have an issue here that I cannot quiet figure out. I have a file that has variables on each line of: 5.35, 5.5, 5.75 in a file called apr.txt. I am reading the file and need to populate the file into a JComboBox. So far I have the file being read fine but cannot figure how to populate it into the JComboBox. This must be something easy. Can someone help point me in the proper direction?
Thank you for your help in advance.
import java.awt.*;
import java.text.NumberFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.JComboBox;
public class MortgageCalculatorGUI9 extends JFrame implements ActionListener
{
// Declarations
//double [] Interest = {5.35, 5.5, 5.75};
int [] Length = {7, 15, 30};
double [] file_data = new double[3];
JLabel mortgagelabel = new JLabel( "Principal Amount:$ " );
JLabel paymentLabel = new JLabel( "Monthly Payment: " );
JLabel intRateLabel = new JLabel( "Interest Rate %: " );
JLabel termLabel = new JLabel( "Length of Loan of Loan in Years: " );
JTextField mortgagePrincipal = new JTextField(7);
JTextField Payment = new JTextField(7);
//JTextField intRateText = new JTextField(3);
JComboBox intRateBox = new JComboBox();
JTextField termText = new JTextField(3);
JButton b7_535 = new JButton( "7 years at 5.35%" );
JButton b15_55 = new JButton( "15 years at 5.50%" );
JButton b30_575 = new JButton( "30 years at 5.75%");
JButton exitButton = new JButton( "Exit" );
JButton clearButton = new JButton( "Clear All" );
JButton calculateButton = new JButton( "Calculate Loan" );
JTextArea LoanPayments = new JTextArea(20,50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public MortgageCalculatorGUI9()
{
//GUI setup
super("Mortgage Calculator 1.0.5");
setSize(800, 400);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(3,1)); Container grid = getContentPane();
grid.setLayout(new GridLayout(4,0,4,4)); pane.add(grid);
pane.add(scroll);
grid.add(mortgagelabel);
grid.add(mortgagePrincipal);
grid.add(intRateLabel);
//grid.add(intRateText);
grid.add (intRateBox);
grid.add(termLabel);
grid.add(termText);
grid.add(paymentLabel);
grid.add(Payment);
grid.add(b7_535);
grid.add(b15_55);
grid.add(b30_575);
grid.add(calculateButton);
grid.add(clearButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
//add GUI functionality
calculateButton.addActionListener (this);
exitButton.addActionListener(this);
clearButton.addActionListener(this);
b7_535.addActionListener(this);
b15_55.addActionListener(this);
b30_575.addActionListener(this);
mortgagePrincipal.addActionListener(this);
//intRateText.addActionListener(this);
intRateBox.addActionListener (this);
termText.addActionListener(this);
Payment.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object command = e.getSource();
if (command == exitButton)
{
System.exit(0);
}
else if (command == b7_535)
{
calcLoan(Length[0], file_data[0]);
}
else if (command == b15_55)
{
calcLoan(Length[1], file_data[1]);
}
else if (command == b30_575)
{
calcLoan(Length[2], file_data[2]);
}
else if (command == calculateButton )
{
double terms = 0;
double rates = 0;
try
{
terms = Double.parseDouble(termText.getText());
//rates = Double.parseDouble(intRateText.getText());
read_File ();
}
catch (Exception ex)
{
LoanPayments.setText("Invalid term or rate Amount");
return;
}
calcLoan(terms, rates);
}
else if (command == clearButton)
{
mortgagePrincipal.setText("");
Payment.setText("");
//intRateText.setText("");
termText.setText("");
LoanPayments.setText("");
}
}
//Input File
public void read_File()
{
File inFile = new File("apr.txt");
try
{
BufferedReader istream = new BufferedReader(new FileReader(inFile));
for(int x=0;x<6;x++)
{
file_data[x]=Double.parseDouble (istream.readLine());
}
}
catch (Exception ex)
{
LoanPayments.setText ("Could Not Read From File.");
return;
}
}
//this is what needs to be done
private void calcLoan(double terms, double rates)
{
termText.setText(String.valueOf(terms) );
//intRateText.setText(String.valueOf(rates));
double amount = 0;
try
{
amount = Double.parseDouble(mortgagePrincipal.getText());
}
catch (Exception ex)
{
LoanPayments.setText("Invalid mortgage Amount");
return;
}
double interestRate = rates;
// Calculations
double intRate = (interestRate / 100) / 12;
int Months = (int)terms * 12;
double rate = (intRate / 12);
double payment = amount * intRate / (1 - (Math.pow(1/(1 + intRate), Months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
double[] balanceArray = new double[Months];
double[] interestArray = new double[Months];
double[] monthArray = new double[Months];
NumberFormat Money = NumberFormat.getCurrencyInstance();
Payment.setText(Money.format(payment));
LoanPayments.setText("Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while(currentMonth < Months)
{
//create loop calculations
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t" + Money.format(MonthlyAmt) + "\t" + Money.format(MonthlyInterest) + "\t" + Money.format(remainingPrincipal) + "\n");
balanceArray[currentMonth] = MonthlyAmt;
interestArray[currentMonth] = MonthlyInterest;
monthArray[currentMonth] = currentMonth;
}
}
public static void main(String[] args)
{
MortgageCalculatorGUI9 frame= new MortgageCalculatorGUI9();
}
}
Have you looked at the JComboBox API for a suitable method? If you start there, you'll likely get the right answer faster than asking in StackOverflow (hint it starts with "add... and ends with ...Item") ;)
I'm having trouble with my radio buttons. I can click on all three at the same time. It should be when you click on one the other one turns off?
I'm using a grid layout. So when I try group.add it doesn't work.
Example:
I have the buttons declared like this
JRadioButton seven = new JRadioButton("7 years at 5.35%", false);
JRadioButton fifteen = new JRadioButton("15 years at 5.5%", false);
JRadioButton thirty = new JRadioButton("30 years at 5.75%", false);
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
This is my code:
/*Change Request #6
Write the program in Java (with a graphical user interface)
so that it will allow the user to select which way
they want to calculate a mortgage:
by input of the amount of the mortgage,
the term of the mortgage,
and the interest rate of the mortgage payment
or by input of the amount of a mortgage and
then select from a menu of mortgage loans:
- 7 year at 5.35%
- 15 year at 5.5 %
- 30 year at 5.75%
In either case, display the mortgage payment amount
and then, list the loan balance and interest paid
for each payment over the term of the loan.
Allow the user to loop back and enter a new amount
and make a new selection, or quit.
Insert comments in the program to document the program.
*/
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WK4 extends JFrame implements ActionListener
{
int loanTerms[] = { 7, 15, 30 };
double annualRates[] = { 5.35, 5.5, 5.75 };
// Labels
JLabel AmountLabel = new JLabel(" Loan Amount $ ");
JLabel PaymentLabel = new JLabel(" Monthly Payment ");
JLabel InterestLabel = new JLabel(" Interest Rate % ");
JLabel TermLabel = new JLabel(" Years of Loan ");
// Text Fields
JTextField mortgageAmount = new JTextField(6);
JTextField Payment = new JTextField(6);
JTextField InterestRate = new JTextField(3);
JTextField Term = new JTextField(3);
// Radio Buttons
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton seven = new JRadioButton("7 years at 5.35%");
JRadioButton fifteen = new JRadioButton("15 years at 5.5%");
JRadioButton thirty = new JRadioButton("30 years at 5.75%");
// Buttons
JButton exitButton = new JButton("Exit");
JButton resetButton = new JButton("Reset");
JButton calculateButton = new JButton("Calculate ");
// Text Area
JTextArea LoanPayments = new JTextArea(20, 50);
JTextArea GraphArea = new JTextArea(20, 50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public WK4(){
super("Mortgage Calculator");
//Window
setSize(700, 400);
setLocation(200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(2, 2));
Container grid = getContentPane();
grid.setLayout(new GridLayout(4, 10, 0, 12)); //rows, cols, hgap, vgap
pane.add(grid);
pane.add(scroll);
grid.add(AmountLabel);
grid.add(mortgageAmount);
grid.add(InterestLabel);
grid.add(InterestRate);
grid.add(TermLabel);
grid.add(Term);
grid.add(PaymentLabel);
grid.add(Payment);
grid.add(Box.createHorizontalStrut(15));
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
grid.add(calculateButton);
grid.add(resetButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
// Action Listeners
mortgageAmount.addActionListener(this);
InterestRate.addActionListener(this);
Term.addActionListener(this);
Payment.addActionListener(this);
seven.addActionListener(this);
fifteen.addActionListener(this);
thirty.addActionListener(this);
calculateButton.addActionListener(this);
exitButton.addActionListener(this);
resetButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object command = e.getSource();
if (command == exitButton) {
System.exit(0);
}
else if (command == seven) {
calcLoan(loanTerms[0], annualRates[0]);
}
else if (command == fifteen) {
calcLoan(loanTerms[1], annualRates[1]);
}
else if (command == thirty) {
calcLoan(loanTerms[2], annualRates[2]);
}
else if (command == calculateButton) {
double years = 0;
double rates = 0;
try {
years = Double.parseDouble(Term.getText());
rates = Double.parseDouble(InterestRate.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
calcLoan(years, rates);
}
else if (command == resetButton) {
mortgageAmount.setText("");
Payment.setText("");
InterestRate.setText("");
Term.setText("");
LoanPayments.setText("");
}
}
private void calcLoan(double years, double rates) {
Term.setText(String.valueOf(years));
InterestRate.setText(String.valueOf(rates));
double amount = 0;
try {
amount = Double.parseDouble(mortgageAmount.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
double interestRate = rates;
double intRate = (interestRate / 100) / 12;
int months = (int) years * 12;
double rate = (intRate / 12);
double payment = amount * intRate
/ (1 - (Math.pow(1 / (1 + intRate), months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
NumberFormat CurrencyFormatter = NumberFormat.getCurrencyInstance();
Payment.setText(CurrencyFormatter.format(payment));
LoanPayments.setText(" Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while (currentMonth < months) {
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t"
+ CurrencyFormatter.format(MonthlyAmt) + "\t"
+ CurrencyFormatter.format(MonthlyInterest) + "\t"
+ CurrencyFormatter.format(remainingPrincipal) + "\n");
GraphArea.append("" + remainingPrincipal);
}
}
public static void main(String[] args) {
new WK4();
}
}
You're adding the radio buttons to the grid but you also need to add them to the button group that you defined.
Maybe this:
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
Should be this: ??? (Copy/paste bug?)
ButtonGroup group = new ButtonGroup();
group.add(seven);
group.add(fifteen);
group.add(thirty);
Or maybe you need to do both. The radio buttons have to belong to a container as well as a button group to be displayed and to behave properly.