After button event the second panel is empty - java

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.

Related

How do I not repeat code when setting JLabel font and foreground over and over again

I am wondering what the fastest way to setFont and foreground for JLabels would be because right now I find myself repeating the same code over and over again. Here is what I have and if anyone know how I could refine this I would greatly appreciate it!
header.setHorizontalAlignment( JLabel.CENTER );
header.setVerticalAlignment( JLabel.TOP );
header.setFont( new Font( "Impact", Font.PLAIN, 40 ) );
header.setForeground( Color.LIGHT_GRAY );
name.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
name.setForeground( Color.LIGHT_GRAY );
temperament.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
temperament.setForeground( Color.LIGHT_GRAY );
lifeSpan.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
lifeSpan.setForeground( Color.LIGHT_GRAY );
origin.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
origin.setForeground( Color.LIGHT_GRAY );
starHeader.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
starHeader.setForeground( Color.LIGHT_GRAY );
affectionStar.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
affectionStar.setForeground( Color.LIGHT_GRAY );
childStar.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
childStar.setForeground( Color.LIGHT_GRAY );
childStar.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
childStar.setForeground( Color.LIGHT_GRAY );
energyStar.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
energyStar.setForeground( Color.LIGHT_GRAY );
dogStar.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
dogStar.setForeground( Color.LIGHT_GRAY );
shedStar.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
shedStar.setForeground( Color.LIGHT_GRAY );
socialStar.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
socialStar.setForeground( Color.LIGHT_GRAY );
healthStar.setFont( new Font( "Impact", Font.PLAIN, 20 ) );
healthStar.setForeground( Color.LIGHT_GRAY );
You could utilize a JLabel Array. It might go something like this (in whatever method...):
String[] labelNames = {"Header", "Name", "Temperament", "LifeSpan", "Origin",
"StarHeader", "AffectionStar", "ChildStar", "energyStar",
"DogStar", "ShedStar", "SocialStar", "HealthStar"};
java.awt.Color grayColor = java.awt.Color.LIGHT_GRAY;
java.awt.Font font = new java.awt.Font( "Impact", java.awt.Font.PLAIN, 20);
javax.swing.JLabel[] label = new javax.swing.JLabel[labelNames.length];
/* Demo Mouse Handler class for the label[] array
if you decide you want a mouseListener for your
JLabels */
LabelslMouseHandler labelsMouseHandler = new LabelsMouseHandler();
for (int i = 0; i < labelNames.length; i++) {
label[i] = new javax.swing.JLabel();
label[i].setFont(font);
label[i].setForeground(grayColor);
label[i].setName(labelNames[i]);
/* If you want to apply common event handlers
then you would do that here as well, for
example.... */
label[i].addMouseListener(labelsMouseHandler);
// Add to panel component here with the desired
// set Layout manager...
}
// ----------------------------------------------------------------------
// Inner Class - A Mouse Handler for ALL JLabels within the label[] array
private class LabelsMouseHandler extends java.awt.event.MouseAdapter {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
javax.swing.JLabel source = (javax.swing.JLabel) evt.getSource();
String name = source.getName();
JOptionPane.showMessageDialog(null, "You clicked on the " + name + " JLabel",
"Mouse Click Event", JOptionPane.INFORMATION_MESSAGE);
}
#Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
// Do what you want for MouseEntered
}
#Override
public void mouseExited(java.awt.event.MouseEvent evt) {
// Do what you want for MouseExited
}
}
By the way, in your listing you have set childStar label properties twice.

Closing JFrames with Windows event [closed]

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);

How to center objects within a panel that is already laid out with borderlayout

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.

Java SWT make a Label Scrollable

I have a Label in a Group in SWT and if it contains many lines of text, I would like to make it scrollable vertically. Setting the style parameter with SWT.V_SCROLL doesn't seem to do it. How can I do this?
Label does not support scrolling.
You could use a read only Text control which will scroll:
Text text = new Text(parent, SWT.READ_ONLY | SWT.V_SCROLL);
Here is a way
ScrolledComposite ivScrollComposite = new ScrolledComposite( ivShell, SWT.V_SCROLL );
ivScrollComposite.addControlListener( new ScrollCompositeControlListener() );
ivScrollComposite.setExpandVertical( true );
ivScrollComposite.setExpandHorizontal( true );
ivScrollComposite.setAlwaysShowScrollBars( true );
Composite ivCompositeResults = new Composite( ivScrollComposite, SWT.NONE );
Label ivLabelResults = new Label( ivCompositeResults, SWT.WRAP );
ivScrollComposite.setContent( ivCompositeResults );
ivScrollComposite.setLayout( new FormLayout() );
FormData formData = new FormData();
formData.top = new FormAttachment( 0, 0 );
formData.left = new FormAttachment( 0, 0 );
formData.right = new FormAttachment( 100, 0 );
formData.bottom = new FormAttachment( 100, 0 );
ivCompositeResults.setLayoutData( formData );
ivCompositeResults.setLayout( new FormLayout() );
formData = new FormData();
formData.top = new FormAttachment( 0, 0 );
formData.left = new FormAttachment( 0, 0 );
formData.right = new FormAttachment( 100, 0 );
formData.bottom = new FormAttachment( 100, 0 );
ivLabelResults.setLayoutData( formData );
then
private void resizeScroll()
{
Rectangle r = ivScrollComposite.getClientArea();
ivScrollComposite.setMinSize( ivCompositeResults.computeSize( r.width, SWT.DEFAULT ) );
}
private class ScrollCompositeControlListener extends ControlAdapter
{
#Override
public void controlResized( ControlEvent e )
{
resizeScroll();
}
}
And whenever you change the Label text
ivLabelResults.setText( "some text" );
resizeScroll();

How to represent 3As as "AAA" or 3Bs as BBB in Java

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);

Categories