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);
Related
I hope I'm doing this right, first post for me here. I've only been programming with java for a few weeks so this might be really simple but I just cannot figure it out, I tried my java book, youtube, google. I have one panel with textfields and one button, after the button is pressed a new panel should show up with some other textfields. The new panel does show up when the button is clicked, only it stays empty. I'm guessing I have to put some of the code in a different location for it to actually show? Any help would be appreciated, I hope the code is readable, I don't understand where exactly I'm going wrong so figured it would be best to add it completely.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class java03 extends JFrame
{
public static void main ( String args[] )
{
JFrame frame1 = new java03();
frame1.setSize ( 600, 500 );
frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame1.setTitle( "Hour Registration" );
JPanel paneel = new Paneelinvoer();
frame1.setContentPane( paneel );
frame1.setVisible ( true );
}
}
class Paneelinvoer extends JPanel
{
private JTextField naaminvoer, badgeinvoer;
private JTextField maandaginvoer, dinsdaginvoer, woensdaginvoer, donderdaginvoer, vrijdaginvoer, zaterdaginvoer, zondaginvoer;
private JLabel naam, badge, uren;
private JLabel maandag, dinsdag, woensdag, donderdag, vrijdag, zaterdag, zondag;
private JButton knop;
public Paneelinvoer()
{
setLayout( null );
//tekstvakken
naaminvoer = new JTextField( 40 );
naaminvoer.setHorizontalAlignment ( JTextField.LEFT );
badgeinvoer = new JTextField( 4 );
badgeinvoer.setHorizontalAlignment ( JTextField.LEFT );
maandaginvoer = new JTextField( 2 );
maandaginvoer.setHorizontalAlignment ( JTextField.LEFT );
dinsdaginvoer = new JTextField( 2 );
dinsdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
woensdaginvoer = new JTextField( 2 );
woensdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
donderdaginvoer = new JTextField( 2 );
donderdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
vrijdaginvoer = new JTextField( 2 );
vrijdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
zaterdaginvoer = new JTextField( 2 );
zaterdaginvoer.setHorizontalAlignment ( JTextField.LEFT );
zondaginvoer = new JTextField( 2 );
zondaginvoer.setHorizontalAlignment ( JTextField.LEFT );
//labels
naam = new JLabel ( "Naam:" );
badge = new JLabel ( "Badgenummer:" );
uren = new JLabel ( "Uren" );
maandag = new JLabel ( "Maandag" );
dinsdag = new JLabel ( "Dinsdag" );
woensdag = new JLabel ( "Woensdag" );
donderdag = new JLabel ( "Donderdag" );
vrijdag = new JLabel ( "Vrijdag" );
zaterdag = new JLabel ( "Zaterdag" );
zondag = new JLabel ( "Zondag" );
//knoppen
knop = new JButton ( "Accept" );
knop.addActionListener ( new knopHandler () );
//plaats en afmetingen
naam.setBounds( 20, 20, 120, 20 );
naaminvoer.setBounds( 140, 20, 90, 20 );
badge.setBounds( 20, 50, 120, 20 );
badgeinvoer.setBounds( 140, 50, 90, 20 );
uren.setBounds ( 190, 100, 90, 20 );
maandag.setBounds( 20, 120, 120, 20 );
maandaginvoer.setBounds( 160, 120, 90, 20 );
dinsdag.setBounds( 20, 160, 120, 20 );
dinsdaginvoer.setBounds( 160, 160, 90, 20 );
woensdag.setBounds( 20, 200, 120, 20 );
woensdaginvoer.setBounds( 160, 200, 90, 20 );
donderdag.setBounds( 20, 240, 120, 20 );
donderdaginvoer.setBounds( 160, 240, 90, 20 );
vrijdag.setBounds( 20, 280, 120, 20 );
vrijdaginvoer.setBounds( 160, 280, 90, 20 );
zaterdag.setBounds( 20, 320, 120, 20 );
zaterdaginvoer.setBounds( 160, 320, 90, 20 );
zondag.setBounds( 20, 360, 120, 20 );
zondaginvoer.setBounds( 160, 360, 90, 20 );
knop.setBounds ( 100, 400, 100, 20 );
//voeg componenten toe
add ( naaminvoer );
add ( badgeinvoer );
add ( naam );
add ( badge );
add ( uren );
add ( maandag );
add ( dinsdag );
add ( woensdag );
add ( donderdag );
add ( vrijdag );
add ( zaterdag );
add ( zondag );
add ( maandaginvoer );
add ( dinsdaginvoer );
add ( woensdaginvoer );
add ( donderdaginvoer );
add ( vrijdaginvoer );
add ( zaterdaginvoer );
add ( zondaginvoer );
add ( knop );
}
class knopHandler implements ActionListener
{
public void actionPerformed ( ActionEvent e )
{
JFrame frame2 = new JFrame ( "Total Hours" );
frame2.setSize ( 600, 500 );
JPanel uitvoerpanel = new JPanel();
frame2.setContentPane( uitvoerpanel );
frame2.setVisible( true );
String invoerstring1 = maandaginvoer.getText();
int getal1 = Integer.parseInt( invoerstring1 );
String invoerstring2 = dinsdaginvoer.getText();
int getal2 = Integer.parseInt( invoerstring2 );
String invoerstring3 = woensdaginvoer.getText();
int getal3 = Integer.parseInt( invoerstring3 );
String invoerstring4 = donderdaginvoer.getText();
int getal4 = Integer.parseInt( invoerstring4 );
String invoerstring5 = vrijdaginvoer.getText();
int getal5 = Integer.parseInt( invoerstring5 );
String invoerstring6 = zaterdaginvoer.getText();
int getal6 = Integer.parseInt( invoerstring6 );
String invoerstring7 = zondaginvoer.getText();
int getal7 = Integer.parseInt( invoerstring7 );
int resultaat = getal1 + getal2 + getal3 + getal4 + getal5 + getal6 + getal7;
}
}
class uitvoerpanel extends JPanel
{
private JTextField naamvak, badgevak, totaalurenvak;
private JLabel naam, badge, totaaluren;
public uitvoerpanel()
{
setLayout( null );
naamvak = new JTextField ( 20 );
naamvak.setHorizontalAlignment ( JTextField.LEFT );
naamvak.setEditable ( false );
badgevak = new JTextField ( 20 );
badgevak.setHorizontalAlignment ( JTextField.LEFT );
badgevak.setEditable ( false );
totaalurenvak = new JTextField ( 20 );
totaalurenvak.setHorizontalAlignment ( JTextField.LEFT );
totaalurenvak.setEditable ( false );
naam = new JLabel ( "Naam:" );
badge = new JLabel ( "Badgenummer:" );
totaaluren = new JLabel ( "Totaal gewerkte uren:" );
naam.setBounds ( 50,50, 90, 20 );
naamvak.setBounds ( 160, 50, 90, 20);
badge.setBounds ( 50, 90, 90, 20 );
badgevak.setBounds ( 160, 90, 90, 20 );
totaaluren.setBounds ( 50, 130, 90, 20 );
totaalurenvak.setBounds ( 160, 130, 90, 20 );
add ( naamvak );
add ( badgevak );
add ( totaalurenvak );
add ( naam );
add ( badge );
add ( totaaluren );
}
}
}
Your problem lies within knopHandler :
JPanel uitvoerpanel = new JPanel();
You are simply creating a new JPanel; you actually want to create a new uitvoerpanel. Because it extends JPanel, you can do this:
JPanel uitvoerpanel = new uitvoerpanel();
This will fix your mentioned problem. However, you should be aware of the Java naming conventions. It will make your code much easier to read.
I have searched this site, other sites, and my textbook and cannot come up with a solution so here goes:
I have a simple temp. conversion program which functions just fine however I would like to make my layout more appealing and more similar to what is asked for in the procedures.
Right now it looks like this:
And I want it to look like this:
Difference being the Input and Output fields are centered in the desired output.
Here is my program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Convert extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel convertFrom, convertTo, top, bottom;
private JLabel label3, label4;
private JTextField temperature1, temperature2;
private ButtonGroup radioFrom, radioTo;
private JRadioButton celsiusBoxTo, fahrenheitBoxTo, kelvinBoxTo, celsiusBoxFrom, fahrenheitBoxFrom, kelvinBoxFrom;
public Convert(){
fahrenheitBoxFrom = new JRadioButton( "Fahrenheit", true );
celsiusBoxFrom = new JRadioButton( "Celsius", false );
kelvinBoxFrom = new JRadioButton( "Kelvin", false );
radioFrom = new ButtonGroup();
radioFrom.add( fahrenheitBoxFrom );
radioFrom.add( celsiusBoxFrom );
radioFrom.add( kelvinBoxFrom );
label3 = new JLabel( "Input" );
label4 = new JLabel( "Output" );
fahrenheitBoxTo = new JRadioButton( "Fahrenheit", false );
celsiusBoxTo = new JRadioButton( "Celsius", true );
kelvinBoxTo = new JRadioButton( "Kelvin", false );
radioTo = new ButtonGroup();
radioTo.add( fahrenheitBoxTo );
radioTo.add( celsiusBoxTo );
radioTo.add( kelvinBoxTo );
convertFrom = new JPanel();
convertFrom.setLayout( new GridLayout( 4, 1 ) );
convertFrom.add(new JLabel( "Input Scale" ));
convertFrom.add( fahrenheitBoxFrom );
convertFrom.add( celsiusBoxFrom );
convertFrom.add( kelvinBoxFrom );
convertTo = new JPanel();
convertTo.setLayout( new GridLayout( 4, 1 ) );
convertTo.add(new JLabel( "Output Scale" ));
convertTo.add( fahrenheitBoxTo );
convertTo.add( celsiusBoxTo );
convertTo.add( kelvinBoxTo );
temperature1 = new JTextField( 10 );
top = new JPanel();
top.setLayout(new GridLayout(1, 2));
top.add(label3);
top.add(temperature1);
temperature1.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent event ){
int convertTemp, temp;
temp = Integer.parseInt( ( ( JTextField ) event.getSource() ).getText() );
if ( fahrenheitBoxFrom.isSelected() && celsiusBoxTo.isSelected() ){
convertTemp = ( int ) ( 5.0f / 9.0f * ( temp - 32 ) );
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( fahrenheitBoxFrom.isSelected() && kelvinBoxTo.isSelected() ){
convertTemp = ( int ) ( 5.0f / 9.0f * ( temp - 32 ) + 273 );
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( celsiusBoxFrom.isSelected() && fahrenheitBoxTo.isSelected() ){
convertTemp = ( int ) ( 9.0f / 5.0f * temp + 32 );
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( celsiusBoxFrom.isSelected() && kelvinBoxTo.isSelected()){
convertTemp = temp + 273;
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( kelvinBoxFrom.isSelected() && celsiusBoxTo.isSelected()){
convertTemp = temp - 273;
temperature2.setText( String.valueOf( convertTemp ) );
}
else if ( kelvinBoxFrom.isSelected() && fahrenheitBoxTo.isSelected()){
convertTemp = ( int ) ( 9.0f / 5.0f * ( temp - 273 ) + 32 );
temperature2.setText( String.valueOf( convertTemp ) );
}
}
});
temperature2 = new JTextField( 10 );
temperature2.setEditable( false );
bottom = new JPanel();
bottom.setLayout(new GridLayout(1, 2));
bottom.add(label4);
bottom.add(temperature2);
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add( top, BorderLayout.NORTH );
container.add( convertFrom, BorderLayout.WEST );
container.add( convertTo, BorderLayout.EAST );
container.add( bottom, BorderLayout.SOUTH );
setSize( 350,250);
setVisible( true );
}
public static void main ( String args[] ){
Convert application = new Convert();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
BoxLayout can place components centered. BoxLayout respects the setAlignmentX property of a component (see also the answers to this question).
One caveat though: you'll have to manage a component's maximum size if it is configured to take the full available width of the window (like a text-field is). Here is how you can do it for the "bottom" panel:
javax.swing.Box bottomBox = Box.createHorizontalBox();
bottom = new JPanel();
bottomBox.add(bottom);
bottom.setAlignmentX(java.awt.Component.CENTER_ALIGNMENT);
bottom.add(label4);
temperature2.setMaximumSize(temperature2.getPreferredSize());
bottom.add(temperature2);
...
container.add( bottomBox, BorderLayout.SOUTH );
You can do a similar thing for the "top" panel.
You can use GridBagLayout for this task. it will easily place your components in a 4x6 grid and you can pretty much specify the desired spacing between components using GridBagConstraints. I would use this layout.
I've been trying to follow the information here and and the code here and I'm having some difficulty.
The database query works and I've outputted it successfully to console. Following the above guides I've since added some code that puts the ResultSet data into the required Vectors. This is my code:
public class Reports extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField dateFromYYYY;
private JTextField dateFromMM;
private JTextField dateFromDD;
private JTextField dateToYYYY;
private JTextField dateToMM;
private JTextField dateToDD;
private JTextField ownerNameInput;
private JTextField petNameInput;
private JTextField doctorNameInput;
private JCheckBox isPaid = new JCheckBox("Is Paid");
public static JTable table;
public static boolean printTable = true;
private String printHeader;
// Static Variables
private final static String BOOKINGS_TABLES = "FROM Doctor, Pet, Treatment, Visit ";
/**
* Create the frame.
*/
private void SearchFrame() {
setTitle("Generate a Report");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 981, 551);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblWhatWouldYou = new JLabel("What would you like a report for?");
lblWhatWouldYou.setBounds(36, 10, 200, 50);
contentPane.add(lblWhatWouldYou);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(260, 60, 690, 370);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
private void DateFields(){
// From Date
//Year
JLabel lblFromDate = new JLabel("From dd:");
lblFromDate.setBounds(20, 180, 165, 25);
contentPane.add(lblFromDate);
JLabel lblFromYear = new JLabel("yyyy:");
lblFromYear.setBounds(180, 180, 165, 25);
contentPane.add(lblFromYear);
dateFromYYYY = new JTextField();
dateFromYYYY.setBounds(210, 180, 40, 25);
contentPane.add(dateFromYYYY);
//Month
JLabel lblFromMonth = new JLabel("mm:");
lblFromMonth.setBounds(128, 180, 165, 25);
contentPane.add(lblFromMonth);
dateFromMM = new JTextField();
dateFromMM.setBounds(155, 180, 20, 25);
contentPane.add(dateFromMM);
dateFromDD = new JTextField();
dateFromDD.setBounds(100, 180, 20, 25);
contentPane.add(dateFromDD);
// To Date
//Year
JLabel lblToDate = new JLabel("To dd:");
lblToDate.setBounds(20, 210, 165, 25);
contentPane.add(lblToDate);
JLabel lblToYear = new JLabel("yyyy:");
lblToYear.setBounds(180, 210, 165, 25);
contentPane.add(lblToYear);
dateToYYYY = new JTextField();
dateToYYYY.setBounds(210, 210, 40, 25);
contentPane.add(dateToYYYY);
//Month
JLabel lblToMonth = new JLabel("mm:");
lblToMonth.setBounds(128, 210, 165, 25);
contentPane.add(lblToMonth);
dateToMM = new JTextField();
dateToMM.setBounds(155, 210, 20, 25);
contentPane.add(dateToMM);
dateToDD = new JTextField();
dateToDD.setBounds(100, 210, 20, 25);
contentPane.add(dateToDD);
}
private void PetName(){
JLabel lblPetName = new JLabel("Pet Name:");
lblPetName.setBounds(20, 90, 165, 25);
contentPane.add(lblPetName);
petNameInput = new JTextField();
petNameInput.setBounds(100, 90, 150, 25);
contentPane.add(petNameInput);
}
private void OwnerName(){
JLabel lblOwnerName = new JLabel("Owner Name:");
lblOwnerName.setBounds(20, 120, 165, 25);
contentPane.add(lblOwnerName);
ownerNameInput = new JTextField();
ownerNameInput.setBounds(100, 120, 150, 25);
contentPane.add(ownerNameInput);
}
private void DoctorName(){
JLabel lblDoctorName = new JLabel("Doctor Name:");
lblDoctorName.setBounds(20, 150, 165, 25);
contentPane.add(lblDoctorName);
doctorNameInput = new JTextField();
doctorNameInput.setBounds(100, 150, 150, 25);
contentPane.add(doctorNameInput);
}
private void IsPaidCheckBox(){
isPaid.setBounds(155, 250, 97, 25);
contentPane.add(isPaid);
}
public void Bookings() {
// Local variables
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
// Instantiate the frame
SearchFrame();
// Set search fields
PetName();
OwnerName();
DoctorName();
IsPaidCheckBox();
DateFields();
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String queryString00 = "";
String queryString01 = "SELECT pet.petname AS [Pet Name], pet.ownerName AS [Owner Name], doctor.doctorName AS [Doctor Name], visit.visitDate AS [Visit Date], treatment.treatmentName AS [Treatment Name], visit.ispaid AS [Is Paid] ";
String queryString03 = "WHERE Visit.petID = Pet.petID ";
String queryString02 = " GROUP BY visitID;";
// build the query
if(!(petNameInput.getText().equals("")))
queryString00 = queryString01 + BOOKINGS_TABLES + queryString03 + "AND petname LIKE " + "'%" + petNameInput.getText() + "%'";
else queryString00 = queryString01 + BOOKINGS_TABLES + queryString03;
if(!(ownerNameInput.getText().equals("")))
queryString00 = queryString00 + "AND ownername LIKE " + "'%" + ownerNameInput.getText() + "%'";
if(!(doctorNameInput.getText().equals("")))
queryString00 = queryString00 + "AND doctorname LIKE " + "'%" + doctorNameInput.getText() + "%'";
if(!(dateFromYYYY.getText().equals(""))){
String fromString = dateFromYYYY.getText() + "-" + dateFromMM.getText() + "-" + dateFromDD.getText();
queryString00 = queryString00 + " AND visitdate >= '" + fromString + "'";
}
if(!(dateToYYYY.getText().equals(""))){
String toString = dateToYYYY.getText() + "-" + dateToMM.getText() + "-" + dateToDD.getText();
queryString00 = queryString00 + " AND visitdate <= '" + toString + "'";
}
if(isPaid.isSelected())
queryString00 = queryString00 + " AND ispaid = 'Y'";
queryString00 = queryString00 + queryString02;
// System.out.println(queryString00);
DatabaseConnection db = new DatabaseConnection();
db.openConn();
// Get query
ResultSet rs = db.getSearch(queryString00);
ResultSetMetaData md = null;
// Set up vectors for table output
// Output query to screen (Much of the following code is adapted from http://www.camick.com/java/source/TableFromDatabase.java)
try{
md = rs.getMetaData();
int columnCount = md.getColumnCount();
// Get column names
for(int i = 1; i <= columnCount; i++)
columnNames.addElement(md.getColumnName(i));
while(rs.next()){
// System.out.printf("%-15s%-15s%-15s%-15s%-15s%-15s\n", rs.getString("Pet Name"), rs.getString("Owner Name"), rs.getString("Doctor Name"), rs.getString("Visit Date"), rs.getString("Treatment Name"), rs.getString("Is Paid"));
Vector<Object> row = new Vector<Object>(columnCount);
for(int i = 1; i <= columnCount; i++)
row.addElement(rs.getObject(i));
data.addElement(row);
}
}
catch (SQLException e) {
e.printStackTrace();
}
db.closeConn();
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
/**
*
*/
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
#Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
// Out put to the table (theoretically)
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
// JScrollPane scrollPane = new JScrollPane( table );
// getContentPane().add( scrollPane );
});
btnSearch.setBounds(36, 460, 165, 25);
contentPane.add(btnSearch);
JLabel resultLabel = new JLabel("Reports will be printed below");
resultLabel.setBounds(515, 10, 312, 50);
contentPane.add(resultLabel);
JButton printReport = new JButton("Print Report");
printReport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String resultLabelPrint = resultLabel.getText();
MessageFormat footer = new MessageFormat(resultLabelPrint);
MessageFormat header = new MessageFormat(printHeader);
boolean complete =table.print(JTable.PrintMode.FIT_WIDTH, header , footer );
if (complete) {
/* show a success message */
} else {
/*show a message indicating that printing was cancelled */
}
} catch (PrinterException pe) {
/* Printing failed, report to the user */
}
}
});
printReport.setBounds(473, 460, 227, 25);
contentPane.add(printReport);
}
}
The final part of the code, which I believe out puts to the table, gives me some weird errors.
// Out put to the table (theoretically)
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
// JScrollPane scrollPane = new JScrollPane( table );
// getContentPane().add( scrollPane );
The first line gives me a syntax error on the semi-colon (;), specifically, Syntax error on token ";", invalid AssignmentOperator. I get the same when I try the 'model' variable.
When I uncomment the last two lines I get 'Syntax error on token ".", { expected' and the Eclipse demands another closing { despite there not being a corresponding opening }. If I add it then I get more errors.
I suspect this has something to do with the class structure of the code that I'm trying to follow but I'm having no luck in following those either.
All I want to do is to take the information that I have and output it in the table which is already there. How do I do this?
You're not showing all the error messages nor the complete error messages (please fix this). The most important one is the, Cannot refer to the non-final local variable data defined in an enclosing scope message. So make the variables final -- one problem solved.
public void Bookings() {
// Local variables
final Vector<Object> columnNames = new Vector<Object>(); //!! made final
final Vector<Object> data = new Vector<Object>();
The other problem is that this code:
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
Is being called outside of any and all methods. You need to match up your curly braces carefully.
Question that confuses me about your code though -- why create a TableModel and not use it as a model for your JTable?
scrollPane is not a global instance.
Move JScrollPane scrollPane out of your method SearchFrame() and place it into your list of instance variables for the class.
That is only your immediate and first issue, your other issue is that your are attempting to access instance variables defined in Reports within the scope of 2x nested anonymous classes.
You should parametarize your GUI methods to accept the components for injection into the panels.
public class Reports extends JFrame {
JScrollPane scrollPane;
...
private void SearchFrame() {
scrollPane = new JScrollPane ();
}
...
public void Bookings() {
scrollPane...
...
}
...
}
So I am having a problem with my Java program. I currently want it to have 3 main course options Hamburger, Pizza, and Salad with add on options. Now currently the program starts with Hamburger selected and the add-ons available they calculate price as well. When the main item is selected the add-on options should change with the new item however they don't. I have been staring at this for awhile now so it could be I am missing something really simple like clearing the area and then having the new add-on options show. In any case any help would be appreciated, here is the current code.
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
public class LunchOrder extends JFrame {
private JRadioButton hamburgerJButton, pizzaJButton, saladJButton;
private JCheckBox lettuceButton, mayonnaiseButton, mustardButton, pepperoniButton,
sausageButton, mushroomsButton, croutonsButton, baconBitsButton, breadSticksButton;
private JLabel subTotal, tax, totalDue;
private JTextField subTotalText, taxText, totalDueText;
private JButton placeOrder, clearOrder, exitButton;
// no-argument constructor
public LunchOrder()
{
createUserInterface();
}
// create and position GUI components; register event handlers
private void createUserInterface()
{
// get content pane for attaching GUI components
Container contentPane = getContentPane();
// enable explicit positioning of GUI components
contentPane.setLayout( null);
hamburgerJButton = new JRadioButton("Hamburger - $6.95" );
hamburgerJButton.setSelected(true);
pizzaJButton = new JRadioButton("Pizza - $5.95");
pizzaJButton.setSelected(false);
saladJButton = new JRadioButton("Salad - $4.95");
saladJButton.setSelected(false);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(hamburgerJButton);
bgroup.add(pizzaJButton);
bgroup.add(saladJButton);
JPanel mainCourse = new JPanel();
mainCourse.setLayout( new GridLayout( 3, 1 ));
mainCourse.setBounds( 10, 10, 150,135 );
mainCourse.add(hamburgerJButton);
mainCourse.add(pizzaJButton);
mainCourse.add(saladJButton);
mainCourse.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Main course" ) );
//contentPane.add( mainCourseJPanel, BorderLayout.NORTH );
contentPane.add( mainCourse );
//Add action listener to created button
//JCheckBox
lettuceButton = new JCheckBox("Lettuce, tomato, and onions");
lettuceButton.setSelected(true);
mayonnaiseButton= new JCheckBox("Mayonnaise");
mayonnaiseButton.setSelected(false);
mustardButton = new JCheckBox("Mustard");
mustardButton.setSelected(true);
pepperoniButton = new JCheckBox("Pepperoni");
sausageButton= new JCheckBox("Sausage");
mushroomsButton = new JCheckBox("Mushrooms");
croutonsButton = new JCheckBox("Croutons");
baconBitsButton= new JCheckBox("Bacon bits");
breadSticksButton = new JCheckBox("Bread sticks");
//JPanel addons
JPanel addOns = new JPanel();
GridLayout addOnGlay = new GridLayout(3,3);
addOns.setLayout(addOnGlay);
addOns.setBounds( 250, 10, 250, 135 );
addOns.add(lettuceButton);
addOns.add(pepperoniButton);
addOns.add(croutonsButton);
addOns.add(mayonnaiseButton);
addOns.add(sausageButton);
addOns.add(baconBitsButton);
addOns.add(mustardButton);
addOns.add(mushroomsButton);
addOns.add(breadSticksButton);
pepperoniButton.setVisible(false);
sausageButton.setVisible(false);
mushroomsButton.setVisible(false);
croutonsButton.setVisible(false);
baconBitsButton.setVisible(false);
breadSticksButton.setVisible(false);
addOns.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Add ons($.25/each)" ) );
contentPane.add( addOns );
// subtotal JLabel
subTotal = new JLabel();
subTotal.setBounds(10, 110, 100, 200);
contentPane.add(subTotal);
subTotal.setText( "Subtotal: " );
subTotal.setHorizontalAlignment(JLabel.RIGHT);
// subtotal JTextField
subTotalText = new JTextField();
subTotalText.setBounds(115, 200, 80, 22);
subTotalText.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(subTotalText);
// Tax JLabel
tax = new JLabel();
tax.setBounds(10, 135, 100, 200);
contentPane.add(tax);
tax.setText("Tax(7.85%) ");
tax.setHorizontalAlignment(JLabel.RIGHT);
// Tax JTextField
taxText = new JTextField();
taxText.setBounds(115, 225, 80, 22);
contentPane.add(taxText);
// total due JLabel
totalDue = new JLabel();
totalDue.setBounds(10, 160, 100, 200);
contentPane.add(totalDue);
totalDue.setText("Total due: " );
totalDue.setHorizontalAlignment(JLabel.RIGHT);
// total due JTextField
totalDueText = new JTextField();
totalDueText.setBounds(115, 250, 80, 22);
contentPane.add(totalDueText);
// order total JPanel
JPanel orderTotal = new JPanel();
GridLayout orderGLay = new GridLayout(3,1);
orderTotal.setLayout(orderGLay);
orderTotal.setBounds(10, 170, 200, 125 );
orderTotal.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Order total" ) );
contentPane.add( orderTotal );
// place order JButton
placeOrder = new JButton();
placeOrder.setBounds( 252, 175, 100, 24 );
placeOrder.setText( "Place order" );
contentPane.add( placeOrder );
placeOrder.addActionListener(
new ActionListener() // anonymous inner class
{
// event handler called when calculateJButton is pressed
public void actionPerformed(ActionEvent event) {
placeOrderActionPerformed(event);
}
} // end anonymous inner class
); // end call to addActionListener
// set up clearOrderJButton
clearOrder = new JButton();
clearOrder.setBounds(252,210, 100, 24 );
clearOrder.setText( "Clear order" );
contentPane.add( clearOrder );
clearOrder.addActionListener(
new ActionListener() // anonymous inner class
{
// event handler called when calculateJButton is pressed
public void actionPerformed(ActionEvent event) {
clearOrderActionPerformed(event);
}
} // end anonymous inner class
); // end call to addActionListener
// set up exitJButton
exitButton = new JButton();
exitButton.setBounds( 425, 260, 70, 24 );
exitButton.setText( "Exit" );
contentPane.add( exitButton );
// set properties of application's window
setTitle( "Lunch order" ); // set window title
setResizable(true); // prevent user from resizing window
setSize( 525, 350 ); // set window size
setVisible( true ); // display window
setLocationRelativeTo(null);
}
// calculate subtotal plus tax
private void placeOrderActionPerformed(ActionEvent event) {
DecimalFormat dollars = new DecimalFormat("$0.00");
// declare double variables
double hamburgerPrice = 6.95;
double pizzaPrice = 5.95;
double saladPrice = 4.95;
double addons = 0;
double subTotPrice;
double taxPercent;
double totalDuePrice;
if ( hamburgerJButton.isSelected())
{
if( lettuceButton.isSelected()){
addons += 0.25;
}
if( mayonnaiseButton.isSelected()){
addons += 0.25;
}
if( mustardButton.isSelected()){
addons += 0.25;
}
else{
addons -= 0.25;
}
subTotPrice = hamburgerPrice + addons;
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
if ( pizzaJButton.isSelected())
{
//lettuceButton.setVisible(false);
//mayonnaiseButton.setVisible(false);
//mustardButton.setVisible(false);
croutonsButton.setVisible(false);
baconBitsButton.setVisible(false);
breadSticksButton.setVisible(false);
pepperoniButton.setVisible(true);
sausageButton.setVisible(true);
mushroomsButton.setVisible(true);
//calculation for pizza selection
if( pepperoniButton.isSelected())
addons += 0.25;
if( sausageButton.isSelected())
addons += 0.25;
if( mushroomsButton.isSelected())
addons += 0.25;
else
addons -= 0.25;
subTotPrice = (pizzaPrice + addons);
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
if ( saladJButton.isSelected())
{
croutonsButton.setVisible(true);
baconBitsButton.setVisible(true);
breadSticksButton.setVisible(true);
if( croutonsButton.isSelected())
addons += 0.25;
if( baconBitsButton.isSelected())
addons += 0.25;
if( breadSticksButton.isSelected())
addons += 0.25;
else
addons -= 0.25;
//calculation for salad selection
subTotPrice = (saladPrice + addons);
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
} // end method calculateJButtonActionPerformed
private void clearOrderActionPerformed(ActionEvent event) {
//reset hamburger and addons to default state
hamburgerJButton.setSelected(true);
lettuceButton.setSelected(true);
mayonnaiseButton.setSelected(false);
mustardButton.setSelected(true);
subTotalText.setText("");
taxText.setText("");
totalDueText.setText("");
} // end method calculateJButtonActionPerformed
public static void main( String args[] )
{
LunchOrder application = new LunchOrder();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
You've not added any listeners that could notify of any kind of state change, Java can't magically know what you want it to...I wish...
You could use a ItemListener on each of the buttons, and based on what's selected, make a change to your UI, for example...
Create you're self a ItemListener...
ItemListener il = new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Hamburger = " + hamburgerJButton.isSelected());
System.out.println("Pizza = " + pizzaJButton.isSelected());
System.out.println("Salad = " + saladJButton.isSelected());
}
}
};
And after you've initalised your buttons, register it with each of them...
hamburgerJButton.addItemListener(il);
pizzaJButton.addItemListener(il);
saladJButton.addItemListener(il);
Take a look at How to use buttons for more details
I'm writing a Java code to represent the grades that students achieved in an exam. When you input the number 10 in the bar labelled # of grade As, and input the number 20 in the bar labelled # of grade Bs, and do it until you reach # of grade E, and then you click on the label "Display bar chart", you get a chart with the output Grade As : 10 ....Grade Bs : 20............Grade E : something. My question to you is this. If, instead of having the output Grade A : 10, I want the output AAAAAAAAAA (ie the letter A written out 10 times), how do I do it? I've thought about it all day but still can't come up with an answer.
Second (related) question: if NO students achieve any particular grade (let's say nobody scored an A), then there should be no grade letters displayed in that bar (the bar for grade A). Could someone please tell me how I should modify my code to take this into account? Here is my code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class GradeChart extends JFrame
implements ActionListener {
private JTextField gradeAField = new JTextField( 5 );
private JTextField gradeBField = new JTextField( 5 );
private JTextField gradeCField = new JTextField( 5 );
private JTextField gradeDField = new JTextField( 5 );
private JTextField gradeEField = new JTextField( 5 );
private int gradeAs;
private int gradeBs;
private int gradeCs;
private int gradeDs;
private int gradeEs;
private JButton displayChartButton = new JButton( "Display bar chart" );
private JButton displayDataFieldsButton = new JButton( "Clear data fields" );
private JPanel chartPanel = new JPanel();
private Color chartPanelColor = Color.cyan;
private final Font labelFont = new Font( "Serif", Font.BOLD, 16 );
// Various fixed coordinates and dimensions
private final int chartLeftXA = 30;
private final int chartLeftXB = 30;
private final int chartLeftXC = 30;
private final int chartLeftXD = 30;
private final int chartLeftXE = 30;
private final int chartTopYA = 50;
private final int chartTopYB = 102;
private final int chartTopYC = 154;
private final int chartTopYD = 206;
private final int chartTopYE = 258;
public static void main( String[] args ) {
GradeChart chart = new GradeChart();
chart.setSize( 550, 550 );
chart.createGUI();
chart.setVisible( true );
}
private void createGUI() {
// Set up main window characteristics
setDefaultCloseOperation( EXIT_ON_CLOSE );
Container window = getContentPane();
window.setLayout( new FlowLayout() );
JLabel gradeAFieldLabel = new JLabel( "# of grade As:" );
gradeAFieldLabel.setFont( labelFont );
window.add( gradeAFieldLabel );
window.add( gradeAField );
JLabel gradeBFieldLabel = new JLabel( "# of grade Bs:" );
gradeBFieldLabel.setFont( labelFont );
window.add( gradeBFieldLabel );
window.add( gradeBField );
JLabel gradeCFieldLabel = new JLabel( "# of grade Cs:" );
gradeCFieldLabel.setFont( labelFont );
window.add( gradeCFieldLabel );
window.add( gradeCField );
JLabel gradeDFieldLabel = new JLabel( "# of grade Ds:" );
gradeDFieldLabel.setFont( labelFont );
window.add( gradeDFieldLabel );
window.add( gradeDField );
JLabel gradeEFieldLabel = new JLabel( "# of grade Es:" );
gradeEFieldLabel.setFont( labelFont );
window.add( gradeEFieldLabel );
window.add( gradeEField );
window.add( displayChartButton );
displayChartButton.addActionListener( this );
window.add( displayDataFieldsButton );
displayDataFieldsButton.addActionListener( this );
chartPanel.setPreferredSize( new Dimension( 450, 300 ) );
chartPanel.setBackground( chartPanelColor );
window.add( chartPanel );
}
public void actionPerformed( ActionEvent e ) {
if ( e.getSource() == displayChartButton ) {
checkAndRecordData();
Graphics g = chartPanel.getGraphics();
g.setColor(Color.white);
g.fillRect(20,20,410,52);
g.setColor(Color.black);
g.drawRect(20,20,410,52);
g.setColor( Color.black );
g.drawString( "Grade As: " + gradeAs, chartLeftXA, chartTopYA );
g.setColor(Color.white);
g.fillRect(20,72,410,52);
g.setColor(Color.black);
g.drawRect(20,72,410,52);
g.setColor( Color.black );
g.drawString( "Grade Bs: " + gradeBs, chartLeftXB, chartTopYB );
g.setColor(Color.white);
g.fillRect(20,124,410,52);
g.setColor(Color.black);
g.drawRect(20,124,410,52);
g.setColor( Color.black );
g.setColor( Color.black );
g.drawString( "Grade Cs: " + gradeCs, chartLeftXC, chartTopYC );
g.setColor(Color.white);
g.fillRect(20,176,410,52);
g.setColor(Color.black);
g.drawRect(20,176,410,52);
g.setColor( Color.black );
g.setColor( Color.black );
g.drawString( "Grade Ds: " + gradeDs, chartLeftXD, chartTopYD );
g.setColor(Color.white);
g.fillRect(20,228,410,52);
g.setColor(Color.black);
g.drawRect(20,228,410,52);
g.setColor( Color.black );
g.setColor( Color.black );
g.drawString( "Grade Es: " + gradeEs, chartLeftXE, chartTopYE );
}
if ( e.getSource() == displayDataFieldsButton ) {
gradeAField.setText("");
gradeBField.setText("");
gradeCField.setText("");
gradeDField.setText("");
gradeEField.setText("");
}
} // End of actionPerformed
private void checkAndRecordData() {
int tempAs = 0;
int tempBs = 0;
int tempCs = 0;
int tempDs = 0;
int tempEs = 0;
tempAs = Integer.parseInt( gradeAField.getText() );
tempBs = Integer.parseInt( gradeBField.getText() );
tempCs = Integer.parseInt( gradeCField.getText() );
tempDs = Integer.parseInt( gradeDField.getText() );
tempEs = Integer.parseInt( gradeEField.getText() );
gradeAs = tempAs;
gradeBs = tempBs;
gradeCs = tempCs;
gradeDs = tempDs;
gradeEs = tempEs;
}
Use a loop:
String longString = "";
for (int i=0; i<numOfLetter; i++) {
longString += gradeLetter;
}
Or, if you have Apache Commons available:
String longString = StringUtils.repeat(gradeLetter, numOfLetter);
If you only need a few:
String someAs = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".substring(0, length);