How to get conditionally assigned value from another class - java

I'm having some issues on using a conditionally assigned value in more than one class. I want to apply the use of a value in one class if and only if a condition is met, then use it in some-other class to add up to a total score. this is my code!
#SuppressWarnings("serial")
public class Beginner extends JPanel {
static JButton quest;
Random rand = new Random();
int n = 10;
static List <Point> points = new ArrayList<Point> ();
int scores;
int fails;
public Beginner() {
int radius = 200;
Point center = new Point (250, 250);
double angle = Math.toRadians(360 / n);
points.add(center);
for (int i = 0; i < n; i++) {
double theta = i * angle;
int dx = (int) (radius * Math.sin(theta));
int dy = (int) (radius * Math.cos(theta));
Point p = new Point (center.x + dx , center.y + dy);
points.add(p);
}
draw (points);
}
public void draw (List<Point> points) {
JPanel panels = new JPanel();
SpringLayout spring = new SpringLayout();
int count = 1;
for (Point point: points) {
quest = new JButton("Question " + count);
quest.setForeground(Color.BLACK);
Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);
quest.setFont(fonte);
add (quest);
count++;
spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels );
spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels );
setLayout(spring);
panels.setOpaque(false);
panels.setVisible(true);
panels.setLocation(5,5);
add(panels);
quest.addActionListener(new java.awt.event.ActionListener(){
#Override
public void actionPerformed (ActionEvent p) {
if (point.equals(points.get(0))) {
new Quest1();
JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
else if (point.equals(points.get(1))) {
new Quest2();
JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
else if (point.equals(points.get(2))) {
new Quest3();
JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
else if (point.equals(points.get(3))) {
new Quest4();
JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
else if (point.equals(points.get(4))) {
new Quest5();
JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
Now, this is what my first called-up class (named Quest1) looks like
public class Quest1 {
//sound files to be shuffled and played!
String [] word = { "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/audio.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/bomb.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/baby.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/gym.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/hearing.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/goal.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/manifest.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/mountain.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/market.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/debate.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/election.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/number.wav",
};
//matching strings for each file
String [] words = { "Audio", "Bomb", "Baby", "Gym", "Hearing", "Goal", "Manifest","Mountain", "Market", "Debate", "Election", "Number" };
Random rand = new Random();
int random = rand.nextInt(word.length);
String temp = word[random];
int scores;
int fails;
public Quest1 () {
//announcing the JComponents to be used
JFrame frame = new JFrame ();
JButton click = new JButton("Play");
JTextField type = new JTextField(15);
JLabel pic = new JLabel(new ImageIcon("C:\\Users\\HP\\Desktop\\Sample pics\\1.png"));
JButton score = new JButton ("Check My Answer");
JPanel cont = new JPanel ();
//set up frame properties
frame.getContentPane().setBackground(Color.WHITE);
frame.setLayout(new FlowLayout());
frame.setUndecorated(true);
frame.setResizable(false);
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.add(cont, BorderLayout.CENTER);
frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
frame.setVisible(true);
//setting layout of JPanel
cont.setLayout(new GridBagLayout());
cont.setOpaque(false);
cont.setPreferredSize(new Dimension(500,500));
cont.setLocation(100, 50);
GridBagConstraints g = new GridBagConstraints();
g.anchor = GridBagConstraints.WEST;
g.gridx = 4;
g.gridy = 2;
g.gridwidth = 2;
g.insets = new Insets (70, 2, 2, 2);
cont.add(pic , g);
g.anchor = GridBagConstraints.WEST;
g.gridx = 4;
g.gridy = 5;
g.gridwidth = 2;
g.insets = new Insets (50, 2, 2, 2);
cont.add(click, g);
click.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e) {
//sound file shuffled and played
}
});
g.anchor = GridBagConstraints.EAST;
g.gridx = 10;
g.gridy = 4;
g.gridwidth = 5;
g.insets = new Insets(30, 2, 2, 10);
Font fonty = new Font("Lucida", Font.PLAIN, 15);
type.setFont(fonty);
cont.add(type, g);
g.anchor = GridBagConstraints.SOUTH;
g.gridx = 9;
g.gridy = 8;
g.gridwidth = 2;
g.insets = new Insets(2, 2, 2, 50);
cont.add(score, g);
score.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent tx) {
if (type.getText().equals(words[random])) {
//sound file played
scores+= 3;
String a = "Correct!..... The answer is " + words[random];
JOptionPane.showMessageDialog(null, a);
frame.dispose();
return;
}
else {
//sound file played again
fails+=0;
// This is where my problem is: The other 10 classes are like
//this, I want to get this value and that of scores (depending on the
//condition that is met), and add them up in the class beginner! )
String a = "Sorry, The Answer is " + words[random];
JOptionPane.showMessageDialog(null, a);
frame.dispose();
}
}
});
//sound file played
}
}

Your score and fail are local variables within the listener event. If you create an instance variable in your help class you can update them within the listener but they will persist as long as your program is running and then can be passed into more classes as constructor parameter for whatever purpose you may need.
public class help extends JFrame {
JPanel hold = new JPanel ();
JTextField enter = new JTextField(10);
JButton check = new JButton ("Check answer");
JButton quest = new JButton ("See question");
JLabel lunch = new JLabel ("Who is the current President of the United States?");
//Add fields you want to track here
int scores;
int fails;
public help () {
Then inside your listeners
scores += 3; //track them anyway you want
Update:
So it looks like you want to pass the score/fails from your Quest class back to your original class. You can do this by adding some accessor methods for scores and fails to your Quest class.
public int getScores(){
return scores;
}
public int getFails(){
return fails;
}
This will allow you get retrieve the values when you need them. You'd simply call them on the Quest object you made. However there's another problem...
new Quest1();
The quest needs to be stored in a variable like scores and fails or else it will get thrown away by the garbage collector. Add a variable that will hold the current Quest on top then swap them out when you switch quests.
Quest1 q1;
...
...
q1 = new Quest1();
...
...
scores = q1.getScores();
fails = q1.getFails();
Update: Button Flags
You can add flags to check if things have occurred by adding booleans variables. In this case you can have Quest1-5 flags in your Beginner class. When the user clicks on the class you can change it to true, then check if all of them have been done.
boolean Q1 = false;
boolean Q2 = false;
...
if (point.equals(points.get(0))) { // User clicks quest 1
Q1 = true;
...
...
if (checkQuests()){
//do stuff if all buttons are clicked
}
...
public boolean checkQuests(){ //cleaner if you use arrays
if(Q1 == false || Q2 == false || ... Q5== false){
return false;
}
else{
return true;
}
}
Update: Call back function
When working GUIs and listeners, not all actions happen in the sequence you want it to. GUIs and events happen on their own thread and often you want to trigger an event at the end of another. You can do this by utilize a call back function.
What is a callback function?
Here's how you can implement one in your program.
Inside your Quests include an interface and variable for an interface:
public class Quest{
CallBack cb;
interface CallBack{
public void callBack();
}
//add some way to set the call back, such as setter (or use constructor)
public void setCB(CallBack cb){ this.cb = cb;}
//Inside the action listener of your quest doing something
...
cb.callBack(); //call the callback method when you are done and want to do your check (it calls the beginner class back)
Inside your Beginner class:
//When creating a quest
Q1 = new Quest1();
Q1.setCB(new CallBack{
public void callBack(){
CheckQuests(); //this tells the program what to do when it hears back from Q1
}
}
What ends up happening is when the code of Q1 finishes, it calls the callBack() method (it could be any time but in your case call it when you're done with your logic).
The beginner class passes in code that tells Q1 what it should do when that method is called.

Related

Custom java calculator troubleshooting

New programmer here, I have been working for a few days on this bit of code that is meant to create a UI where I input a basement's perimeter length (textfield integer), if a new pump is needed (combobox string), if there is an outlet nearby (combobox string), and how many hours It will take to prepare a site (textfield integer), and I calculate my costs to complete a job. I was able to set up a UI where I can enter the inputs and press a button to calculate but I'm having trouble connecting the button I made to the formula I made to generate a price. Here is my code:
package packagepackage;
import packagepackage.HintTextFieldUI;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CP_GUI implements ActionListener {
String[] sumpo = {"New sump pump","Existing sump pump"};
String[] electo = {"There is an outlet within 6 feet of sump pump","There is no outlet nearby, or I do not need a new one"};
Integer estimatex = 0;
String esto = String.valueOf(estimatex);
public volatile String estimatoof = "Estimated Cost: ${}".format(esto);
private JComboBox sump = new JComboBox(sumpo);
private JComboBox elec = new JComboBox(electo);
private JTextField linear = new JTextField();
private JTextField prep = new JTextField();
private JLabel title = new JLabel("Drain Tile Calculator");
private JButton calculate = new JButton("Calculate!");
public JLabel estimate = new JLabel(estimatoof);
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
public CP_GUI() {
linear.addActionListener(this);
calculate.addActionListener(this);
elec.addActionListener(this);
sump.addActionListener(this);
prep.addActionListener(this);
// the panel with the button and text
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(400, 400, 100, 100));
panel.setLayout(new GridLayout(0, 1));
panel.add(linear);
panel.add(sump);
panel.add(elec);
panel.add(prep);
frame.add(panel, BorderLayout.CENTER);
panel.add(title);
calculate.addActionListener(this);
panel.add(calculate);
// set up the frame and display it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Drain Tile Calculator");
frame.pack();
frame.setVisible(true);
linear.setUI(new HintTextFieldUI("Perimeter length", true));
prep.setUI(new HintTextFieldUI("Hours of preptime", true));}
// create one Frame
public static void main(String[] args) {
new CP_GUI();
}
#Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
if(e.getSource()==linear) {String input = linear.getText();
Integer pars = Integer.parseInt(input);
Integer distVar = pars *= 13;
estimatex += distVar;
} else if (e.getSource()==sump) {String inputa = sump.getToolTipText();
int sumpa = 0;
if(inputa == "New sump pump" | inputa == "yes") {
sumpa += 260;}
estimatex += sumpa;
} else if (e.getSource()==elec) {String inputb =elec.getToolTipText();
int eleca = 0;
if("There is an outlet within 6 feet of the sump pump".equals(inputb)) {
eleca += 1;
}
eleca *= 280;
estimatex += eleca;
}
else if (e.getSource()==prep) {String inputc = prep.getText();
int parsa = Integer.parseInt(inputc);
int prepCost = parsa += 1;
prepCost *= 110;
estimatex += prepCost;
} else if (e.getSource()==linear) {
String disto = linear.getText();
int di = Integer.parseInt(disto);
di *= 13;
String pumpo = (String)sump.getSelectedItem();
int sumpo = 0;
if ("New sump pump".equals(pumpo)) {
sumpo += 260;
}
String ele = (String)elec.getSelectedItem();
int elc = Integer.parseInt(ele);
elc *= 280;
String clea = prep.getText();
int cla = Integer.parseInt(clea);
cla += 1;
cla *= 110;
int cali = 0;
cali += di;
cali += sumpo;
cali += elc;
cali += cla;
estimatex = cali;
}
}
}
Edit: Made the suggested edits made so far and now the UI opens and works, the only issue is that the estimated price does not show up. Am I connecting the action listener correctly?
Your "primary" problem is right here...
String disto = String.valueOf(linear);
where linear is a JTextField, so the above call will generate something like...
javax.swing.JTextField[,0,0,0x0,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.apple.laf.AquaTextFieldBorder#4e323305,flags=288,maximumSize=,minimumSize=,preferredSize=,caretColor=javax.swing.plaf.ColorUIResource[r=0,g=0,b=0],disabledTextColor=javax.swing.plaf.ColorUIResource[r=128,g=128,b=128],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=com.apple.laf.AquaImageFactory$SystemColorProxy[r=0,g=0,b=0],selectionColor=com.apple.laf.AquaImageFactory$SystemColorProxy[r=165,g=205,b=255],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]
which is obviously not what you're looking for.
You should probably be just doing something like...
String disto = linear.getText();
pumpo == "New sump pump" is also not how you compare a String in Java, you should be using "New sump pump".equals(pumpo) ... but I suspect you're going to have the same issues as mentioned above.
I really recommend you take the time to read through Creating a GUI With Swing as well as taking the time to come to grips with the core basics of the language

Comparing the text of different JButtons

I am currently coding a game and part of it consist of having different tiles to be put in a board. I plan on simulating this by having different buttons that will be used to represent the tiles with their corresponding coordinates. For example, one button will say "A1", "A2", etc. What I would like to accomplish, is to have the user click on the "A1" tile and then the button on the board that represents "A1" will change colors, is there any way to go through the buttons on the board and compare its text to the selection of the user? The following is what I used to create the board:
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
panel.add(buttons[r][c]);
}
}
This is what I wrote on the code of one of the tiles
JButton tile1 = new JButton ("A1");
tile1.setBounds(60,725,60,60);
frame.getContentPane().add(tile1);
tile1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String buttonText = tile1.getText();
// iterating through all buttons:
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++)
{
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText))
{
[i][j].setBackground(Color.BLACK);
}
}
}
}
} );
However, it is given me an error saying that there is an action expected after "{"
You may add an action listener to each of the JButton you are creating in the loop like below:
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code here
}
} );
Placing the listener in your code may look like
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
// now iterate over all the jbuttons you have
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++){
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText)){
// you found a match here
// and you have the positions i, j
//
}
}
}
}
} );
panel.add(buttons[r][c]);
}
}
And you could store the the colors to be changed to in global static array, and use that array in your action listener.
For information on adding listener to the JButton, you may refer this thread How do you add an ActionListener onto a JButton in Java
Hope this helps!
You need listeners.
Implement ActionListener to your class. This will require you to add public void actionPerformed(ActionEvent e) {} to your class.
Every JButton you use should have an action listener.
Apply one like that:
JButton but = new JButton();
but.addActionListener(this);
Finally, in the actionPerformed method we added, you need to add something like that:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but)
but.setBackground(Color.BLACK);
}
P.S. you can get a button's text value by the means of:
but.getText();

Trouble displaying dice images in a JApplet

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:

Swing gui not hiding/showing properly

I am writing this gui in java and it works great, except I recently discovered a bug. Currently I access each of my screens through file menus and use the below method to switch back and forth between the panels I am looking at. I have also included the method which one of the file menu actionlisteners executes. For the sake of brevity I have not included the others, just know that they use the same types of commands in a very similar order.
The problem is that sometimes when clicking between the screens, elements of the previous panel will be still visible on the new panel. This new panel will usually be missing most or all of its elements as well. Another (and probably related) issue I am experiencing is that when I run the code half or more of the time I see my initial screen but after that when I click to a new screen nothing shows up at all. It is very confusing because I don't change anything with the code or even recompile between runs and it behaves differently. This second problem has only been occurring since I moved the add methods for the panels to the setCurrentPanel for simplicity's sake.
private void setCurrentPanel(JPanel current) {
System.out.println(oldCurrent.getName() + " " + current.getName());
if (oldCurrent.getName().equals(current.getName())) {
} else {
buildingPanel.setVisible(false);
securityPanel.setVisible(false);
adminUsersPanel.setVisible(false);
adminBuildingPanel.setVisible(false);
adminServerPanel.setVisible(false);
changePasswordPanel.setVisible(false);
serverSettingsPanel.setVisible(false);
addBuildingPanel.setVisible(false);
addUser.setVisible(false);
for (BuildingItem item : buildingMenuItem) {
item.panel.setVisible(false);
}
add(current);
current.setVisible(true);
revalidate();
repaint();
oldCurrent = current;
refreshCount = refreshCount + 1;
System.out.println("Refresh " + refreshCount);
}
}
private void setupAdminServerPanel() {
getServerSettingsFromSQL();
serverSettingsPanel = new JPanel(new GridBagLayout());
serverSettingsPanel.setName("Server Settings Panel");
GridBagConstraints gbr = new GridBagConstraints();
SpinnerModel minPasswordModel = new SpinnerNumberModel(Integer.parseInt(settingMinPassword), 5, 20, 1);
SpinnerModel minUsernameModel = new SpinnerNumberModel(Integer.parseInt(settingMinUsername), 5, 20, 1);
final JSpinner minPasswordSpinner = new JSpinner(minPasswordModel);
final JSpinner minUsernameSpinner = new JSpinner(minUsernameModel);
JButton lockdownButton = new JButton("Lockdown");
lockdownButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
lockdownMode();
}
});
JButton ApplyButton = new JButton("Apply");
ApplyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (minPasswordSpinner.getValue() != Integer.parseInt(settingMinPassword) ||
(minUsernameSpinner.getValue() != Integer.parseInt(settingMinUsername))) {
writeSettingsToSQL((Integer) minPasswordSpinner.getValue(),
(Integer) minUsernameSpinner.getValue());
getServerSettingsFromSQL();
}
}
});
lockdownButton.setPreferredSize(new Dimension(50, 50));
minUsernameSpinner.setPreferredSize(new Dimension(150, 30));
minPasswordSpinner.setPreferredSize(new Dimension(150, 30));
gbr.gridy = 0;
gbr.gridx = 1;
gbr.gridwidth = 1;
gbr.ipady = 0;
gbr.insets = new Insets(10, 10, 10, 10);
serverSettingsPanel.add(lockdownButton, gbr);
gbr.gridy = 1;
gbr.gridx = 0;
serverSettingsPanel.add(new JLabel("Minimum Username Length"), gbr);
gbr.gridy = 2;
gbr.gridx = 0;
serverSettingsPanel.add(new JLabel("Minimum Password Length"), gbr);
gbr.gridy = 1;
gbr.gridx = 1;
gbr.gridwidth = 2;
serverSettingsPanel.add(minUsernameSpinner, gbr);
gbr.gridy = 2;
serverSettingsPanel.add(minPasswordSpinner, gbr);
gbr.gridy = 3;
gbr.gridx = 1;
gbr.gridwidth = 1;
serverSettingsPanel.add(ApplyButton, gbr);
setCurrentPanel(serverSettingsPanel);
}
If you need to see more of the code let me know. I really would appreciate any help I can get! Thanks
I am not allowed to comment, so maybe it is not a full answer:
You revalidate and repaint the panel, do you do it to the frame or panel, in which it is displayed?
As already suggested, Card Layout is a better way.

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