Trouble displaying dice images in a JApplet - java

Hello I'm trying to add dice images on the side of my craps program. However I keep running into the issue of all my JLabels, Jtextfeilds and JButtons disappearing.
Dice images:
Craps.java:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Craps extends JApplet implements ActionListener{
private static final long serialVersionUID = 1L;
//constant variables for the status of the game
final int WON = 0,LOST =1, CONTINUE = 2;
//other variables used in the program
boolean firstRoll = true;
int sumOfDice = 0;
int myPoint = 0;
int gameStatus = CONTINUE;
int numberHouseWins = 0;
int numberPlayerWins = 0;
String divider = "*******";
int die1,die2,workSum;
//die faces
Image dieFace1,dieFace2,dieFace3,dieFace4,dieFace5,dieFace6;
//graphical user interface components
JLabel dieLabel1, dieLabel2, sumLabel, rollLabel, pointLabel;
JLabel lblHouseWins, lblPlayerWins;
JLabel leftDivider, rightDivider;
JTextField firstDie, secondDie, sum, point;
JTextField txtHouseWins, txtPlayerWins;
JButton roll;
public void paint(Graphics g){
if(die1 == 1){
repaint();
g.drawImage(dieFace1, 0, 0, this);
}
else if( die1 == 2){
repaint();
g.drawImage(dieFace2, 0, 0, this);
}
else if( die1 == 3){
repaint();
g.drawImage(dieFace3, 0, 0, this);
}
else if( die1 == 4){
repaint();
g.drawImage(dieFace4, 0, 0, this);
}
else if( die1 == 5){
repaint();
g.drawImage(dieFace5, 0, 0, this);
}
else if( die1 == 6){
repaint();
g.drawImage(dieFace6, 0, 0, this);
}
if ( die2==1){
repaint();
g.drawImage(dieFace1, 0, 30, this);
}else if( die2 == 2){
repaint();
g.drawImage(dieFace2, 0, 30, this);
}
else if( die2 == 3){
repaint();
g.drawImage(dieFace3, 0, 30, this);
}
else if( die2 == 4){
repaint();
g.drawImage(dieFace4, 0, 30, this);
}
else if( die2 == 5){
repaint();
g.drawImage(dieFace5, 0, 30, this);
}
else if( die2 == 6){
repaint();
g.drawImage(dieFace6, 0, 30, this);
}
}
public void init()
{
//setup graphical user interface components
JPanel display = new JPanel();
display.setLayout(new GridLayout(8, 2, 10, 10));
//creating JLabel Die1 to the display
dieLabel1 = new JLabel("Die 1:",SwingConstants.RIGHT);
display.add(dieLabel1);
firstDie = new JTextField(3);
firstDie.setEditable(false);
display.add(firstDie);
//creating JLabel Die2 to the Display
dieLabel2 = new JLabel("Die 2:",SwingConstants.RIGHT);
display.add(dieLabel2);
secondDie = new JTextField(3);
secondDie.setEditable(false);
display.add(secondDie);
//creating JLabel sum die to the display
sumLabel = new JLabel("Their sum is:",SwingConstants.RIGHT);
display.add(sumLabel);
sum = new JTextField(4);
sum.setEditable(false);
display.add(sum);
//creating JLabel rollLabel to the display
rollLabel= new JLabel("Roll Again",SwingConstants.RIGHT);
display.add(rollLabel);
roll = new JButton("Roll Dice");
roll.addActionListener(this);
display.add(roll);
//creating JLabel pointLabel to the display
pointLabel = new JLabel("Point is:",SwingConstants.RIGHT);
display.add(pointLabel);
point = new JTextField(3);
point.setEditable(false);
display.add(point);
//creating JLabel leftDivider and rightDivider to the display
leftDivider = new JLabel(divider,SwingConstants.RIGHT);
display.add(leftDivider);
rightDivider = new JLabel(divider,SwingConstants.LEFT);
display.add(rightDivider);
//creating JLabel lblPlayerWins and JTextField txtPlayerWins to the display
lblPlayerWins = new JLabel("Player wins:",SwingConstants.RIGHT);
display.add(lblPlayerWins);
txtPlayerWins = new JTextField(4);
txtPlayerWins.setEnabled(false);
display.add(txtPlayerWins);
//creating JLabel lblHouseWins and JTextField txtHouseWins to the display
lblHouseWins = new JLabel("House wins:",SwingConstants.RIGHT);
display.add(lblHouseWins);
txtHouseWins = new JTextField(4);
txtHouseWins.setEnabled(false);
display.add(txtHouseWins);
setContentPane(display);
dieFace1=getImage(getDocumentBase(),"die1.jpg");
dieFace2=getImage(getDocumentBase(), "die2.jpg");
dieFace3=getImage(getDocumentBase(),"die3.jpg");
dieFace4=getImage(getDocumentBase(), "die4.jpg");
dieFace5=getImage(getDocumentBase(),"die5.jpg");
dieFace6=getImage(getDocumentBase(), "die6.jpg");
}
public void actionPerformed(ActionEvent e){
play();
}
public void play(){
if(firstRoll){
sumOfDice = rollDice();
switch (sumOfDice) {
//player wins on first roll
case 7: case 11:
gameStatus = WON;
point.setText("");
break;
//house wins player loses on first roll
case 2:case 3: case 12:
gameStatus = LOST;
point.setText("");
break;
default:
gameStatus = CONTINUE;
myPoint = sumOfDice;
point.setText(Integer.toString(myPoint));
firstRoll = false;
break;
}
}
else{
sumOfDice = rollDice();
if(sumOfDice==myPoint)
gameStatus = WON;
else
if(sumOfDice == 7)
gameStatus = LOST;
}
if(gameStatus == CONTINUE)
showStatus("Roll again");
else{
if(gameStatus == WON){
showStatus("Player wins."+"Click Roll Dice to play again");
numberPlayerWins++;
txtPlayerWins.setText(Integer.toString(numberPlayerWins));
}
else{
showStatus("House wins."+"Click Roll Dice to play again");
numberHouseWins++;
txtHouseWins.setText(Integer.toString(numberHouseWins));
}
firstRoll = true;
}
}
public int rollDice(){
die1 = 1+ (int)(Math.random()*6);
die2 = 1+ (int)(Math.random()*6);
workSum = die1 +die2;
firstDie.setText(Integer.toString(die1));
secondDie.setText(Integer.toString(die2));
sum.setText(Integer.toString(workSum));
return workSum;
}
}

I've edited your code and included comments to explain what I did and the reasoning for it. It was much easier to explain the code in the code, rather than write up a huge explanation and reference different pieces of the code.
I removed your paint method, as it was not needed and endlessly looped between paint and repaint calls.
Note: Sorry about the spacing between types and variables, my IDE is set up that way.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Craps extends JApplet implements ActionListener {
private static final long serialVersionUID = 1L;
// constant variables for the status of the game
final int WON = 0, LOST = 1, CONTINUE = 2;
// other variables used in the program
boolean firstRoll = true;
int sumOfDice = 0;
int myPoint = 0;
int gameStatus = CONTINUE;
int numberHouseWins = 0;
int numberPlayerWins = 0;
String divider = "*******";
int die1, die2, workSum;
// graphical user interface components
JLabel dieLabel1, dieLabel2, sumLabel, rollLabel, pointLabel;
JLabel lblHouseWins, lblPlayerWins;
JLabel leftDivider, rightDivider;
JTextField firstDie, secondDie, sum, point;
JTextField txtHouseWins, txtPlayerWins;
JButton roll;
// added these two JLabels to display dice ImageIcons
JLabel dieImg1, dieImg2;
// die faces, changed to an array of ImageIcons
ImageIcon dieFaces[];
// moved these into their own function, init is pretty stuffed
public void createImageIcons() {
// create an array of ImageIcons, easier to set JLabels image using
// index rather than 6 if-else-if statements
dieFaces = new ImageIcon[6];
dieFaces[0] = new ImageIcon(getImage(getDocumentBase(), "die1.jpg"));
dieFaces[1] = new ImageIcon(getImage(getDocumentBase(), "die2.jpg"));
dieFaces[2] = new ImageIcon(getImage(getDocumentBase(), "die3.jpg"));
dieFaces[3] = new ImageIcon(getImage(getDocumentBase(), "die4.jpg"));
dieFaces[4] = new ImageIcon(getImage(getDocumentBase(), "die5.jpg"));
dieFaces[5] = new ImageIcon(getImage(getDocumentBase(), "die6.jpg"));
}
public JPanel createTxtImgContainer(JTextField txt, JLabel img) {
JPanel container = new JPanel();
container.setLayout(new GridLayout(1, 2, 10, 10));
txt.setEditable(false);
container.add(txt);
container.add(img);
return container;
}
#Override
public void init() {
// don't know if this is necessary, but it can't hurt
super.init();
// let's load the images first, no need to run a bunch of code and then
// error out on image loading also we can use the ImageIcons after this
createImageIcons();
// setup graphical user interface components
JPanel display = new JPanel();
display.setLayout(new GridLayout(8, 2, 10, 20));
// creating JLabel Die1 to the display
dieLabel1 = new JLabel("Die 1:", SwingConstants.RIGHT);
display.add(dieLabel1);
firstDie = new JTextField(3);
// created dieImg1 here also set the initial ImageIcon to "die6.jpg"
dieImg1 = new JLabel(dieFaces[5]);
// create a JPanel to house the JTextField and JLabel, and it to display
display.add(createTxtImgContainer(firstDie, dieImg1));
// creating JLabel Die2 to the Display
dieLabel2 = new JLabel("Die 2:", SwingConstants.RIGHT);
display.add(dieLabel2);
secondDie = new JTextField(3);
// created dieImg2 here also set the initial image to "die6.jpg"
dieImg2 = new JLabel(dieFaces[5]);
// create a JPanel to house the JTextField and JLabel, and it to display
display.add(createTxtImgContainer(secondDie, dieImg2));
// creating JLabel sum die to the display
sumLabel = new JLabel("Their sum is:", SwingConstants.RIGHT);
display.add(sumLabel);
sum = new JTextField(4);
sum.setEditable(false);
display.add(sum);
// creating JLabel rollLabel to the display
rollLabel = new JLabel("Roll Again", SwingConstants.RIGHT);
display.add(rollLabel);
roll = new JButton("Roll Dice");
roll.addActionListener(this);
display.add(roll);
// creating JLabel pointLabel to the display
pointLabel = new JLabel("Point is:", SwingConstants.RIGHT);
display.add(pointLabel);
point = new JTextField(3);
point.setEditable(false);
display.add(point);
// creating JLabel leftDivider and rightDivider to the display
leftDivider = new JLabel(divider, SwingConstants.RIGHT);
display.add(leftDivider);
rightDivider = new JLabel(divider, SwingConstants.LEFT);
display.add(rightDivider);
// creating JLabel lblPlayerWins and JTextField txtPlayerWins to the
// display
lblPlayerWins = new JLabel("Player wins:", SwingConstants.RIGHT);
display.add(lblPlayerWins);
txtPlayerWins = new JTextField(4);
txtPlayerWins.setEnabled(false);
display.add(txtPlayerWins);
// creating JLabel lblHouseWins and JTextField txtHouseWins to the
// display
lblHouseWins = new JLabel("House wins:", SwingConstants.RIGHT);
display.add(lblHouseWins);
txtHouseWins = new JTextField(4);
txtHouseWins.setEnabled(false);
display.add(txtHouseWins);
setContentPane(display);
}
#Override
public void actionPerformed(ActionEvent e) {
play();
}
public void play() {
if (firstRoll) {
sumOfDice = rollDice();
switch(sumOfDice) {
// player wins on first roll
case 7 :
case 11 :
gameStatus = WON;
point.setText("");
break;
// house wins player loses on first roll
case 2 :
case 3 :
case 12 :
gameStatus = LOST;
point.setText("");
break;
default:
gameStatus = CONTINUE;
myPoint = sumOfDice;
point.setText(Integer.toString(myPoint));
firstRoll = false;
break;
}
}
else {
sumOfDice = rollDice();
if (sumOfDice == myPoint) {
gameStatus = WON;
} else if (sumOfDice == 7) {
gameStatus = LOST;
}
}
if (gameStatus == CONTINUE) {
showStatus("Roll again");
} else {
if (gameStatus == WON) {
showStatus("Player wins." + "Click Roll Dice to play again");
numberPlayerWins++;
txtPlayerWins.setText(Integer.toString(numberPlayerWins));
} else {
showStatus("House wins." + "Click Roll Dice to play again");
numberHouseWins++;
txtHouseWins.setText(Integer.toString(numberHouseWins));
}
firstRoll = true;
}
}
public int rollDice() {
die1 = 1 + (int) (Math.random() * 6);
die2 = 1 + (int) (Math.random() * 6);
workSum = die1 + die2;
firstDie.setText(Integer.toString(die1));
secondDie.setText(Integer.toString(die2));
sum.setText(Integer.toString(workSum));
// set dieImgs to die values - 1, because the array starts at 0 not 1
dieImg1.setIcon(dieFaces[die1 - 1]);
dieImg2.setIcon(dieFaces[die2 - 1]);
return workSum;
}
}
Here's a screenshot of the applet running:

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.

How can I get all the combinations of six dice that equal 7?

This is a homework assignment where I'm supposed to roll 6 dice, then pick out ANY combination of dice that make 7 and discard them all.
EX. 1,1,1,1,1,2. My score would be 0 because I have to discard all six dice.
At first I believed it was any combination of 2 dice but have now been told otherwise. My code right now reflects the 2 dice and I have no idea how to wrap my head around doing all six without just using brute force with it and writing in every single possible combination and checking for that.
private void calculateScore(){
//checks for 7's, calculates score if none, updates values
discardDieMessage = "Discard Dice. Combinations of die equals 7";
boolean noSevens = true;
//diceRoll is an array with 6 values
for(int i = 0; i<diceRoll.length;i++){
int temp = diceRoll[i];
for(int j = 0; j<diceRoll.length;j++){
if(temp + diceRoll[j] == 7){noSevens = false;}
}
}
if(noSevens){
playerScore[playerNumber] = 0;
for (int i = 0; i < diceRoll.length;i++) {
playerScore[playerNumber] += diceRoll[i];
}
playerScoreString = new String ("Your score is: " +
+ playerScore[playerNumber] +
"\nYou rolled: " + currentPlayerRolls + " time(s)");
update();
outputTextArea.setText(playerScoreString);
calculateButton.setDisable(true);
messageLabel.setText("");
}
else {
messageLabel.setText(discardDieMessage);
messageLabel.setTextFill(Paint.valueOf("red"));
}
}
UPDATE_1: This is the complete code I have so far. It's a 7's Game where a player rolls 6 dice, they must discard dice that equal 7 EX.{3,2,1,1} while the other two die are {6,6} so the remaining dice no longer are equal to 7.
//all-gui imports
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
//GUI specific controls
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
import javafx.scene.paint.Color;
//GUI specific containers
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
//EventHandler Interface
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import java.util.Random;
import javafx.scene.paint.*;
import java.util.Arrays;
import java.util.stream.*;
import java.io.*;
/***************************************************************************/
public class SevensGameGUI extends Application {
//declare the scene and main stage
private Stage primaryStage;
private Scene scene;
//declare the handler
private SevensGameHandler handler;
//declare panes going to be used
private BorderPane mainPane;
private GridPane topPane;
private GridPane centerPane;
private GridPane outputPane;
private HBox bottomPane;
//declare up labels, boxes, buttons, and textAreas
private Button rollButton;
private Button calculateButton;
private Button endButton;
private Button[] discardButton;
private Label playerNumberLabel;
private Label totalPlayersLabel;
private Label rollNumberLabel;
private Label maxRollLabel;
private TextField[] diceTextField;//Dice TextFields
private TextField playerNumberTextField; //What player is currently playing
private TextField totalPlayersTextField;
private TextField rollNumberTextField; //What roll the player is on
private TextField maxRollTextField; //The total rolls a player has availiable
private Label messageLabel; //Display error
private TextArea outputTextArea;
//setting up program-specfic variables
private int MAX_THROWS = 3;
private int[] playerScore;
private int[] diceRoll;
private int[] discardDie;
private int DICE_COUNT;
private int playerNumber;
private int firstPlayerRolls;
private int currentPlayerRolls;
private int winningPlayer;
Random generator = new Random();
private String cannotRollMessage = "";
private String playerScoreString = "";
private String discardDieMessage = "";
/***************************************************************************/
public void start(Stage primaryStage) {
startUP();
sculptGUI();
prepareGame();
}
/***************************************************************************/
private class SevensGameHandler implements EventHandler<ActionEvent>{
public void handle(ActionEvent ae){
if(ae.getSource() == rollButton){
rollDice();
}else if(ae.getSource() == calculateButton){
calculateScore();
}else if(ae.getSource() == endButton){
nextPlayer();
}
for (int i = 0; i < discardButton.length; i++){
if(ae.getSource() == discardButton[i]){
diceRoll[i] = 0;
update();
discardButton[i].setDisable(true);
}
}
}
}//end of SevensGameHandler
/***************************************************************************/
private void rollDice(){
calculateButton.setDisable(false);
//rolls dice, shows updated values
for (int i = 0; i < diceRoll.length; i++) {
//this rolls the dice 6 times and checks if the button is disabled
if(!discardButton[i].isDisable()){diceRoll[i] = (generator.nextInt(6)+ 1);}
}
//increments how many times the first player rolls
if (playerNumber == 0) {
firstPlayerRolls++;
}
currentPlayerRolls++;
//checking updated values and sends error message if so
if (currentPlayerRolls == MAX_THROWS) {
cannotRollMessage = ("Error: Player " +
(playerNumber + 1) + " cannot roll anymore!");
messageLabel.setText(cannotRollMessage);
messageLabel.setTextFill(Paint.valueOf("red"));
rollButton.setDisable(true);
}
update();
}
/***************************************************************************/
private void calculateScore(){
//checks for 7's, calculates score if none, updates values
discardDieMessage = "Discard Dice. Combinations of die equals 7";
boolean noSevens = true;
//diceRoll is an array with 6 values
for(int i = 0; i<diceRoll.length;i++){
int temp = diceRoll[i];
for(int j = 0; j<diceRoll.length;j++){
if(temp + diceRoll[j] == 7){noSevens = false;}
}
}
if(noSevens){
playerScore[playerNumber] = 0;
for (int i = 0; i < diceRoll.length;i++) {
playerScore[playerNumber] += diceRoll[i];
}
playerScoreString = new String ("Your score is: " +
+ playerScore[playerNumber] +
"\nYou rolled: " + currentPlayerRolls + " time(s)");
update();
outputTextArea.setText(playerScoreString);
calculateButton.setDisable(true);
messageLabel.setText("");
}
else {
messageLabel.setText(discardDieMessage);
messageLabel.setTextFill(Paint.valueOf("red"));
}
}
/***************************************************************************/
private void nextPlayer(){
//increments player, resets rolls and such, updates values
if (playerNumber == 0) {
MAX_THROWS = firstPlayerRolls;
}
playerNumber++;
clearBoard();
update();
calculateButton.setDisable(false);
rollButton.setDisable(false);
for (int i = 0; i < DICE_COUNT; i++){
discardButton[i].setDisable(false);
}
outputTextArea.clear();
for(int i = 0;i<playerScore.length;i++){
if(playerScore[i] > playerScore[winningPlayer]){
winningPlayer = i;
}
}
outputTextArea.appendText("\n\tPlayer " + Integer.toString(winningPlayer+1)+
" is Winning with " + Integer.toString(playerScore[winningPlayer])+" Points");
if ( playerNumber == playerScore.length){
endGame();
}
}//end of nextPlayer()
/***************************************************************************/
private void endGame(){
//sets up a seperate pane to display the winning player along with player scores
TextArea scoreArea = new TextArea();
Button closeButton = new Button("Close");
GridPane endPane = new GridPane();
scoreArea.setPrefSize(300,350);
endPane.setHgap(15);
endPane.setVgap(5);
endPane.setAlignment(Pos.CENTER);
endPane.add(scoreArea,0,0);
endPane.add(closeButton,0,1);
endPane.setHalignment(closeButton ,HPos.CENTER);
endPane.setHalignment(scoreArea ,HPos.CENTER);
Scene endScene = new Scene(endPane,500,500);
primaryStage.setScene(endScene);
primaryStage.show();
closeButton.setOnAction(e -> {
System.exit(0);
});
//output scores and player info
scoreArea.appendText("Player \t Score\n\n");
for(int i = 0;i<playerScore.length;i++){
scoreArea.appendText("Player " + Integer.toString(i+1) +"\t " +
Integer.toString(playerScore[i]) + "\n");
}
scoreArea.appendText("\n\tCongratulations Player " +
Integer.toString(winningPlayer+1) + "\n\tYOU WIN!");
}
/***************************************************************************/
private void prepareGame(){
//Prepares the game for the player to use by initializing variables
//and handlers
playerScore = new int[] {0,0,0,0,0};
diceRoll = new int[] {0,0,0,0,0,0};
discardDie = new int[] {0,0,0,0,0,0};
DICE_COUNT = 6;
playerNumber = 0;
firstPlayerRolls = 0;
currentPlayerRolls = 0;
winningPlayer =0;
update();
handler = new SevensGameHandler();
rollButton.setOnAction(handler);
calculateButton.setOnAction(handler);
endButton.setOnAction(handler);
for(int i = 0;i < discardButton.length; i++) {
discardButton[i].setOnAction(handler);
}
}
/***************************************************************************/
private void clearBoard(){
//Method used to reset and update the GUI
for (int i = 0; i < diceRoll.length; i++) {
diceRoll[i] = 0;
discardDie[i] = 0;
}
currentPlayerRolls = 0;
rollButton.setDisable(false);
messageLabel.setText("");
outputTextArea.setText("");
playerNumberTextField.setText(Integer.toString(playerNumber + 1));
totalPlayersTextField.setText(Integer.toString(playerScore.length));
rollNumberTextField.setText(Integer.toString(currentPlayerRolls));
maxRollTextField.setText(Integer.toString(MAX_THROWS));
}
/***************************************************************************/
private void update() {
//Method used to update the GUI
for (int i = 0; i < diceTextField.length; i++) {
diceTextField[i].setText(Integer.toString(diceRoll[i]));
}
outputTextArea.setText("");
calculateButton.setDisable(false);
playerNumberTextField.setText(Integer.toString(playerNumber + 1));
totalPlayersTextField.setText(Integer.toString(playerScore.length));
rollNumberTextField.setText(Integer.toString(currentPlayerRolls));
maxRollTextField.setText(Integer.toString(MAX_THROWS - currentPlayerRolls));
}
/***************************************************************************/
private void startUP() {
//Buttons
rollButton = new Button ("ROLL");
calculateButton = new Button ("CALCULATE");
endButton= new Button ("END TURN");
discardButton = new Button[6];
for (int i = 0; i < discardButton.length; i++){
discardButton[i] = new Button("Discard " + (i+1));
}
//Labels
playerNumberLabel = new Label("Player #");
totalPlayersLabel = new Label("Total Players");
rollNumberLabel = new Label("Roll #");
maxRollLabel = new Label("Remaining Rolls");
//TextFields
diceTextField = new TextField[6];
for (int k = 0; k < diceTextField.length; k++){
diceTextField[k] = new TextField("");
}
for (int j = 0; j < diceTextField.length; j++) {
diceTextField[j].setDisable(true);
}
playerNumberTextField = new TextField ();
playerNumberTextField.setDisable(true);
totalPlayersTextField = new TextField ();
totalPlayersTextField.setDisable(true);
rollNumberTextField = new TextField ();
rollNumberTextField.setDisable(true);
maxRollTextField = new TextField ();
maxRollTextField.setDisable(true);
messageLabel = new Label ();
outputTextArea = new TextArea();
topPane = new GridPane();
centerPane = new GridPane();
outputPane = new GridPane();
bottomPane = new HBox();
mainPane = new BorderPane();
}
/***************************************************************************/
private void sculptGUI() {
//setting textFields parameters
playerNumberLabel.setPrefWidth(85);
totalPlayersLabel.setPrefWidth(85);
rollNumberLabel.setPrefWidth(85);
maxRollLabel.setPrefWidth(85);
for (int i = 0; i < diceTextField.length; i++) {
diceTextField[i].setPrefWidth(50);
}
playerNumberTextField.setPrefWidth(85);
totalPlayersTextField.setPrefWidth(85);
maxRollTextField.setPrefWidth(85);
rollNumberTextField.setPrefWidth(85);
outputTextArea.setPrefSize(300,350);
//sculpting topPane with GUI elements
topPane.setHgap(15);
topPane.setVgap(5);
topPane.setPrefHeight(100);
topPane.setAlignment(Pos.CENTER);
//placement of top pane
topPane.add(playerNumberLabel, 0, 0);
topPane.add(playerNumberTextField, 0, 1);
topPane.add(totalPlayersLabel, 1, 0);
topPane.add(totalPlayersTextField, 1, 1);
topPane.add(maxRollLabel, 2, 0);
topPane.add(maxRollTextField, 2, 1);
topPane.add(rollNumberLabel, 3, 0);
topPane.add(rollNumberTextField, 3, 1);
//sculpting centerPane with GUI elements
centerPane.setHgap(20);
centerPane.setVgap(5);
centerPane.setAlignment(Pos.CENTER);
centerPane.setHalignment(messageLabel ,HPos.CENTER);
//placements in top line
centerPane.add(diceTextField[0], 0, 0);
centerPane.add(discardButton[0], 0, 1);
centerPane.add(diceTextField[1], 0, 2);
centerPane.add(discardButton[1], 0, 3);
//placement in 2nd line
centerPane.add(diceTextField[2], 1, 0);
centerPane.add(discardButton[2], 1, 1);
centerPane.add(diceTextField[3], 1, 2);
centerPane.add(discardButton[3], 1, 3);
//placement in 3rd line
centerPane.add(diceTextField[4], 2, 0);
centerPane.add(discardButton[4], 2, 1);
centerPane.add(diceTextField[5], 2, 2);
centerPane.add(discardButton[5], 2, 3);
centerPane.add(messageLabel, 0, 4, 3, 1);
//added seperate pane to house the output in one cell,
//and the dice controls in another (for proper centering)
outputPane.add(centerPane,0,0);
outputPane.add(outputTextArea, 0, 1);
outputPane.setHgap(20);
outputPane.setVgap(5);
outputPane.setAlignment(Pos.CENTER);
//sculpting bottomPane with GUI elements
bottomPane.setSpacing(25);
bottomPane.getChildren().addAll(rollButton, calculateButton, endButton);
bottomPane.setAlignment(Pos.CENTER);
bottomPane.setPrefHeight(100);
//setting the main display with seperate panes
mainPane.setTop(topPane);
mainPane.setCenter(outputPane);
mainPane.setBottom(bottomPane);
//setting up the scene and stage
scene = new Scene(mainPane, 500, 500);
primaryStage = new Stage();
primaryStage.setTitle ("Sevens Game (Craps) GUI");
primaryStage.setScene(scene);
primaryStage.show();
}//end of sculptGUI
/***************************************************************************/
}//end of SevensGameGUI

Displaying Java 2D graphics content in a JPanel

I am trying to generate a user interface and while my creation worked fine as a JFrame, it is not displaying my line based graphics in it's JPanel incarnation. If someone could point out what I am doing wrong here it would be very appreciated.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.*;
public class Bowling_GUI_v9 extends JPanel {
public JLabel[] label1;
public JTextField[] text1;
public JComboBox[] combo1;
public JPanel displayPanel = new JPanel();
private int[] horz_coords = new int[] {8,60,580, 53,140,420,100,60,580,245,140,580,280,140,580,315,140,580,350,60,580,400,60,580};
private int[] vert_coords = new int[] {60,140,220,260,300,340,380,420,460,500,540,580};
public Bowling_GUI_v9() {
displayPanel.setLayout(null);
//displayPanel.setSize(800, 600);
displayPanel.setSize(new Dimension(800,600));
createUserInterface();
}
public void drawLines(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
//super.paintComponent(g);
int a = vert_coords.length;
for(int i=0; i<a; i++){
g2d.drawLine(1, vert_coords[i], 400, vert_coords[i]);
}
a = horz_coords.length;
for(int i=0; i<a; i=i+3){
g2d.drawLine(horz_coords[i],horz_coords[i+1],horz_coords[i],horz_coords[i+2]);
}
}
public void paint(Graphics g) {
//super.paint(g);
paint(g);
drawLines(g);
}
private void createUserInterface(){
//Container contentPane = getContentPane();
//contentPane.setLayout(null);
label1 = new JLabel[51];
text1 = new JTextField[17];
combo1 = new JComboBox[5];
int text1counter = 0;
int label1counter = 0;
int combo1counter = 0;
int popCounter = 0;
int counter = 2;
int h_pos =0;
int v_pos =1;
int flag = 0;
int wide = 30;
String[] populate = new String[] {"Team Name", "Ave", "HCP", "Name", "Game 1", "Game 2", "Game 3", "Total", "Won", "Scratch Total", "Lost", "Team HCP", "", "HCP Total Pin", "", "WINS"};
int[] identifier = new int[] {1,2,2,1,1,1,1,1,1,1,2,2,4,3,3,3,2,8,1,2,1,2,2,2,2,9};
label1[label1counter] = new JLabel();
label1[label1counter].setText(populate[popCounter]);
label1[label1counter].setBounds(8,60,80,10);
displayPanel.add(label1[label1counter]);
label1counter++;
popCounter++;
text1[text1counter] = new JTextField();
text1[text1counter].setText("Enter Team Name Here");
text1[text1counter].setBounds(101,60,200,20);
displayPanel.add(text1[text1counter]);
text1counter++;
text1[text1counter] = new JTextField();
text1[text1counter].setText("Lane");
text1[text1counter].setBounds(351,60,40,20);
displayPanel.add(text1[text1counter]);
text1counter++;
for(int a=0; a<10; a++){
for(int b=0; b<7; b++){
counter++;
switch(identifier[counter]){
case 1:
if (b == 2){ wide = 90; }
else if (b == 6 && a == 0){ wide = 55; }
else { wide = 30; }
label1[label1counter] = new JLabel();
label1[label1counter].setText(populate[popCounter]);
label1[label1counter].setBounds(horz_coords[h_pos],vert_coords[v_pos]- 20,wide,20);
displayPanel.add(label1[label1counter]);
h_pos = h_pos + 3;
label1counter++;
popCounter++;
break;
case 2:
label1[label1counter] = new JLabel();
label1[label1counter].setText("0");
label1[label1counter].setBounds(horz_coords[h_pos],vert_coords[v_pos] -20, 30, 20);
displayPanel.add(label1[label1counter]);
h_pos = h_pos + 3;
label1counter++;
break;
case 3:
text1[text1counter] = new JTextField();
text1[text1counter].setText("0");
text1[text1counter].setBounds(horz_coords[h_pos],vert_coords[v_pos] - 20,30,20);
displayPanel.add(text1[text1counter]);
text1counter++;
h_pos = h_pos + 3;
break;
case 4:
combo1[combo1counter] = new JComboBox();
combo1[combo1counter].setBounds(horz_coords[h_pos],vert_coords[v_pos] - 20,30,20);
displayPanel.add(combo1[combo1counter]);
combo1counter++;
h_pos = h_pos + 3;
break;
case 8:
b--;
flag++;
counter = 9;
break;
case 9:
b--;
flag++;
counter = 17;
break;
}
}
v_pos++;
h_pos=0;
if(flag == 4){
flag = 1;
counter ++;
}
}
label1[38].setText("");
label1[45].setText("");
}
}
Don't override paint(). Custom painting is done by overriding paintComponent(...) and then you invoke super.paintComponent(...) as the first statement.
You need to override getPreferredSize() to return the size of your panel so layout managers can do their job.
Don't use a null layout and don't use setSize(). Use an appropriate layout manager and the layout manager will determine the size/location of any component you add to the panel.
You don't show where you actually add the panel to a frame.
Read the section from the Swing tutorial on Custom Painting for more information and working examples. In other words, start with a small example and make sure you understand the entire process before doing complex painting.
The tutorial also has a section on Layout Managers that you should be reading to you use them properly.

Why is my ItemListener program not allowing me to select an option from two different JComboBoxes in Java?

My program will only do one JcomboBox at a time when I am trying to get both numbers to be added together to display the final number.
It allows me to run the program, but it will not display the final price because it does not want to select two things at once.
Here is the code for my program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CottageRental2 extends JFrame implements ItemListener{
// Declare all instance data (primitives and objects used)
private int WIDTH = 676;
private int HEIGHT = 321;
Container con;
private JLabel label1;
private JLabel label2;
private JLabel label3;
JComboBox cbox1;
JComboBox cbox2;
String [ ] roomChoice = {"1 Bedroom: $600","2 Bedroom: $800","3 Bedroom: $1000"};
String [ ] activityChoice = {"Horse Back Riding: $60","Rafting: $40","Row Boat Rental: $50"};
ImageIcon icon1 = new ImageIcon("C:\\Users\\Coding\\Desktop\\cottage.jpeg");
Font f1 = new Font("Ariel", Font.BOLD, 30);
//constructor
public CottageRental2(){
super("Cottage Rental");
con = getContentPane();
con.setLayout(new BorderLayout());
con.setBackground(Color.GRAY);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createGUI(){
label1 = new JLabel("Woodberry Cottage Rental", JLabel.CENTER);
label1.setFont(f1);
label1.setForeground(Color.WHITE);
label2 = new JLabel("Rental Amount Due: $660", JLabel.CENTER);
label2.setFont(f1);
label2.setForeground(Color.WHITE);
label3 = new JLabel(icon1);
cbox1 = new JComboBox();
cbox1.addItem(roomChoice[0]);
cbox1.addItem(roomChoice[1]);
cbox1.addItem(roomChoice[2]);
cbox1.addItemListener(this);
cbox2 = new JComboBox();
cbox2.addItem(activityChoice[0]);
cbox2.addItem(activityChoice[1]);
cbox2.addItem(activityChoice[2]);
cbox2.addItemListener(this);
con.add(label1, BorderLayout.NORTH);
con.add(label2, BorderLayout.SOUTH);
con.add(label3, BorderLayout.CENTER);
con.add(cbox1, BorderLayout.WEST);
con.add(cbox2, BorderLayout.EAST);
}
public void itemStateChanged(ItemEvent event){
Object source = event.getSource();
int price1 = 0;
int price2 = 0;
if(source == cbox1){
int roomIndex = cbox1.getSelectedIndex();
if(roomIndex == 0){
price1 = 600;
}
if(roomIndex == 1){
price1 = 800;
}
if(roomIndex == 2){
price1 = 1000;
}
}
if(source == cbox2){
int activityIndex = cbox2.getSelectedIndex();
if(activityIndex == 0){
price2 = 60;
}
if(activityIndex == 1){
price2 = 40;
}
if(activityIndex == 2){
price2 = 50;
}
}
label2.setText("Rental Amount Due: $" + (price1 + price2));
}
public static void main(String[] args){
CottageRental2 object = new CottageRental2();
object.createGUI();
object.setSize(675, 320);
}
}
Your problem is your if (source == ...) if blocks which prevent the program from getting the selected item from the other JComboBox, the one that isn't being actively selected.
One solution: get rid of the offending if blocks that test for the source of the event in the listener:
public void itemStateChanged(ItemEvent event) {
// Object source = event.getSource();
int price1 = 0;
int price2 = 0;
// if(source == cbox1){
int roomIndex = cbox1.getSelectedIndex();
if (roomIndex == 0) {
price1 = 600;
} else if (roomIndex == 1) {
price1 = 800;
} else if (roomIndex == 2) {
price1 = 1000;
}
// }
// if(source == cbox2){
int activityIndex = cbox2.getSelectedIndex();
if (activityIndex == 0) {
price2 = 60;
} else if (activityIndex == 1) {
price2 = 40;
} else if (activityIndex == 2) {
price2 = 50;
}
// }
label2.setText("Rental Amount Due: $" + (price1 + price2));
}
Also, it would be safer if you use some else if blocks in your item selection statements.

for loop for array only processing one element in java?

I can't figure out why whenever I cycle through my array using the for-loop it only produces one element (the first) to console? I'm pretty sure it's a rookie-mistake I'm looking over, so any tips and suggestions would help.
I'm making a program for fun that compares two strings typed in a text field and if they don't exist in the array it produces a JOPtionPane message on the contrary. It's for a battle-hack I may produce in the future for vBulletin forum, but I'm messing around with algorithms before I move to that step. Thanks, guys!
package battleoptionspart1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import javax.swing.border.*;
public class BattleOptionsPart1 extends JFrame{
JButton newthread, previewpost;
JRadioButton battle1;
JTextField postcount, oppA, oppB;
JLabel battle2, max;
JPanel panel;
String [] array = {"Bill","Tom","Wendy", "Paula"};
public BattleOptionsPart1 () {
panel = new JPanel();
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension dim = tool.getScreenSize();
this.setSize(500, 500);
this.setTitle("Battle Options");
GridLayout grid = new GridLayout(0,1,2,2);
this.setLayout(grid);
newthread = new JButton("Post New Thread");
previewpost = new JButton("Preview Post");
postcount = new JTextField("", 4);
oppA = new JTextField("",10);
oppB = new JTextField("",10);
battle1 = new JRadioButton();
battle2 = new JLabel("Would you like to start a recorded battle?");
max = new JLabel("Enter max post count user must have to vote");
ListenForButton listen = new ListenForButton();
newthread.addActionListener(listen);
previewpost.addActionListener(listen);
JPanel opponents = new JPanel();
Border oppBorder = BorderFactory.createTitledBorder("Battlers");
opponents.setBorder(oppBorder);
opponents.add(oppA);
opponents.add(oppB);
JPanel battle = new JPanel();
Border battleBorder = BorderFactory.createTitledBorder("Start Battle");
battle.setBorder(battleBorder);
battle.add(battle1);
battle.add(battle2);
JPanel buttons = new JPanel();
Border buttonBorder = BorderFactory.createTitledBorder("Create Thread");
buttons.setBorder(buttonBorder);
buttons.add(newthread);
buttons.add(previewpost);
JPanel restriction = new JPanel();
Border resBorder = BorderFactory.createTitledBorder("Restrictions");
restriction.setBorder(buttonBorder);
restriction.add(postcount);
restriction.add(max);
this.add(opponents);
this.add(battle);
this.add(restriction);
this.add(buttons);
this.add(panel);
int xPos = (dim.width / 2) - (this.getWidth() / 2);
int yPos = (dim.height / 2) - (this.getHeight() / 2);
this.setLocation(xPos,yPos); //places form in the middle
this.setVisible(true); // users can see form
this.setResizable(false); //users can't resize the form
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String compareA = oppA.getText();
String compareB = oppB.getText();
if (e.getSource() == newthread)
{
System.out.println(compareA + "\n" + compareB);
for(int j = 0; j < array.length; j++)
{
System.out.println(array[j]);
if(!compareA.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareA + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppA.requestFocus();
break;
}
if (!compareB.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareB + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppB.requestFocus();
break;
}
else
{
JOptionPane.showMessageDialog(null, "New thread created successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
else if (e.getSource() == previewpost)
{
System.exit(0);
}
}
}
public static void main(String[] args) {
BattleOptionsPart1 battle = new BattleOptionsPart1();
}
}
In each of the possible options in your loop, you use break, which leaves the loop immediately. If you remove those statements, you'll process each object in the array.
If you want to check if there's a match, you need to go through every element and do your processing after going through the whole array. Here is an example for an array of type int:
boolean contains = false;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == searchKey)
{
contains = true;
break;
}
}
You're breaking out of the loop. with the break; command after the first array element

Categories

Resources