if statement with adding many picture in java swing - java

Hi I'm working on a program that requires to a take a random number of dice 1-6
I want to show a picture for any number show .
Here I initialized the pictures with jlable
JLabel diceNumber;
Random r = new Random();
int roll;
ImageIcon dicePic1 = new ImageIcon("dice1_.png");
ImageIcon dicePic2 = new ImageIcon("dice2.png");
ImageIcon dicePic3 = new ImageIcon("dice3.png");
ImageIcon dicePic4 = new ImageIcon("dice4.png");
ImageIcon dicePic5 = new ImageIcon("dice5.png");
ImageIcon dicePic6 = new ImageIcon("dice6.png");
JLabel diceNum1 = new JLabel("", dicePic1, JLabel.CENTER);
JLabel diceNum2 = new JLabel("", dicePic2, JLabel.CENTER);
JLabel diceNum3 = new JLabel("", dicePic3, JLabel.CENTER);
JLabel diceNum4 = new JLabel("", dicePic4, JLabel.CENTER);
JLabel diceNum5 = new JLabel("", dicePic5, JLabel.CENTER);
JLabel diceNum6 = new JLabel("", dicePic6, JLabel.CENTER);
this is the panel where one picture will appear
with if statements and I have to initialize diceNumber
JPanel panel6 = new JPanel();
diceNumber = new JLabel("1");
if (diceNumber.getText().equals("1")) {
panel6.add(diceNum1);
}
else if (diceNumber.getText().equals("2")) {
panel6.add(diceNum2);
}
else if (diceNumber.getText().equals("3")) {
panel6.add(diceNum3);
}
else if (diceNumber.getText().equals("4")) {
panel6.add(diceNum4);
}
else if (diceNumber.getText().equals("5")) {
panel6.add(diceNum5);
}
else if (diceNumber.getText().equals("6")) {
panel6.add(diceNum6);
}
here when I start rolling
public void actionPerformed(ActionEvent e) {
if (e.getSource() == dice) {
roll = r.nextInt(6) + 1;
if (roll == 1) {
diceNumber.setText("1");
}
else if (roll == 2) {
diceNumber.setText("2");
}
else if (roll == 3) {
diceNumber.setText("3");
}
else if (roll == 4) {
diceNumber.setText("4");
}
else if (roll == 5) {
diceNumber.setText("5");
}
else if (roll == 6) {
diceNumber.setText("6");
}
the problem is thath diceNumber always takes the value "1" and never change
any help ?

diceNumber = new JLabel("1");
immediately precedes the logical checks on the diceNumber text. At this stage, you have initiated a JLabel with the text "1", hence it will always be "1" at this stage. You don't change the text until much later, at which stage you no longer check to set the Dice image. The approach you have taken resembles a Rube Goldberg machine; triggering a series of events to perform a relatively simple task. A simple solution would be:
List<JLabel> disc = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
disc.add(new ImageIcon(String.format("dice%d_.png", i));
}
Then when you need to change the image you call:
int roll = r.nextInt(6) + 1;
panel.add(disc[roll]);
Regardless, there are many improvements that can be made to the code as it is; I would recommend that you change the excessive amount of if statements to:
diceNumber.setText(roll.toString()); or
diceNumber.setText(roll + "");

In your actionPerformed() method, you change the text of the diceNumber label, and that's all you're doing. You don't change the image displayed by the image label.
You should really really learn about arrays, and store your 6 images in an array. Your logic should be:
init() {
// add a label displaying the number (1 by default)
// add a label displaying the icon (1 by default)
}
actionPerformed() {
// choose a random number
// change the text of the number label
// change the icon of the image label
}
And to do that, ni need for big chain of if statements: it should just be
imageLabel.setIcon(images[randomRoll - 1]);

Related

Centering GUI's

I've created a simple guessing game with GUI's. The problem is, whenever I maximize my window, the whole GUI is stuck in the top middle. I would like to know how to center it in the middle and how to make it bigger. Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuessingGameNew implements ActionListener {
private final double VERSION = 2.3;
//Initializing Main Window and Difficulty Window
JFrame window = new JFrame("Guess The Number " + VERSION);
JFrame DiffFrame = new JFrame("Difficulty");
JButton btnNewGame = new JButton("New Game");
JButton btnInstruction = new JButton("Instructions");
JButton btnDifficulty = new JButton("Change Difficulty");
JButton btnAbout = new JButton("About");
JButton btnExit = new JButton("Exit");
JButton btnOK = new JButton("Ok");
JButton btnDiff[] = new JButton[6];
//Making Panel for Main Menu Buttons
JPanel pnlMainMenu = new JPanel();
//Making Panel for Difficulty Buttons
JPanel pnlDifficulty = new JPanel();
int diff = 10;
int tries;
int Secret;
int Guess;
int option = 0;
boolean Cancel = false;
GuessingGameNew() { //constructor
//Setting Main Window properties
window.setSize(400, 300);
window.setLocation(500, 260);
window.setLayout(new FlowLayout(FlowLayout.CENTER));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DiffFrame.setSize(230, 210);
DiffFrame.setLocation(530, 230);
DiffFrame.setLayout(new BorderLayout());
//MainMenu Panel Layout and adding Main Menu Buttons
// GridLayout(int rows, int columns, int Horizontal_Gap, intVertical_Gap)
pnlMainMenu.setLayout(new GridLayout(5, 1, 2, 8));
pnlMainMenu.add(btnNewGame);
pnlMainMenu.add(btnInstruction);
pnlMainMenu.add(btnDifficulty);
pnlMainMenu.add(btnAbout);
pnlMainMenu.add(btnExit);
pnlMainMenu.setBackground(Color.red);
//Setting Layout for Difficulty Panel
pnlDifficulty.setLayout(new GridLayout(6, 1, 2, 2));
btnDiff[0] = new JButton("Very Easy (0 - 3)");
btnDiff[1] = new JButton("Easy (0 - 50)");
btnDiff[2] = new JButton("Medium (0 - 100)");
btnDiff[3] = new JButton("Hard (0 - 500)");
btnDiff[4] = new JButton("Very Hard (0 - 1000)");
btnDiff[5] = new JButton("Custom (0 - ?)");
btnNewGame.addActionListener(this);
btnInstruction.addActionListener(this);
btnDifficulty.addActionListener(this);
btnAbout.addActionListener(this);
btnExit.addActionListener(this);
btnOK.addActionListener(this);
for(int i=0; i<6; i++) {
btnDiff[i].addActionListener(this);
pnlDifficulty.add(btnDiff[i]);
}
window.add(pnlMainMenu);
window.setVisible(true);
}
public void actionPerformed(ActionEvent click) {
System.out.println("Action Performed");
if(click.getSource() == btnNewGame) {
NewGame();
}
if(click.getSource() == btnExit) {
option = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exit Game" ,JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION)
System.exit(0);
}
if(click.getSource() == btnInstruction) {
JOptionPane.showMessageDialog(null,
"Game:" + "\nClick New Game to start a new game.\nGuess a number between 0 and the selected number. Keep Guessing until you get it correct."
+ "\n\nDifficulty:" + "\nYou can change the difficulty of the game\n in the Main Menu to a Custom range or a \npreset range."
, "Instructions", JOptionPane.INFORMATION_MESSAGE);
}
if(click.getSource() == btnAbout) {
JOptionPane.showMessageDialog(null,JOptionPane.INFORMATION_MESSAGE);
}
if(click.getSource() == btnDifficulty) {
Change_Difficulty();
}
for(int i=0; i<6; i++) {
if(click.getSource() == btnDiff[i]) {
if(click.getSource() == btnDiff[0])
diff = 3;
if(click.getSource() == btnDiff[1])
diff = 50;
if(click.getSource() == btnDiff[2])
diff = 100;
if(click.getSource() == btnDiff[3])
diff = 500;
if(click.getSource() == btnDiff[4])
diff = 1000;
if(click.getSource() == btnDiff[5])
diff = Custom();
DiffFrame.setVisible(false);
}
}
}
public void NewGame() {
tries = 1;
Guess = 101;
Secret = (int)((Math.random()) * (diff + 1));
Cancel = false;
while(Guess != Secret) {
try {
if(tries == 1) {
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: 1" + "\nGuess a number between 0 and " + diff, "Guess?", JOptionPane.PLAIN_MESSAGE));
tries++;
} else {
if(Guess > Secret)
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: " + tries + "\n" + Guess + "\nGuess Lower..."));
else if(Guess < Secret)
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: " + tries + "\n" + Guess + "\nGuess Higher..."));
tries++;
}
} catch(NumberFormatException e) {
if(e.getMessage() == "null") {
option = JOptionPane.showConfirmDialog(null, "Are you sure you want to go back to the Main Menu?", "Cancel?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(option == JOptionPane.YES_OPTION) {
Cancel = true;
break;
}
}
JOptionPane.showMessageDialog(null, "Error: " + e.getMessage() + "\nEnter whole numbers only!");
}
}
if(!Cancel) {
tries--;
JOptionPane.showMessageDialog(null, Guess + " is Correct!!\nYou WON in " + tries + " tries.", "Winner", JOptionPane.INFORMATION_MESSAGE);
option = JOptionPane.showConfirmDialog(null, "Do you want to try again?", "Try Again?", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
if(option == JOptionPane.YES_OPTION)
NewGame();
}
}
public void Change_Difficulty() {
DiffFrame.add(pnlDifficulty, BorderLayout.CENTER);
DiffFrame.setVisible(true);
}
public int Custom() {
try {
diff = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a number that you want to be the range (0 to ?)", diff));
} catch(NumberFormatException e) {
}
return diff;
}
public static void main(String[] args) {
new GuessingGameNew();
}
}
You are setting a FlowLayout:
window.setLayout(new FlowLayout(FlowLayout.CENTER));
This layout has no notion of vertical alignment, it will only wrap its contents when out of horizontal space. Setting the alignment applies only to horizontal behavior.
I would like to know how to center it in the middle and how to make it bigger.
If you delete that line then the default CENTER position of BorderLayout will be used, which centers and stretches the component both horizontally and vertically:
The default Layout Manager for a JFrame is the BorderLayout. Calling window.getContentPane().add(component); or if you feel like typing more, then window.getContentPane().add(component, BorderLayout.CENTER); adds your component to the center of the window. Also, as a tip, do study Layout Managers deeply. You can build really cool stuff with the proper understanding of how they work, what they do, and which one is more appropriate for which scenario.

Checking to see if a JtextField is NOT equal to saved arrays

Hey guys I'm very new to Java and started in July with an intro to Java class.
I am currently working on a project which is a translator with arrays. The main applet shows 10 words in english that when typed into a JTextField outputs the spanish translation of that work. And vice versa. The program also shows a picture associated with that word.
The program is all done in that case, the only portion I am missing currently is that if a user inputs ANY other word than the 20 given words (10 spanish and 10 english) the JTextArea where translations are displayed is supposed to show "That word is not in the dictionary".
I'm having issues creating an ELSE statement that shows this error message. Here is the complete code. I'm not sure what to do to make it so eg
if (textFieldWord.!equals(englishWords[english])){
translate.setText("That word is not in the Dictionary");}
Here is the complete code - - - -
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DictionaryArrays extends JApplet implements ActionListener{
String[] spanishWords = {"biblioteca","reloj",
"alarma", "volcan", "ventana",
"autobus", "raton", "lago", "vaca", "encendedor"};
String[] englishWords = {"library", "clock", "alarm",
"volcano", "window", "bus", "rat",
"lake","cow","lighter"};
String textFieldWord;
Image[] photos;
ImageIcon icon;
ImageIcon icontwo;
JButton getTranslation;
JTextField entry;
JLabel imageviewer;
TextArea translate;
static int defaultX = 10;
static int defaultY = 10;
static int defaultW = 780;
static int defaultH = 50;
public void init() {
photos = new Image[10];
photos[0] = getImage(getCodeBase(), "library.jpg");
photos[1] = getImage(getCodeBase(), "clock.jpg");
photos[2] = getImage(getCodeBase(), "alarm.jpg");
photos[3] = getImage(getCodeBase(), "volcano.jpg");
photos[4] = getImage(getCodeBase(), "window.jpg");
photos[5] = getImage(getCodeBase(), "bus.jpg");
photos[6] = getImage(getCodeBase(), "rat.jpg");
photos[7] = getImage(getCodeBase(), "lake.jpg");
photos[8] = getImage(getCodeBase(), "cow.jpg");
photos[9] = getImage(getCodeBase(), "lighter.jpg");
final JPanel outer = new JPanel(new BorderLayout());
JPanel inner = new JPanel(new BorderLayout());
JPanel viewer = new JPanel(new BorderLayout());
JPanel visualviewer = new JPanel(new BorderLayout());
// here is the main component we want to see
// when the outer panel is added to the null layout
//JButton toSpanish = new JButton("English to Spanish");
//JButton toEnglish = new JButton("Spanish to English");
final JLabel list = new JLabel("<HTML><FONT COLOR=RED>English</FONT> - library, clock, alarm, volcano, window, bus, rat, lake, cow, lighter"
+"<BR><FONT COLOR=RED>Spanish</FONT> - biblioteca, reloj, alarma, volcan, ventana, autobus, raton, lago, vaca, encendedor<BR>");
translate = new TextArea("Your translation will show here");
imageviewer = new JLabel(icon);
viewer.add("West",translate);
visualviewer.add("East",imageviewer);
inner.add("Center",list);
//inner.add("West",toSpanish);
//inner.add("East", toEnglish);
outer.add("Center", inner);
JPanel c = (JPanel)getContentPane();
final JPanel nullLayoutPanel = new JPanel();
nullLayoutPanel.setLayout(null);
c.add("Center", nullLayoutPanel);
// set the bounds of the panels manually
nullLayoutPanel.add(outer);
nullLayoutPanel.add(viewer);
nullLayoutPanel.add(visualviewer);
outer.setBounds(defaultX, defaultY, defaultW, defaultH);
viewer.setBounds(20, 75, 300, 300);
visualviewer.setBounds(485, 75, 300, 300);
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
entry = new JTextField("Enter English or Spanish word to translate here");
entry.addActionListener(this);
entry.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
entry.setText("");
}});
getTranslation = new JButton("Translate");
getTranslation.addActionListener(this);
controlPanel.add(entry);
controlPanel.add(getTranslation);
c.add("South", controlPanel);
viewer.setBackground(Color.blue);
controlPanel.setBackground(Color.red);
inner.setBackground(Color.yellow);
visualviewer.setBackground(Color.black);
outer.setBackground(Color.black);
}
public void paint(Graphics g) {
super.paint(g);
}
public void actionPerformed (ActionEvent ae){
if(ae.getSource()==getTranslation){
textFieldWord=(entry.getText().toLowerCase());
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translate.setText(spanishWords[english]);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translate.setText(englishWords[spanish]);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
}
}
Any help would be appreciated guys. If the top paragraph was TLDR. Im trying to make it so typing in ANY other word in the JTextField (entry) other than the 10 english and 10 spanish words will output an error msg of "That word is not in the Dictionary" in the TextArea (translate)
This is (obviously) wrong...
if (textFieldWord.!equals(englishWords[english])){
and should be...
if (!textFieldWord.equals(englishWords[english])){
Try and think of it this way, String#equals returns a boolean, you want to invert the result of this method call, it would be the same as using something like...
boolean doesEqual = textFieldWord.equals(englishWords[english]);
if (!doesEqual) {...
You need to evaluate the result of the method call, but in oder to make that call, the syntax must be [object].[method], therefore, in order to invert the value, you must complete the method call first, then apply the modifier to it ... ! ([object].[method])
Updated...
Now having said all that, let's look at the problem from a different perspective...
You need to find a matching word, in order to do that, you must, at worse case, search the entire array. Until you've search the entire array, you don't know if a match exists.
This means we could use a separate if-else statement to manage the updating of the output, for example...
String translatedWord = null;
int foundIndex = -1;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = englishWords[english];
foundIndex = english;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icon= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icon);
} else {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[english];
foundIndex = spanish;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icontwo);
} else {
translate.setText("That word is not in the Dictionary");
}
Basically, all this does is sets the translatedWord to a non null value when it finds a match in either of the arrays. In this, you want to display the results, else you want to display the error message...
Equally, you could merge your current approach with the above, so when you find a work, you update the output, but also check the state of the translatedWord variable, displaying the error message if it is null...
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = spanishWords[english];
translate.setText(translatedWord);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[spanish];
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
Updated
Okay, you have a logic problem. You're never quite sure which direction you are translating to.
The following basically changes the follow by not translating the work from Spanish IF it was translated to English
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == getTranslation) {
textFieldWord = (entry.getText().toLowerCase());
translate.setText(null);
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++) {
if (textFieldWord.equals(englishWords[english])) {
translatedWord = spanishWords[english];
translate.append(translatedWord + "\n");
icon = new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
for (int spanish = 0; spanish < englishWords.length; spanish++) {
if (textFieldWord.equals(spanishWords[spanish])) {
translatedWord = englishWords[spanish];
translate.append(translatedWord + "\n");
icontwo = new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
if (translatedWord == null) {
translate.append("A Spanish-English match is not in the Dictionary\n");
}
}
}
Now, I would suggest that you replace TextArea with a JTextArea, but you will need to wrap it in a JScrollPane
translate = new JTextArea("Your translation will show here");
viewer.add("West", new JScrollPane(translate));
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Basically, this was really painful to try and use for this very reason...

Program freezing(not responding) after button click no a Java app

Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.

Multiple bugs, no reason

This program is designed in the end to make a slot machine like thing that will be integrated into a friend's game, still in pre alpha stages and will be for a long time or maybe forever. (he's only using it for a class project ATM)
package SlotMachine;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.Color;
public class SlotGui{
static Random one = new Random();
static Random two = new Random();
static Random three = new Random();
static Random four = new Random();
static Random five = new Random();
static Random six = new Random();
static Random seven = new Random();
static Random eight = new Random();
static Random nine = new Random();
static int st = one.nextInt(10);
static int nd = two.nextInt(10);
static int trd = three.nextInt(10);
static int frth = four.nextInt(10);
static int fth = five.nextInt(10);
static int sxth = six.nextInt(10);
static int svth = seven.nextInt(10);
static int eth = eight.nextInt(10);
static int nth = nine.nextInt(10);
static int coins = 15;
static JTextField money = new JTextField(Integer.toString(coins));
static JLabel blueLabel = new JLabel();
static JLabel slotOne = new JLabel();
static JLabel slotTwo = new JLabel();
static JLabel slotThree = new JLabel();
static JLabel slotFour = new JLabel();
static JLabel slotFive = new JLabel();
static JLabel slotSix = new JLabel();
static JLabel slotSeven = new JLabel();
static JLabel slotEight = new JLabel();
static JLabel slotNine = new JLabel();
static Icon lever = new ImageIcon("lever.jpg");
static Icon a = new ImageIcon("0.jpg");
static Icon b = new ImageIcon("1.jpg");
static Icon c = new ImageIcon("2.jpg");
static Icon d = new ImageIcon("3.jpg");
static Icon ee = new ImageIcon("4.jpg");
static Icon f = new ImageIcon("5.jpg");
static Icon g = new ImageIcon("6.jpg");
static Icon h = new ImageIcon("7.jpg");
static Icon i = new ImageIcon("8.jpg");
static Icon j = new ImageIcon("9.jpg");
static JButton startLever = new JButton(lever);
static Color backGround = new Color (0,0,0);
public static void slotVisualSet(JLabel slot,int Xval, int Yval, int h, int w){
slot.setOpaque(true);
slot.setLocation(Xval,Yval);
slot.setSize(h,w);
slot.setVisible(true);
}
public static void slotLogic(JLabel slotLab,int slotNum){
if (slotNum == 0){
slotLab.setIcon(a);
} else if (slotNum == 1){
slotLab.setIcon(b);
} else if (slotNum == 2){
slotLab.setIcon(c);
} else if (slotNum == 3){
slotLab.setIcon(d);
} else if (slotNum == 4){
slotLab.setIcon(ee);
} else if (slotNum == 5){
slotLab.setIcon(f);
} else if (slotNum == 6){
slotLab.setIcon(g);
} else if (slotNum == 7){
slotLab.setIcon(h);
} else if (slotNum == 8){
slotLab.setIcon(i);
} else if (slotNum == 9){
slotLab.setIcon(j);
}
}
public static void makeWindow(){
//creating the window
JFrame windo = new JFrame ();
windo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
windo.setExtendedState(JFrame.MAXIMIZED_BOTH);
windo.setVisible(true);
//creating the components of the window
money.setOpaque(true);
money.setLocation(500,900);
money.setSize(60,20);
blueLabel.setOpaque(true);
blueLabel.setBackground(backGround);
blueLabel.setPreferredSize(new Dimension(1000, 1000));
blueLabel.setVisible(true);
blueLabel.setLayout(null);
//setting the coordinates and sizes of the slots
slotVisualSet(slotOne,100,100,225,225);
slotVisualSet(slotTwo,350,100,225,225);
slotVisualSet(slotThree,600,100,225,225);
slotVisualSet(slotFour,100,350,225,225);
slotVisualSet(slotFive,350,350,225,225);
slotVisualSet(slotSix,600,350,225,225);
slotVisualSet(slotSeven,100,600,225,225);
slotVisualSet(slotEight,350,600,225,225);
slotVisualSet(slotNine,600,600,225,225);
startLever.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int st = one.nextInt(10);
int nd = two.nextInt(10);
int trd = three.nextInt(10);
int frth = four.nextInt(10);
int fth = five.nextInt(10);
int sxth = six.nextInt(10);
int svth = seven.nextInt(10);
int eth = eight.nextInt(10);
int nth = nine.nextInt(10);
coins = coins - 5;
money.setText(Integer.toString(coins));
// making the slots change pictures when the lever is pulled
slotLogic(slotOne,st);
slotLogic(slotTwo,nd);
slotLogic(slotThree,trd);
slotLogic(slotFour,frth);
slotLogic(slotFive,fth);
slotLogic(slotSix,sxth);
slotLogic(slotSeven,svth);
slotLogic(slotEight,eth);
slotLogic(slotNine,nth);
if ((st == nd) && (nd == trd)){
coins = coins + 30;
}else if((frth == fth) && (fth == sxth)){
coins = coins + 30;
}else if ((svth == eth) && (eth == nth)){
coins = coins + 30;
} else if ((st == fth) && (fth == nth)){
coins = coins + 100;
}else if ((svth == fth) && (fth == trd)){
coins = coins + 100;
}
}
});
startLever.setSize(183,275);
startLever.setLocation(1000,300);
windo.add(startLever);
windo.add(money);
windo.add(blueLabel);
windo.add(slotOne);
windo.add(slotTwo);
windo.add(slotThree);
windo.add(slotFour);
windo.add(slotFive);
windo.add(slotSix);
windo.add(slotSeven);
windo.add(slotEight);
windo.add(slotNine);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
makeWindow();
}
} );
}
}
There are three bugs here, I have been looking for answers forever and have not been able to find any, so help would be much appreciated.
The ninth slot does not go listen to the placement parameters for some reason and just sits on the side.
The slots do not always appear after you click the button that is supposed to change the images (maybe I need to use something other than JLabels for this?)
The background doesn't change colour.
There are so many issues with that code that are problematic, let me enumerate some:
Trying to set location of a component on a non-null layout using container
Trying to use set location at all and not use layout managers. That's what they're there for, to make it easy to create complex GUI's without fussing with exact positioning.
Not using arrays.
Over use of static. None of the fields should be static. Edit: except for the background color which could very well be a constant, a static final variable named BACKGROUND.
Using nine Random objects. One would work just fine and would be a lot less confusing.
.... etc...
posting code for a "friend's" class project.
I think that the best fix-up for this code is to trash it, and instead try to re-write the code from scratch using arrays, using layout managers, avoiding static variables. Start over and you could create a nice GUI and quickly too, and learn quite a bit in the process.
Edit 2
Consider using a GridLayout using JPanel to hold your 3 x 3 grid of JLabels.
Consider using a BorderLayout for your overall GUI, placing the GridLayout JPanel into the BorderLayout.CENTER position.
The play button could go in a JPanel that is placed in the main GUI BorderLayout.EAST position.
The bet window could go in a JPanel that is located in the main GUI in the BorderLayout.SOUTH position.
Again use of arrays will simplify and shrink your code, making it much easier to debug and to enhance.
The same goes for use of layout managers as they will make it easier for you to debug, enhance and modify your GUI.

How can I determine which JCheckBox caused an event when the JCheckBox text is the same

I am working on a program that needs to determine which JCheckBox was selected. I am using three different button groups, two of which have overlapping text. I need to be able to determine which triggered the event so I can add the appropriate charge (COSTPERROOM vs COSTPERCAR) to the total(costOfHome). What I cant figure out is how to differentiate the checkbox source if the text is the same. I was thinking of trying to change the text on one button group to strings like "one" "two" etc, but that introduces a bigger problem with how I have created the checkboxes in the first place. Any ideas would be appreciated, thanks in advance!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JMyNewHome extends JFrame implements ItemListener {
// class private variables
private int costOfHome = 0;
// class arrays
private String[] homeNamesArray = {"Aspen", "Brittany", "Colonial", "Dartmour"};
private int[] homeCostArray = {100000, 120000, 180000, 250000};
// class constants
private final int MAXROOMS = 3;
private final int MAXCARS = 4;
private final int COSTPERROOM = 10500;
private final int COSTPERCAR = 7775;
JLabel costLabel = new JLabel();
// constructor
public JMyNewHome ()
{
super("My New Home");
setSize(450,150);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font labelFont = new Font("Time New Roman", Font.BOLD, 24);
setJLabelString(costLabel, costOfHome);
costLabel.setFont(labelFont);
add(costLabel);
JCheckBox[] homesCheckBoxes = new JCheckBox[homeNamesArray.length];
ButtonGroup homeSelection = new ButtonGroup();
for (int i = 0; i < homeNamesArray.length; i++)
{
homesCheckBoxes[i] = new JCheckBox(homeNamesArray[i], false);
homeSelection.add(homesCheckBoxes[i]);
homesCheckBoxes[i].addItemListener(this);
add(homesCheckBoxes[i]);
}
JLabel roomLabel = new JLabel("Number of Rooms in Home");
add(roomLabel);
ButtonGroup roomSelection = new ButtonGroup();
JCheckBox[] roomCheckBoxes = new JCheckBox[MAXROOMS];
for (int i = 0; i < MAXROOMS; i++)
{
String intToString = Integer.toString(i + 2);
roomCheckBoxes[i] = new JCheckBox(intToString);
roomSelection.add(roomCheckBoxes[i]);
roomCheckBoxes[i].addItemListener(this);
add(roomCheckBoxes[i]);
}
JLabel carLabel = new JLabel("Size of Garage (number of cars)");
add(carLabel);
ButtonGroup carSelection = new ButtonGroup();
JCheckBox[] carCheckBoxes = new JCheckBox[MAXCARS];
for (int i = 0; i < MAXCARS; i++)
{
String intToString = Integer.toString(i);
carCheckBoxes[i] = new JCheckBox(intToString);
carSelection.add(carCheckBoxes[i]);
carCheckBoxes[i].addItemListener(this);
add(carCheckBoxes[i]);
}
setVisible(true);
}
private void setJLabelString(JLabel label, int cost)
{
String costOfHomeString = Integer.toString(cost);
label.setText("Cost of Configured Home: $ " + costOfHomeString + ".00");
invalidate();
validate();
repaint();
}
public void itemStateChanged(ItemEvent e) {
JCheckBox source = (JCheckBox) e.getItem();
String sourceText = source.getText();
//JLabel testLabel = new JLabel(sourceText);
//add(testLabel);
//invalidate();
//validate();
//repaint();
for (int i = 0; i < homeNamesArray.length; i++)
{
if (sourceText == homeNamesArray[i])
{
setJLabelString(costLabel, costOfHome + homeCostArray[i]);
}
}
}
}
I would
Use JRadioButtons for this rather than JCheckBoxes since I think it is GUI standard to have a set of JRadioButtons that only allow one selection rather than a set of JCheckBoxes.
Although you may have "overlapping text" you can set the button's actionCommand to anything you want to. So one set of buttons could have actionCommands that are "room count 2", "room count 3", ...
But even better, the ButtonGroup can tell you which toggle button (either check box or radio button) has been selected since if you call getSelection() on it, it will get you the ButtonModel of the selected button (or null if none have been selected), and then you can get the actionCommand from the model via its getActionCommand() method. Just first check that the model selected isn't null.
Learn to use the layout managers as they can make your job much easier.
For instance, if you had two ButtonGroups:
ButtonGroup fooBtnGroup = new ButtonGroup();
ButtonGroup barBtnGroup = new ButtonGroup();
If you add a bunch of JRadioButtons to these ButtonGroups, you can then check which buttons were selected for which group like so (the following code is in a JButton's ActionListener):
ButtonModel fooModel = fooBtnGroup.getSelection();
String fooSelection = fooModel == null ? "No foo selected" : fooModel.getActionCommand();
ButtonModel barModel = barBtnGroup.getSelection();
String barSelection = barModel == null ? "No bar selected" : barModel.getActionCommand();
System.out.println("Foo selected: " + fooSelection);
System.out.println("Bar selected: " + barSelection);
Assuming of course that you've set the actionCommand for your buttons.
Checkboxes have item listeners like any other swing component. I would decouple them, and simply add listeners to each
{
checkBox.addActionListener(actionListener);
}
http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxItemListener.htm

Categories

Resources