setText() not updating label - java

I have searched the internet trying to fix my problem. The whoWon.setText() part is not updating the JLabel.
The part where it should update the JLabel is in the PlayAgain.java file under the comment
//Get Winner
I have tried repaint() and postInvalidate() and still it is not working. There must be something I am missing.
Here is the code:
TicTacToe.java =>
package ticTacToe;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicTacToe extends JFrame implements ActionListener {
private JPanel contentPane;
boolean winner = false;
boolean draw = false;
byte count = 0;
String btnLabel;
PlayAgain playAgain = new PlayAgain();
JButton btn1 = new JButton("");
JButton btn2 = new JButton("");
JButton btn3 = new JButton("");
JButton btn4 = new JButton("");
JButton btn5 = new JButton("");
JButton btn6 = new JButton("");
JButton btn7 = new JButton("");
JButton btn8 = new JButton("");
JButton btn9 = new JButton("");
static TicTacToe frame = new TicTacToe();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TicTacToe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 616, 637);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btn1.setBounds(0, 0, 200, 200);
btn1.addActionListener(this);
contentPane.add(btn1);
btn2.setBounds(200, 0, 200, 200);
btn2.addActionListener(this);
contentPane.add(btn2);
btn3.setBounds(400, 0, 200, 200);
btn3.addActionListener(this);
contentPane.add(btn3);
btn4.setBounds(0, 200, 200, 200);
btn4.addActionListener(this);
contentPane.add(btn4);
btn5.setBounds(200, 200, 200, 200);
btn5.addActionListener(this);
contentPane.add(btn5);
btn6.setBounds(400, 200, 200, 200);
btn6.addActionListener(this);
contentPane.add(btn6);
btn7.setBounds(0, 400, 200, 200);
btn7.addActionListener(this);
contentPane.add(btn7);
btn8.setBounds(200, 400, 200, 200);
btn8.addActionListener(this);
contentPane.add(btn8);
btn9.setBounds(400, 400, 200, 200);
btn9.addActionListener(this);
contentPane.add(btn9);
}
//Main Code
#Override
public void actionPerformed(ActionEvent e) {
//Play label (Player 1 = X, Player 2 = O)
if(count==0 || count==2 || count==4 || count==6 || count==8){
btnLabel = "X";
}else btnLabel = "O";
count++;
//Clicking buttons
if(e.getSource()==btn1){
btn1.setText(btnLabel);
btn1.setEnabled(false);
btn1.setBackground(Color.BLACK);
}
else if(e.getSource()==btn2){
btn2.setText(btnLabel);
btn2.setEnabled(false);
btn2.setBackground(Color.BLACK);
}
else if(e.getSource()==btn3){
btn3.setText(btnLabel);
btn3.setEnabled(false);
btn3.setBackground(Color.BLACK);
}
else if(e.getSource()==btn4){
btn4.setText(btnLabel);
btn4.setEnabled(false);
btn4.setBackground(Color.BLACK);
}
else if(e.getSource()==btn5){
btn5.setText(btnLabel);
btn5.setEnabled(false);
btn5.setBackground(Color.BLACK);
}
else if(e.getSource()==btn6){
btn6.setText(btnLabel);
btn6.setEnabled(false);
btn6.setBackground(Color.BLACK);
}
else if(e.getSource()==btn7){
btn7.setText(btnLabel);
btn7.setEnabled(false);
btn7.setBackground(Color.BLACK);
}
else if(e.getSource()==btn8){
btn8.setText(btnLabel);
btn8.setEnabled(false);
btn8.setBackground(Color.BLACK);
}
else if(e.getSource()==btn9){
btn9.setText(btnLabel);
btn9.setEnabled(false);
btn9.setBackground(Color.BLACK);
}
//Win Conditions
//Horizontal
if(btn1.getText().equals(btn2.getText())&&btn2.getText().equals(btn3.getText())&!btn1.getText().equals("")){
winner = true;
afterGame(btnLabel);
}
else if(btn4.getText().equals(btn5.getText())&&btn5.getText().equals(btn6.getText())&!btn4.getText().equals("")){
winner = true;
afterGame(btnLabel);
}
else if(btn7.getText().equals(btn8.getText())&&btn8.getText().equals(btn9.getText())&!btn7.getText().equals("")){
winner = true;
afterGame(btnLabel);
}
//Vertical
else if(btn1.getText().equals(btn4.getText())&&btn4.getText().equals(btn7.getText())&!btn1.getText().equals("")){
winner = true;
afterGame(btnLabel);
}
else if(btn2.getText().equals(btn5.getText())&&btn5.getText().equals(btn8.getText())&!btn2.getText().equals("")){
winner = true;
afterGame(btnLabel);
}
else if(btn3.getText().equals(btn6.getText())&&btn6.getText().equals(btn9.getText())&!btn3.getText().equals("")){
winner = true;
afterGame(btnLabel);
}
//Diagonal
else if(btn1.getText().equals(btn5.getText())&&btn5.getText().equals(btn9.getText())&!btn1.getText().equals("")){
winner = true;
afterGame(btnLabel);
}
else if(btn3.getText().equals(btn5.getText())&&btn5.getText().equals(btn7.getText())&!btn3.getText().equals("")) {
winner = true;
afterGame(btnLabel);
}
//Draw
else if(count==9&winner==false)System.out.println("Game is draw");
}
public void afterGame(String btnName){
playAgain.getWinner(btnName);
playAgain = new PlayAgain();
playAgain.setVisible(true);
frame.dispose();
}
}
PlayAgain.java =>
package ticTacToe;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
public class PlayAgain extends JFrame {
private JPanel contentPane;
JLabel whoWon = new JLabel();
static PlayAgain frame = new PlayAgain();
String winner;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PlayAgain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 153);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
whoWon.setText(" ");
whoWon.setFont(new Font("Tahoma", Font.BOLD, 18));
whoWon.setBounds(10, 11, 414, 48);
contentPane.add(whoWon);
JButton playAgain = new JButton("Play Again!");
playAgain.setBounds(10, 70, 200, 34);
contentPane.add(playAgain);
JButton exit = new JButton("Quit!");
exit.setBounds(220, 70, 204, 34);
contentPane.add(exit);
}
//Get Winner
public void getWinner(String player){
System.out.println("getWinner()");
System.out.println("btnName: " + player);
if(player.equals("X")){
System.out.println("Player 1 won");
whoWon.setText("Player 1 has won!");
repaint();
}
else {
System.out.println("Player 2 won");
whoWon.setText("Player 2 has won!");
repaint();
}
}
}
EDIT: System.out.println() are there to help me follow the program's steps

I think your problem is in method afterGame . You call getWinner method for one instance and then, in next line, create a new one with empty value , because of that your label doesn't change text . You see a new instance of object.

You mustn't check string equality with ==. Use equals:
if (player.equals("X"))
btn1.getText()==btn2.getText() is bad equality check too...

Do this somewhere before the label is updated ans see if it helps. If the label isnt updating, it might be because it isnt editable/enabled.
whoWon.setEditable(true);

Related

How to remove the blank JFrame from appearing?

When I run my java program, two JFrames are showing, the JFrame that I created and another one that is blank that I cannot close. I think this error also has something to do with my JFrame that I created with components in it, not show when I run the program, instead the one showing is the blank JFrame. How do I fix this?
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import java.awt.Font;
public class trial extends Frame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
JButton newButton1, newButton2, newButton3,newButton4,newButton5,newButton6,newButton7,newButton8,newButton9;
Icon ic1=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A1.png");
Icon ic2=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A2.png");
Icon ic3=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A3.png");
Icon ic4=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A4.png");
Icon ic5=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A5.png");
Icon ic6=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A6.png");
Icon ic7=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A7.png");
Icon ic8=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A8.png");
Icon pink=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\c9.png");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
trial window = new trial();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public trial() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 986, 677);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
newButton1 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A1.png"));
newButton1.setBounds(43, 37, 150, 150);
newButton2 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A2.png"));
newButton2.setBounds(191,37, 150, 150);
newButton3 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A3.png"));
newButton3.setBounds(340,37, 150, 150);
newButton4 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A4.png"));
newButton4.setBounds(43,186, 150, 150);
newButton5 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A5.png"));
newButton5.setBounds(191,186, 150, 150);
newButton6 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A6.png"));
newButton6.setBounds(340,186, 150, 150);
newButton7 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A7.png"));
newButton7.setBounds(43,335, 150, 150);
newButton8 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A8.png"));
newButton8.setBounds(191,335,150, 150);
newButton9 = new JButton(pink);
newButton9.setBounds(340,335,150, 150);
newButton1.addActionListener(this);
newButton2.addActionListener(this);
newButton3.addActionListener(this);
newButton4.addActionListener(this);
newButton5.addActionListener(this);
newButton6.addActionListener(this);
newButton7.addActionListener(this);
newButton8.addActionListener(this);
newButton9.addActionListener(this);
frame.getContentPane().add(newButton1);frame.getContentPane().add(newButton2);frame.getContentPane().add(newButton3);frame.getContentPane().add(newButton4);frame.getContentPane().add(newButton5);frame.getContentPane().add(newButton6);
frame.getContentPane().add(newButton7);frame.getContentPane().add(newButton8);frame.getContentPane().add(newButton9);
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
DrumInfo a = new DrumInfo();
a.setLocationRelativeTo(null);
a.setVisible(true);
}
});
btnNewButton.setIcon(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\drums.png"));
btnNewButton.setBounds(597, 37, 300, 277);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("Click the picture to find out what's the picture about!");
lblNewLabel.setFont(new Font("Berlin Sans FB Demi", Font.PLAIN, 15));
lblNewLabel.setBounds(563, 315, 382, 45);
frame.getContentPane().add(lblNewLabel);
JButton btnNewButton_1 = new JButton("BACK");
btnNewButton_1.setBounds(412, 563, 156, 63);
frame.getContentPane().add(btnNewButton_1);
JButton btnCategories = new JButton("CATEGORIES");
btnCategories.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
Puzzle2 a = new Puzzle2();
a.setLocationRelativeTo(null);
a.setVisible(true);
}
});
btnCategories.setBounds(604, 563, 156, 63);
frame.getContentPane().add(btnCategories);
JButton btnNext = new JButton("NEXT");
btnNext.setBounds(789, 563, 156, 63);
frame.getContentPane().add(btnNext);
setSize(600,500);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==newButton1){
Icon s1 = newButton1.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton1.setIcon(pink);
}
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton1.setIcon(pink);
}
}
if(e.getSource()==newButton2){
Icon s1 = newButton2.getIcon();
if(newButton1.getIcon().equals(pink)) {
newButton1.setIcon(s1);
newButton2.setIcon(pink);
}
if(newButton3.getIcon().equals(pink)) {
newButton3.setIcon(s1);
newButton2.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton2.setIcon(pink);
}
}
if(e.getSource()==newButton3){
Icon s1 = newButton3.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton3.setIcon(pink);
}
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton3.setIcon(pink);
}
}
if(e.getSource()==newButton4){
Icon s1 = newButton4.getIcon();
if(newButton1.getIcon().equals(pink)) {
newButton1.setIcon(s1);
newButton4.setIcon(pink);
}
if(newButton7.getIcon().equals(pink)) {
newButton7.setIcon(s1);
newButton4.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton4.setIcon(pink);
}
}
if(e.getSource()==newButton5){
Icon s1 = newButton5.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton5.setIcon(pink);
}
}
if(e.getSource()==newButton6){
Icon s1 = newButton6.getIcon();
if(newButton9.getIcon().equals(pink)) {
newButton9.setIcon(s1);
newButton6.setIcon(pink);
}
if(newButton3.getIcon().equals(pink)) {
newButton3.setIcon(s1);
newButton6.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton6.setIcon(pink);
}
}
if(e.getSource()==newButton7){
Icon s1 = newButton7.getIcon();
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton7.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton7.setIcon(pink);
}
}
if(e.getSource()==newButton8){
Icon s1 = newButton8.getIcon();
if(newButton9.getIcon().equals(pink)) {
newButton9.setIcon(s1);
newButton8.setIcon(pink);
}
if(newButton7.getIcon().equals(pink)) {
newButton7.setIcon(s1);
newButton8.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton8.setIcon(pink);
}
}
if(e.getSource()==newButton9){
Icon s1 = newButton9.getIcon();
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton9.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton9.setIcon(pink);
}
}
if(newButton1.getIcon().equals(ic1)&&newButton2.getIcon().equals(ic2)&&newButton3.getIcon().equals(ic3)&&newButton4.getIcon().equals(ic4)&&newButton5.getIcon().equals(ic5)&&newButton6.getIcon().equals(ic6)&&newButton7.getIcon().equals(ic7)&&newButton8.getIcon().equals(ic8)&&newButton9.getIcon().equals(pink)) {
JOptionPane.showMessageDialog(this,"Congratulations! You won.");
}
}
}

Changing JPanel Icon when JButton is clicked

The JFrame window needs to display a random dice image. When the button is clicked, the random dice image needs to change. I have figured out how to display the random dice image, but I cannot figure out how to use the actionlistener to generate a new random dice image. I am only in my third Java class, so any guidance would be greatly appreciated!
package guiDice;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.event.ActionEvent;
public class LabGuiDice extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LabGuiDice frame = new LabGuiDice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LabGuiDice() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnRollem = newDiceRoll();
contentPane.add(btnRollem, BorderLayout.SOUTH);
JLabel lblDice = newDiceImage();
contentPane.add(lblDice, BorderLayout.CENTER);
}
private JLabel newDiceImage() {
Random rnd = new Random();
int rand1 = 0;
rand1 = rnd.nextInt(6)+1;
JLabel lblDice = new JLabel("");
switch (rand1) {
case 1:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-1.png")));
break;
case 2:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-2.png")));
break;
case 3:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-3.png")));
break;
case 4:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-4.png")));
break;
case 5:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-5.png")));
break;
case 6:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-6.png")));
break;
}
return lblDice;
}
private JButton newDiceRoll() {
JButton btnRollem = new JButton("Roll 'Em");
btnRollem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnRollem.setBorderPainted(false);
btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
btnRollem.setOpaque(true);
btnRollem.setBackground(new Color(255, 0, 0));
return btnRollem;
}
}
Create a method that generates the integer and sets the icon to the label. But in order to do that, label should be a field in the class, so all methods can access it. For example:
private void rollDice() {
Random random = new Random();
int randomInt = random.nextInt(6) + 1;
String resource = String.format("/Dice/die-%d.png", randomInt);
Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
diceIconLabel.setIcon(icon);
}
and then:
btnRollem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rollDice();
}
});
with full code:
public class LabGuiDice extends JFrame {
private JPanel contentPane;
private JLabel diceIconLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
LabGuiDice frame = new LabGuiDice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LabGuiDice() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnRollem = newDiceRoll();
contentPane.add(btnRollem, BorderLayout.SOUTH);
diceIconLabel = newDiceImage();
contentPane.add(diceIconLabel, BorderLayout.CENTER);
rollDice();
pack();
}
private void rollDice() {
Random random = new Random();
int randomInt = random.nextInt(6) + 1;
String resource = String.format("/Dice/die-%d.png", randomInt);
Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
diceIconLabel.setIcon(icon);
}
private JLabel newDiceImage() {
JLabel lblDice = new JLabel("");
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
return lblDice;
}
private JButton newDiceRoll() {
JButton btnRollem = new JButton("Roll 'Em");
btnRollem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rollDice();
}
});
btnRollem.setBorderPainted(false);
btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
btnRollem.setOpaque(true);
btnRollem.setBackground(new Color(255, 0, 0));
return btnRollem;
}
}

Why will this code compile in eclipse but not jGrasp

I decided to take a java class and the prof wants all the .java files to run in jGrasp but I am much more familiar with eclipse so I've been using that. I have two files who will compile fine in eclipse but when I open their .java files in jGrasp they either don't execute correctly or some of the import statements cause errors.
This one will compile but the JFrame will be empty:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class JDisappearingFriends {
static int i = 1;
static void increase_i() {
++i;
}
public static void main(String[] args) {
JFrame frame1 = new JFrame();
frame1.setVisible(true);
frame1.setSize(303, 286);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel[] friends = new JLabel[6];
friends[0] = new JLabel(
"Hello. To begin changing friends press the button");
friends[1] = new JLabel("Laura");
friends[2] = new JLabel("Kendra");
friends[3] = new JLabel("Nicole");
friends[4] = new JLabel("Melissa");
friends[5] = new JLabel("Elizabeth");
frame1.add(friends[0]);
JButton btnChangeFriends = new JButton("Change Friends");
btnChangeFriends.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (i < 6) {
frame1.getContentPane().add(friends[i]);
frame1.remove(friends[i - 1]);
frame1.revalidate();
frame1.repaint();
increase_i();
} else {
JLabel done = new JLabel("That's it, your out of friends");
frame1.remove(friends[5]);
frame1.add(done);
frame1.revalidate();
frame1.repaint();
}
}
});
frame1.getContentPane().add(btnChangeFriends, BorderLayout.SOUTH);
}
}
This code won't compile at all. jGrasp claims the import statement for jGoodies is invalid but it works fine in eclipse.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.RowSpec;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class JPhotoFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JPhotoFrame frame = new JPhotoFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JPhotoFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 505, 274);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
panel.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("46px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),},
new RowSpec[] {
FormFactory.LINE_GAP_ROWSPEC,
RowSpec.decode("23px"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JLabel lblNewLabel_2 = new JLabel("Please select a number of people. Pets Optional");
panel.add(lblNewLabel_2, "2, 2, 7, 1, fill, center");
JCheckBox single = new JCheckBox("Single ");
panel.add(single, "4, 4, left, top");
JCheckBox more_people = new JCheckBox("2+ People");
panel.add(more_people, "6, 4, left, top");
JCheckBox pets = new JCheckBox("Pet");
panel.add(pets, "8, 4, left, top");
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.NORTH);
panel_1.setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("87px"),
ColumnSpec.decode("46px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("97px"),},
new RowSpec[] {
FormFactory.LINE_GAP_ROWSPEC,
RowSpec.decode("23px"),}));
JLabel lblNewLabel_3 = new JLabel("Please select a location");
panel_1.add(lblNewLabel_3, "1, 2, 3, 1, left, center");
JCheckBox studio = new JCheckBox("Studio");
panel_1.add(studio, "4, 2, left, top");
JCheckBox other = new JCheckBox("Other");
panel_1.add(other, "6, 2, left, top");
studio.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if((e.getStateChange() == ItemEvent.SELECTED)){
other.setEnabled(false);
}
}
});
other.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if((e.getStateChange() == ItemEvent.SELECTED)){
studio.setEnabled(false);
}
}
});
single.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if((e.getStateChange() == ItemEvent.SELECTED)){
more_people.setEnabled(false);
}
}
});
more_people.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if((e.getStateChange() == ItemEvent.SELECTED)){
single.setEnabled(false);
}
}
});
JLabel lblNewLabel = new JLabel("Press Button to calculate total cost");
contentPane.add(lblNewLabel, BorderLayout.SOUTH);
JButton btnCalculateTotal = new JButton("Calculate Total");
btnCalculateTotal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int total = 0;
int other_price=0;
int single_price=0;
int more_people_price=0;
int pets_price=0;
if(studio.isSelected() == false && other.isSelected()== false){
lblNewLabel.setText("Please enter a least one location value");
}
else if(single.isSelected() == false && more_people.isSelected() == false){
lblNewLabel.setText("Please enter at least one subject value");
}
else{
if(single.isSelected() == true) single_price = 40;
if(other.isSelected() ==true ) other_price = 90;
if(more_people.isSelected() == true) more_people_price = 75;
if(pets.isSelected() == true) pets_price = 95;
total = calculate(single_price,other_price, more_people_price, pets_price);
lblNewLabel.setText("Your Total is: $" + total);
}
lblNewLabel.revalidate();
lblNewLabel.repaint();
studio.setEnabled(true);
other.setEnabled(true);
single.setEnabled(true);
more_people.setEnabled(true);
studio.setSelected(false);
other.setSelected(false);
single.setSelected(false);
more_people.setSelected(false);
pets.setSelected(false);
}
});
contentPane.add(btnCalculateTotal, BorderLayout.EAST);
}
int calculate(int single, int other, int more_people, int pets){
int total = single + other + more_people + pets;
return total;
}
}
When you create a project in eclipse it creates certain dependencies to packages and modules based on its configuration.
The program is showing an empty JFrame because the project in eclipse uses those dependancies but jGrasp can't find them because it is not familiar with project structure of eclipse.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException if-statement

I'm developing a tic tac toe game and have one problem - Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException, it occurs when i try to press the button. The buttonText is changed to X, but after that i get the problem. I believe there is something wrong with if statements:
The source code of Main.java:
package mytictactoegame;
public class Main {
public static boolean playerTurn = true;
public static boolean playerWon = false;
public static boolean compWon = false;
public static boolean playing = true;
public static ticgame board = new ticgame ();
public static void main(String[] args) {
board.setVisible(true);
}
public static void checkforwin (){
//147
if (board.button1.getText().equals("X")){
if (board.button4.getText().equals("X")){
if (board.button7.getText().equals("X")){
playerWon = true;
compWon = false;
board.labelWon.setText ("Player X won!");
}
}
}
}
}
And ticgame (GUI):
package mytictactoegame;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.GridLayout;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.RowSpec;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JLabel;
public class ticgame extends JFrame {
Main main = new Main ();
/**
*
*/
public static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ticgame frame = new ticgame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ticgame() {
setTitle("Tic Tac Toe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(new Color(204, 255, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(3, 3, 0, 0));
JButton button1 = new JButton("");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (button1.getText().equals("")){
if (Main.playerTurn == true){
button1.setText("X");
Main.checkforwin();
Main.playerTurn = false;
} else {
button1.setText("O");
Main.checkforwin();
Main.playerTurn = true;
}
}
}
});
panel.add(button1);
JButton button4 = new JButton("");
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (button4.getText().equals("")){
if (Main.playerTurn == true){
button4.setText("X");
Main.checkforwin();
Main.playerTurn = false;
} else {
button4.setText("O");
Main.checkforwin();
Main.playerTurn = true;
}
}
}
});
panel.add(button4);
JButton button7 = new JButton("");
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (button7.getText().equals("")){
if (Main.playerTurn == true){
button7.setText("X");
Main.checkforwin();
Main.playerTurn = false;
} else {
button7.setText("O");
Main.checkforwin();
Main.playerTurn = true;
}
}
}
});
panel.add(button7);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.EAST);
panel_1.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
ColumnSpec.decode("117px"),},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("29px"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JButton buttonNewGame = new JButton("New Game");
buttonNewGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button1.setText("");
button2.setText("");
button3.setText("");
button4.setText("");
button5.setText("");
button6.setText("");
button7.setText("");
button8.setText("");
button9.setText("");
Main.playerTurn = true;
Main.playerWon = false;
Main.compWon = false;
}
});
buttonNewGame.setForeground(Color.RED);
buttonNewGame.setBackground(new Color(153, 255, 0));
panel_1.add(buttonNewGame, "2, 2, left, top");
JButton buttonHistory = new JButton("History");
buttonHistory.setForeground(Color.RED);
panel_1.add(buttonHistory, "2, 4");
JButton buttonExit = new JButton("Exit");
buttonExit.setForeground(Color.RED);
buttonExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panel_1.add(buttonExit, "2, 6");
JLabel labelWon = new JLabel();
labelWon.setText ("Who won?");
labelWon.setForeground(Color.GREEN);
panel_1.add(labelWon, "2, 10, left, default");
}
public JButton button1;
public JButton button2;
public JButton button3;
public JButton button4;
public JButton button5;
public JButton button6;
public JButton button7;
public JButton button8;
public JButton button9;
public JLabel labelWon;
}
Here is first lines of the error log, the rest doesnt fit due to number of words:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mytictactoegame.Main.checkforwin(Main.java:20)
at mytictactoegame.ticgame$2.actionPerformed(ticgame.java:71)
You're shadowing your variables such as your button1 variable and others like it. By shadowing, I mean that you declare them in the class, but then re-declare and initialize the re-declared variable in your class's constructor. When you do that, the field (the variable declared in the class) remains null. Solution: don't shadow your variables by not re-declaring them in the constructor.
e.g., you do this:
// should be named TicGame to comply with Java naming standards
public class ticgame extends JFrame {
public ticgame() {
// ....
// here you re-declare the button1 variable
// by doing this, you initialize the local variable that
// is present int he constructor but leave the class field null
JButton button1 = new JButton("");
//....
}
public JButton button1; // this guy remains null
// .....
}
When you should be doing this:
public class TicGame extends JFrame {
public TicGame() {
// ....
// JButton button1 = new JButton("");
button1 = new JButton(""); // note the difference?
//....
}
public JButton button1; // now he's not null!
// .....
}

My image disappear when i run jar file

well here are the classes i made..
package testdnevnik;
import javax.swing.JFrame;
public class Diary {
StartWindow startWindow = new StartWindow();
static JFrame frame = new JFrame("Diary");
int n = 0;
public Diary() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
//frame.add(new ImagePanel("Img//bg2.jpeg"));
frame.setVisible(true);
frame.add(startWindow);
startWindow.checkStudents(n);
startWindow.chooseOption();
}
public static void main(String[] args) {
new Diary();
}
}
that was the main class,and here is the panel for the start window..
package testdnevnik;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import static testdnevnik.Diary.frame;
public class StartWindow extends JPanel {
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JLabel headline = new JLabel();
JButton viewStudents = new JButton();
JButton editStudents = new JButton();
JButton addStudents = new JButton();
JButton removeStudents = new JButton();
JLabel usernameLbl = new JLabel();
JLabel passwordLbl = new JLabel();
JTextField usernameFld = new JTextField();
JPasswordField passwordFld = new JPasswordField();
JButton logIn = new JButton("Log In");
JButton signUp = new JButton("Sign Up");
public StartWindow () {
jp.setLayout( new BorderLayout() );
// headline
headline.setText("Diary");
headline.setLocation(200, 30);
headline.setHorizontalAlignment(JLabel.CENTER);
headline.setFont(new Font("Serif", Font.BOLD, 60));
headline.setForeground(Color.ORANGE);
headline.setSize(300, 80);
headline.setVisible(true);
// Buttons
//View Students - Button
viewStudents.setText("View All Students");
viewStudents.setSize(200,40);
viewStudents.setLocation(70 , 200);
viewStudents.setVisible(true);
// Edit Students - Button
editStudents.setText("Edit Students");
editStudents.setSize(200,40);
editStudents.setLocation(70 , 300);
editStudents.setVisible(true);
// Add Students - Button
addStudents.setText("Add New Students");
addStudents.setSize(200,40);
addStudents.setLocation(70 ,400);
addStudents.setVisible(true);
// Remove Students - Button
removeStudents.setText("Remove Students");
removeStudents.setSize(200,40);
removeStudents.setLocation(70 , 500);
removeStudents.setVisible(true);
// username and password labels and input field
usernameLbl.setText("Username: ");
usernameLbl.setBounds(320, 200, 108, 40);
usernameLbl.setFont(new Font(null,Font.BOLD, 20));
usernameLbl.setVisible(true);
usernameFld.setBounds(450, 205, 200, 30); // username field input
usernameFld.setVisible(true);
passwordLbl.setText("Password: ");
passwordLbl.setBounds(320, 300, 108, 40);
passwordLbl.setFont(new Font(null,Font.BOLD, 20));
passwordLbl.setVisible(true);
passwordFld.setBounds(450, 305, 200, 30); // password field input
passwordFld.setVisible(true);
// button for log in and sign up
logIn.setBounds(580, 400, 70, 40);
logIn.setVisible(true);
signUp.setBounds(480, 400, 90, 40);
signUp.setVisible(true);
// panel
jp.setSize(new Dimension(800,600));
jp.add(viewStudents); // add ViewStudents button to the panel
jp.add(editStudents); // add EditStudents button to the panel
jp.add(addStudents); // add AddStudents button to the panel
jp.add(removeStudents); // add RemoveStudents button to the panel
jp.add(usernameLbl); // username label
jp.add(passwordLbl); // password label
jp.add(usernameFld); // username input field
jp.add(passwordFld); // password input field
jp.add(logIn); //add log in button to the panel
jp.add(signUp); //add sign up button to the panel
jp.add(headline); // add headline label to the panel
jp.add(new ImagePanel("Img//bg2.jpg")); // add background image to the panel
// adding panel to the frame
frame.add(jp);
validate();
}
public void checkStudents(int n) {
int numberOfStudents = n;
if (numberOfStudents == 0) {
removeStudents.setEnabled(false);
}
}
public void chooseOption() {
viewStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "view students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
editStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "edit students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
addStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "add students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
removeStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "remove students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
logIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "succesful log in", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
signUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "sign up form", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
and here is the class for the image background
package testdnevnik;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
when i run the program from the NetBeans everything is ok,running perfectly,but when i click "Clean and Build Project" in NetBeans and run from the jar file in the folder,the background is white but the components added to the panel are fine,just the image for the background disappearing,why??

Categories