So im tearing my hair out at this, I cannot seem to figure out why these JLabels are not drawing to the window. I keep looking at another project Ive done in the past that also used JLabels inside a JPanel and everything seems right. Does anyone see where I am messing this up?
package lab19_20;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class Lab19_20 extends JFrame implements ActionListener, MouseListener
{
JLabel[] lblBoard = new JLabel[16];
int[] nums = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8};
int firstChoice = -1;
int tries = 0;
JLabel lblFirst;
JButton btnGame = new JButton("New Game");
JLabel lblTries = new JLabel("0");
JPanel pnlControls = new JPanel();
JPanel pnlBoard = new JPanel();
Font lblBoardFont = new Font("Helvetica", Font.BOLD, 30);
Container content = this.getContentPane();
public Lab19_20()
{
setTitle("The Concentration Game");
setVisible(true);
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createLabels();
content.add(pnlBoard, BorderLayout.NORTH);
pnlControls.add(btnGame);
pnlControls.add(lblTries);
content.add(pnlControls, BorderLayout.SOUTH);
btnGame.addActionListener(this);
}
void createLabels()
{
pnlBoard.setLayout(new GridLayout(4, 4, 5, 5));
for(int i = 0; i < lblBoard.length; i++)
{
lblBoard[i] = new JLabel("", JLabel.CENTER);
lblBoard[i].setVisible(true);
lblBoard[i].setOpaque(true);
lblBoard[i].setBackground(Color.BLUE);
lblBoard[i].setForeground(Color.BLACK);
lblBoard[i].setFont(lblBoardFont);
lblBoard[i].addMouseListener(this);
lblBoard[i].setName("" + i);
pnlBoard.add(lblBoard[i]);
}
}
void shuffle()
{
int num1, num2, tmp = 0;
Random r = new Random();
for (int i = 0; i < 500; i++)
{
num1 = r.nextInt(nums.length);
num2 = r.nextInt(nums.length);
tmp = nums[num1];
nums[num1] = nums[num2];
nums[num2] = tmp;
}
}
#Override
public void actionPerformed(ActionEvent ae)
{
shuffle();
firstChoice = -1;
for (int i = 0; i < lblBoard.length; i++)
lblBoard[i].setText("");
tries = 0;
lblTries.setText("" + tries);
}
#Override
public void mouseClicked(MouseEvent me)
{
JLabel l = (JLabel) me.getSource();
int theNumber = Integer.parseInt(l.getName());
if (firstChoice == -1)
{
l.setText("" + nums[theNumber]);
lblFirst = l;
firstChoice = theNumber;
}
else if (nums[theNumber] != nums[firstChoice])
{
l.setText("" + nums[theNumber]);
pnlBoard.paintImmediately(0,0, pnlBoard.getWidth(), pnlBoard.getHeight());
try
{
Thread.sleep(250);
}
catch(InterruptedException blah){}
lblFirst.setText("");
l.setText("");
lblFirst = null;
firstChoice = -1;
tries++;
}
else
{
l.setText("" + nums[theNumber]);
firstChoice = -1;
tries++;
}
lblTries.setText("" + tries);
}
public static void main(String[] args)
{
Lab19_20 console = new Lab19_20();
}
#Override public void mousePressed(MouseEvent me) {}
#Override public void mouseReleased(MouseEvent me) {}
#Override public void mouseEntered(MouseEvent me) {}
#Override public void mouseExited(MouseEvent me) {}
}
Two quick things...
Call setVisible(true); last, after you have established the basic UI.
Use lblBoard[i].setText("" + i); instead of (or as well as) lblBoard[i].setName("" + i);
Related
I am making a Color game in which when I click on start a chain of colors will be shown. Now I have to click on my 4 color buttons and match the shown chain.
If I win, the chain adds a color (Level up) if I lose the chain loses a color (Level down).
My problems right now :
If I overlap the shown colors to match, I will only see the first index of the Array. I need to make it to show all Indexes of the JButton [] like every 2 seconds. I tried it with timer but it still show only the first one.
If I level up, I can add a color to the need to match array, but If I level down, I cant delete the last added color. I know there is no way to remove something from an Array, but is there a workaround. Right now I am making the player lose completely if he doesnt match the scheme.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class Farbgedaechtnisspiel {
private static int startLevel = 1;
private static int gameLevel = 3;
private static List<Integer> gameArray = new ArrayList<>();
private static List<Integer> userArray = new ArrayList<>();
private static int save = 0;
private static int count = 0;
private static JButton [] b;
private static final Color red = new Color(255, 0, 0);
private static final Color green = new Color(0, 255, 0);
private static final Color blue = new Color(0, 0, 255);
private static final Color yellow = new Color(255, 255, 0);
private static JFrame frame = new JFrame("Farbgedächtnisspiel");
private static JLabel levelTxt;
public static void main(String[] args) {
// create mainframe
new Farbgedaechtnisspiel();
}
public Farbgedaechtnisspiel () {
createFrame(frame);
levelTxt = new JLabel("Level: " + startLevel);
frame.add(levelTxt);
levelTxt.setFont(new Font("Times New Roman", Font.ITALIC, 40));
// create 4 color buttons + start/exit
b = new JButton[7];
for(int i = 0;i<b.length;i++){
b[i] = new JButton();
frame.add(b[i]);
}
// create button layout
createButtons();
// button listeners
b[4].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// start Game -> show taskArray
levelTxt.setBounds(550, 200, 200, 200);
startGame(gameLevel);
}});
b[5].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
b[0].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userArray.add(1);
save++;
}
}
);
b[1].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userArray.add(2);
save++;
}
});
b[2].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userArray.add(3);
save++;
}
});
b[3].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userArray.add(4);
save++;
}
});
b[6].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean result = compareArrays(userArray, gameArray);
if (result){
gameLevel++;
save = 0;
startLevel++;
levelTxt.setText("Level: " + startLevel);
} else {
JOptionPane.showMessageDialog(frame, "Sie haben verloren");
new Farbgedaechtnisspiel();
System.exit(1);
}
startGame(gameLevel);
}
});
// make frame visible
frame.setVisible(true);
}
public static void startGame(int gameLevel){
int x = 100;
JButton [] tmp = new JButton[gameLevel];
for(int i = 0;i<tmp.length;i++) {
tmp[i] = new JButton();
tmp[i].setBackground(randomColor());
tmp[i].setOpaque(true);
tmp[i].setBorderPainted(false);
frame.add(tmp[i]);
if (tmp[i].getBackground() == red) {
gameArray.add(1);
} else if (tmp[i].getBackground() == blue) {
gameArray.add(2);
} else if (tmp[i].getBackground() == green) {
gameArray.add(3);
} else if (tmp[i].getBackground() == yellow) {
gameArray.add(4);
}
}
for (int i = 0; i < tmp.length; i++) {
tmp[i].setBounds(x, 50, 100, 100);
x+=100;
}
// for (int i = 0; i < tmp.length; i++) {
// tmp[i].setBounds(450, 50, 300, 299);
// x += 100;
// }
}
public static void createButtons() {
int x = 0;
for (int i = 0; i < b.length; i++) {
b[i].setBounds(x, 0, 200, 200);
x += 200;
}
b[0].setBackground(red);
b[0].setOpaque(true);
b[0].setBorderPainted(false);
b[1].setBackground(blue);
b[1].setOpaque(true);
b[1].setBorderPainted(false);
b[2].setBackground(green);
b[2].setOpaque(true);
b[2].setBorderPainted(false);
b[3].setBackground(yellow);
b[3].setOpaque(true);
b[3].setBorderPainted(false);
b[4].setBounds(150,600,300,200);
b[4].setText("Start");
b[5].setBounds(450, 600, 300, 200);
b[5].setText("Beenden");
b[6].setBounds(750, 600, 300, 200);
b[6].setText("Continue");
b[0].setBounds(200, 400, 200, 200);
b[1].setBounds(400, 400, 200, 200);
b[2].setBounds(600, 400, 200, 200);
b[3].setBounds(800, 400, 200, 200);
}
public static boolean compareArrays(List<Integer> userArray, List<Integer> gameArray){
return userArray.equals(gameArray);
}
public static void createFrame(JFrame frame){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200,800);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setResizable(false);
}
public static Color randomColor () {
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
return switch (randomNum) {
case 1 -> red;
case 2 -> green;
case 3 -> blue;
case 4 -> yellow;
default -> null;
};
}
}```
I have made 3 classes for each level (easy 4*4, medium 6*4, hard 6*6) in a memory game. They consist of the same code, however they have different numbers of the array length and other variables. I want to make the code more efficient by combining the three classes together into only one, do you have any suggestions? If it helps I have pasted the three different classes below :)
Arrays and variables from the 3 different classes:
JButton[] button = new JButton[16];
JButton[] button = new JButton[24];
JButton[] button = new JButton[36];
int[] StoreCards = new int[16];
int[] StoreCards = new int[24];
int[] StoreCards = new int[36];
static int[] card = new int[9];
static int[] card = new int[13];
static int[] card = new int[19];
Easy Level:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
class EasyWindow extends JFrame implements ActionListener, MouseListener {
JLabel Score = new JLabel("Score: - ");
JLabel Welcome = new JLabel("Welcome " + StartWindow.user + "!");
ImageIcon Back = new ImageIcon("mback.png");
ImageIcon musicicon = new ImageIcon("musicicon.png");
ImageIcon themeicon = new ImageIcon("themeicon.png");
ImageIcon difficultyicon = new ImageIcon("difficulty.png");
ImageIcon pointsicon = new ImageIcon("pointsicon.png");
ImageIcon studentsicon = new ImageIcon("studentsicon.png");
JButton AnOtherLevel = new JButton(
"Click here if you want to change level.");
JButton Quit = new JButton("Quit Game!");
JButton[] button = new JButton[16];
JMenuBar menuBar = new JMenuBar();
JMenu Settings = new JMenu("Settings");
JMenu Theme = new JMenu("Theme");
JMenu Rules = new JMenu("Rules");
JMenu Creators = new JMenu("Creators");
JMenuItem Music = new JMenuItem("Music", musicicon);
JMenuItem Celebrities = new JMenuItem("Celebrities", themeicon);
JMenuItem Cities = new JMenuItem("Cities", themeicon);
JMenuItem Memes = new JMenuItem("Memes", themeicon);
JMenuItem Difficulty = new JMenuItem("Difficulty", difficultyicon);
JMenuItem Points = new JMenuItem("Points", pointsicon);
JMenuItem Ava = new JMenuItem("Ava Baghchesara", studentsicon);
JMenuItem Michelle = new JMenuItem("Michelle Bill", studentsicon);
int[] StoreCards = new int[16];
static int[] cardChecker = new int[2];
static int[] card = new int[9];
int[] Button = new int[2];
static int flipped = 0;
static int score = 0;
String imageType = ".png";
String back = ".png";
JPanel Top = new JPanel(new GridLayout(1, 1, 5, 15));
JPanel Center = new JPanel(new GridLayout(4, 4, 5, 5));
JPanel Bottom = new JPanel(new GridLayout(1, 2, 0, 0));
JPanel Right = new JPanel(new GridLayout(2, 2, 0, 0));
JPanel Left = new JPanel(new GridLayout(1, 1, 0, 0));
static Container contentArea;
public EasyWindow() {
super("User: " + StartWindow.user + " || Easy Level");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLayout(new BorderLayout());
setVisible(true);
AnOtherLevel.addActionListener(this);
Quit.addActionListener(this);
AnOtherLevel.addMouseListener(this);
Quit.addMouseListener(this);
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
add(Top, BorderLayout.NORTH);
add(Left, BorderLayout.WEST);
add(Center, BorderLayout.CENTER);
add(Right, BorderLayout.EAST);
add(Bottom, BorderLayout.SOUTH);
Welcome.setFont(new Font("Serif", Font.PLAIN, 30));
Welcome.setHorizontalAlignment(SwingConstants.CENTER);
Welcome.setVerticalAlignment(SwingConstants.CENTER);
Top.add(Welcome);
Top.setBackground(Color.white);
Center.setBackground(Color.white);
Right.setBackground(Color.white);
Right.add(Score);
Bottom.add(AnOtherLevel);
Bottom.add(Quit);
Bottom.setBackground(Color.white);
for (int n = 0; n <= button.length - 1; n++) {
button[n] = new JButton();
Center.add(button[n]);
button[n].addActionListener(this);
button[n].setBackground(Color.white);
}
contentArea = getContentPane();
contentArea.add("North", Top);
contentArea.add("Center", Center);
contentArea.add("South", Bottom);
menuBar.add(Settings);
menuBar.add(Rules);
menuBar.add(Creators);
setJMenuBar(menuBar);
Music.addActionListener(this);
Theme.addActionListener(this);
Celebrities.addActionListener(this);
Cities.addActionListener(this);
Memes.addActionListener(this);
Difficulty.addActionListener(this);
Points.addActionListener(this);
Ava.addActionListener(this);
Michelle.addActionListener(this);
Settings.add(Music);
Settings.add(Theme);
Theme.add(Celebrities);
Theme.add(Cities);
Theme.add(Memes);
Rules.add(Difficulty);
Rules.add(Points);
Creators.add(Ava);
Creators.add(Michelle);
Game();
flipped = 3;
Reset();
setContentPane(contentArea);
contentArea.setBackground(Color.white);
}
public void Game() {
int number = 0;
int x = 0;
ImageIcon image[] = new ImageIcon[15];
while (x < 16) {
number = (int) RandomNumbers.GetRandomNumber(8);
image[number] = new ImageIcon(number + imageType);
if (card[number] < 2) {
card[number]++;
StoreCards[x] = number;
System.out.println(number + " Number" + "card nr " + x);
x++;
}
}
}
public void Reset() {
if (flipped > 2) {
flipped = 0;
for (int n = 0; n <= button.length - 1; n++) {
button[n].setIcon(Back);
}
}
}
public void Check(int number) {
if (cardChecker[0] == cardChecker[1]) {
score = score + 2;
Score.setText("Score: " + score);
DisableButtons();
} else {
System.out.println("jj");
}
if (score == 16) {
setVisible(false);
new EndWindow1();
}
}
public void Card1and2(int number, int button) {
if (flipped == 0) {
cardChecker[0] = number;
Button[0] = button;
}
if (flipped == 1) {
cardChecker[1] = number;
Button[1] = button;
if (StoreCards[cardChecker[0]] == StoreCards[cardChecker[1]]) {
if (Button[0] != Button[1])
Check(number);
}
}
}
public void DisableButtons() {
for (int n = 0; n <= button.length; n++) {
if (Button[0] == n || Button[1] == n) {
button[n].setVisible(false);
}
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == AnOtherLevel) {
setVisible(false);
new AnOtherWindow();
}
if (event.getSource() == Quit) {
System.exit(0);
}
for (int n = 0; n <= button.length - 1; n++) {
if (event.getSource() == button[n]) {
int number = StoreCards[n];
button[n].setIcon(new ImageIcon(number + imageType));
Card1and2(number, n);
flipped++;
Reset();
}
}
if (event.getSource() == Celebrities) {
Back = new ImageIcon("ceback.png");
imageType = "c.png";
}
if (event.getSource() == Cities) {
Back = new ImageIcon("ciback.png");
imageType = ".jpg";
}
if (event.getSource() == Memes) {
Back = new ImageIcon("mback.png");
imageType = ".png";
}
}
public void mouseEntered(MouseEvent event) {
if (event.getSource() == AnOtherLevel) {
AnOtherLevel.setBackground(Color.lightGray);
AnOtherLevel.setForeground(Color.BLACK);
}
if (event.getSource() == Quit) {
Quit.setBackground(Color.lightGray);
Quit.setForeground(Color.BLACK);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
public class EasyLevelWindow {
public static void main(String[] args) {
EasyWindow win = new EasyWindow();
}
Medium Level:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
class MediumWindow extends JFrame implements ActionListener, MouseListener {
JLabel Score = new JLabel("Score: - ");
JLabel Welcome = new JLabel("Welcome " + StartWindow.user + "!");
ImageIcon Back = new ImageIcon("mback.png");
ImageIcon musicicon = new ImageIcon("musicicon.png");
ImageIcon themeicon = new ImageIcon("themeicon.png");
ImageIcon difficultyicon = new ImageIcon("difficulty.png");
ImageIcon pointsicon = new ImageIcon("pointsicon.png");
ImageIcon studentsicon = new ImageIcon("studentsicon.png");
JButton AnOtherLevel = new JButton(
"Click here if you want to change level.");
JButton Quit = new JButton("Quit Game!");
JButton[] button = new JButton[24];
JMenuBar menuBar = new JMenuBar();
JMenu Settings = new JMenu("Settings");
JMenu Theme = new JMenu("Theme");
JMenu Rules = new JMenu("Rules");
JMenu Creators = new JMenu("Creators");
JMenuItem Music = new JMenuItem("Music", musicicon);
JMenuItem Celebrities = new JMenuItem("Celebrities", themeicon);
JMenuItem Cities = new JMenuItem("Cities", themeicon);
JMenuItem Memes = new JMenuItem("Memes", themeicon);
JMenuItem Difficulty = new JMenuItem("Difficulty", difficultyicon);
JMenuItem Points = new JMenuItem("Points", pointsicon);
JMenuItem Ava = new JMenuItem("Ava Baghchesara", studentsicon);
JMenuItem Michelle = new JMenuItem("Michelle Bill", studentsicon);
int[] StoreCards = new int[24];
static int[] cardChecker = new int[2];
static int[] card = new int[13];
int[] Button = new int[2];
static int flipped = 0;
static int score = 0;
String imageType = ".png";
String back = ".png";
JPanel Top = new JPanel(new GridLayout(2, 1, 5, 15));
JPanel Center = new JPanel(new GridLayout(6, 4, 5, 5));
JPanel Bottom = new JPanel(new GridLayout(1, 1, 0, 0));
JPanel Right = new JPanel(new GridLayout(2, 2, 0, 0));
JPanel Left = new JPanel(new GridLayout(1, 1, 0, 0));
static Container contentArea;
public MediumWindow() {
super("User: " + StartWindow.user + " || Medium Level");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLayout(new BorderLayout());
setVisible(true);
AnOtherLevel.addActionListener(this);
Quit.addActionListener(this);
AnOtherLevel.addMouseListener(this);
Quit.addMouseListener(this);
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
add(Top, BorderLayout.NORTH);
add(Left, BorderLayout.WEST);
add(Center, BorderLayout.CENTER);
add(Right, BorderLayout.EAST);
add(Bottom, BorderLayout.SOUTH);
Welcome.setFont(new Font("Serif", Font.PLAIN, 30));
Welcome.setHorizontalAlignment(SwingConstants.CENTER);
Welcome.setVerticalAlignment(SwingConstants.CENTER);
Top.add(Welcome);
Top.setBackground(Color.white);
Center.setBackground(Color.white);
Right.setBackground(Color.white);
Right.add(Score);
Bottom.add(AnOtherLevel);
Bottom.add(Quit);
Bottom.setBackground(Color.white);
for (int n = 0; n <= button.length - 1; n++) {
button[n] = new JButton();
Center.add(button[n]);
button[n].addActionListener(this);
button[n].setBackground(Color.white);
}
contentArea = getContentPane();
contentArea.add("North", Top);
contentArea.add("Center", Center);
contentArea.add("South", Bottom);
menuBar.add(Settings);
menuBar.add(Rules);
menuBar.add(Creators);
setJMenuBar(menuBar);
Music.addActionListener(this);
Theme.addActionListener(this);
Celebrities.addActionListener(this);
Cities.addActionListener(this);
Memes.addActionListener(this);
Difficulty.addActionListener(this);
Points.addActionListener(this);
Ava.addActionListener(this);
Michelle.addActionListener(this);
Settings.add(Music);
Settings.add(Theme);
Theme.add(Celebrities);
Theme.add(Cities);
Theme.add(Memes);
Rules.add(Difficulty);
Rules.add(Points);
Creators.add(Ava);
Creators.add(Michelle);
Game();
flipped = 3;
Reset();
setContentPane(contentArea);
contentArea.setBackground(Color.white);
}
public void Game() {
int number = 0;
int x = 0;
ImageIcon image[] = new ImageIcon[23];
while (x < 24) {
number = (int) RandomNumbers.GetRandomNumber(12);
image[number] = new ImageIcon(number + imageType);
if (card[number] < 2) {
card[number]++;
StoreCards[x] = number;
System.out.println(number + " Number" + "card nr " + x);
x++;
}
}
}
public void Reset() {
if (flipped > 2) {
flipped = 0;
for (int n = 0; n <= button.length - 1; n++) {
button[n].setIcon(Back);
}
}
}
public void Check(int number) {
if (cardChecker[0] == cardChecker[1]) {
score = score + 2;
Score.setText("Score: " + score);
DisableButtons();
} else {
System.out.println("jj");
}
if (score == 24) {
setVisible(false);
new EndWindow1();
}
}
public void Card1and2(int number, int button) {
if (flipped == 0) {
cardChecker[0] = number;
Button[0] = button;
}
if (flipped == 1) {
cardChecker[1] = number;
Button[1] = button;
if (StoreCards[cardChecker[0]] == StoreCards[cardChecker[1]]) {
if (Button[0] != Button[1])
Check(number);
}
}
}
public void DisableButtons() {
for (int n = 0; n <= button.length; n++) {
if (Button[0] == n || Button[1] == n) {
button[n].setVisible(false);
}
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == AnOtherLevel) {
setVisible(false);
new AnOtherWindow();
}
if (event.getSource() == Quit) {
System.exit(0);
}
for (int n = 0; n <= button.length - 1; n++) {
if (event.getSource() == button[n]) {
int number = StoreCards[n];
button[n].setIcon(new ImageIcon(number + imageType));
Card1and2(number, n);
flipped++;
Reset();
}
}
if (event.getSource() == Celebrities) {
Back = new ImageIcon("ceback.png");
imageType = "c.png";
}
if (event.getSource() == Cities) {
Back = new ImageIcon("ciback.png");
imageType = ".jpg";
}
if (event.getSource() == Memes) {
Back = new ImageIcon("mback.png");
imageType = ".png";
}
}
public void mouseEntered(MouseEvent event) {
if (event.getSource() == AnOtherLevel) {
AnOtherLevel.setBackground(Color.lightGray);
AnOtherLevel.setForeground(Color.BLACK);
}
if (event.getSource() == Quit) {
Quit.setBackground(Color.lightGray);
Quit.setForeground(Color.BLACK);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
public class MediumLevelWindow {
public static void main(String[] args) {
MediumWindow win = new MediumWindow();
}
}
Hard Level:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
class HardWindow extends JFrame implements ActionListener, MouseListener {
JLabel Score = new JLabel("Score: - ");
JLabel Welcome = new JLabel("Welcome " + StartWindow.user + "!");
ImageIcon Back = new ImageIcon("mback.png");
ImageIcon musicicon = new ImageIcon("musicicon.png");
ImageIcon themeicon = new ImageIcon("themeicon.png");
ImageIcon difficultyicon = new ImageIcon("difficulty.png");
ImageIcon pointsicon = new ImageIcon("pointsicon.png");
ImageIcon studentsicon = new ImageIcon("studentsicon.png");
JButton AnOtherLevel = new JButton(
"Click here if you want to change level.");
JButton Quit = new JButton("Quit Game!");
JButton[] button = new JButton[36];
JMenuBar menuBar = new JMenuBar();
JMenu Settings = new JMenu("Settings");
JMenu Theme = new JMenu("Theme");
JMenu Rules = new JMenu("Rules");
JMenu Creators = new JMenu("Creators");
JMenuItem Music = new JMenuItem("Music", musicicon);
JMenuItem Celebrities = new JMenuItem("Celebrities", themeicon);
JMenuItem Cities = new JMenuItem("Cities", themeicon);
JMenuItem Memes = new JMenuItem("Memes", themeicon);
JMenuItem Difficulty = new JMenuItem("Difficulty", difficultyicon);
JMenuItem Points = new JMenuItem("Points", pointsicon);
JMenuItem Ava = new JMenuItem("Ava Baghchesara", studentsicon);
JMenuItem Michelle = new JMenuItem("Michelle Bill", studentsicon);
int[] StoreCards = new int[36];
static int[] cardChecker = new int[2];
static int[] card = new int[19];
int[] Button = new int[2];
static int flipped = 0;
static int score = 0;
String imageType = ".png";
String back = ".png";
JPanel Top = new JPanel(new GridLayout(2, 1, 5, 15));
JPanel Center = new JPanel(new GridLayout(6, 6, 5, 5));
JPanel Bottom = new JPanel(new GridLayout(1, 1, 0, 0));
JPanel Right = new JPanel(new GridLayout(2, 2, 0, 0));
JPanel Left = new JPanel(new GridLayout(1, 1, 0, 0));
static Container contentArea;
public HardWindow() {
super("User: " + StartWindow.user + " || Hard Level");
setSize(780, 730);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLayout(new BorderLayout());
setVisible(true);
AnOtherLevel.addActionListener(this);
Quit.addActionListener(this);
AnOtherLevel.addMouseListener(this);
Quit.addMouseListener(this);
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
add(Top, BorderLayout.NORTH);
add(Left, BorderLayout.WEST);
add(Center, BorderLayout.CENTER);
add(Right, BorderLayout.EAST);
add(Bottom, BorderLayout.SOUTH);
Welcome.setFont(new Font("Serif", Font.PLAIN, 30));
Welcome.setHorizontalAlignment(SwingConstants.CENTER);
Welcome.setVerticalAlignment(SwingConstants.CENTER);
Top.add(Welcome);
Top.setBackground(Color.white);
Center.setBackground(Color.white);
Right.setBackground(Color.white);
Right.add(Score);
Bottom.add(AnOtherLevel);
Bottom.add(Quit);
Bottom.setBackground(Color.white);
for (int n = 0; n <= button.length - 1; n++) {
button[n] = new JButton();
Center.add(button[n]);
button[n].addActionListener(this);
button[n].setBackground(Color.white);
}
contentArea = getContentPane();
contentArea.add("North", Top);
contentArea.add("Center", Center);
contentArea.add("South", Bottom);
menuBar.add(Settings);
menuBar.add(Rules);
menuBar.add(Creators);
setJMenuBar(menuBar);
Music.addActionListener(this);
Theme.addActionListener(this);
Celebrities.addActionListener(this);
Cities.addActionListener(this);
Memes.addActionListener(this);
Difficulty.addActionListener(this);
Points.addActionListener(this);
Ava.addActionListener(this);
Michelle.addActionListener(this);
Settings.add(Music);
Settings.add(Theme);
Theme.add(Celebrities);
Theme.add(Cities);
Theme.add(Memes);
Rules.add(Difficulty);
Rules.add(Points);
Creators.add(Ava);
Creators.add(Michelle);
Game();
flipped = 3;
Reset();
setContentPane(contentArea);
contentArea.setBackground(Color.white);
}
public void Game() {
int number = 0;
int x = 0;
ImageIcon image[] = new ImageIcon[35];
while (x < 36) {
number = (int) RandomNumbers.GetRandomNumber(18);
image[number] = new ImageIcon(number + imageType);
if (card[number] < 2) {
card[number]++;
StoreCards[x] = number;
System.out.println(number + " Number" + "card nr " + x);
x++;
}
}
}
public void Reset() {
if (flipped > 2) {
flipped = 0;
for (int n = 0; n <= button.length - 1; n++) {
button[n].setIcon(Back);
}
}
}
public void Check(int number) {
if (cardChecker[0] == cardChecker[1]) {
score = score + 2;
Score.setText("Score: " + score);
DisableButtons();
} else {
System.out.println("jj");
}
if (score == 36) {
setVisible(false);
new EndWindow1();
}
}
public void Card1and2(int number, int button) {
if (flipped == 0) {
cardChecker[0] = number;
Button[0] = button;
}
if (flipped == 1) {
cardChecker[1] = number;
Button[1] = button;
if (StoreCards[cardChecker[0]] == StoreCards[cardChecker[1]]) {
if (Button[0] != Button[1])
Check(number);
}
}
}
public void DisableButtons() {
for (int n = 0; n <= button.length; n++) {
if (Button[0] == n || Button[1] == n) {
button[n].setVisible(false);
}
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == AnOtherLevel) {
setVisible(false);
new AnOtherWindow();
}
if (event.getSource() == Quit) {
System.exit(0);
}
for (int n = 0; n <= button.length - 1; n++) {
if (event.getSource() == button[n]) {
int number = StoreCards[n];
button[n].setIcon(new ImageIcon(number + imageType));
Card1and2(number, n);
flipped++;
Reset();
}
}
if (event.getSource() == Celebrities) {
Back = new ImageIcon("ceback.png");
imageType = "c.png";
}
if (event.getSource() == Cities) {
Back = new ImageIcon("ciback.png");
imageType = ".jpg";
}
if (event.getSource() == Memes) {
Back = new ImageIcon("mback.png");
imageType = ".png";
}
}
public void mouseEntered(MouseEvent event) {
if (event.getSource() == AnOtherLevel) {
AnOtherLevel.setBackground(Color.lightGray);
AnOtherLevel.setForeground(Color.BLACK);
}
if (event.getSource() == Quit) {
Quit.setBackground(Color.lightGray);
Quit.setForeground(Color.BLACK);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
public class HardLevelWindow {
public static void main(String[] args) {
HardWindow win = new HardWindow();
}
}
You can create a Parent class e.g.: BaseGame which is abstract. Like that:
public abstract class BaseGame {
private abstract int[] getStoreCards();
private abstract JButton[] getButtons();
private abstract int[] getCards();
... your other code goes here
}
And then you can create your child classes where you implement these methods, e.g:
public class EasyGame {
#Override
private int[] getStoreCards() {
return new int[16];
}
#Override
private int[] getCards() {
return new int[9];
}
#Override
private JButton[] getButtons() {
return new JButton[16];
}
}
So everywhere in your code where you usually initalize your arrays, use those methods instead.
int[] Button = new int[2];
becomes
getButtons();
You probably want to use an ArrayList, like so:
ArrayList<JButton> buttons = new ArrayList<>();
//...
for (int n = 0; n < boardSize; n++) {
JButton button = new JButton();
buttons.add(button); // add to the end of the expandable list
Center.add(button);
button.addActionListener(this);
button.setBackground(Color.white);
}
where boardSize is a parameter to your constructor specifying the size.
Please some one can told me why I don't have the JTextField in the same line with my JComboBox ?
I need to have like that:
myJComboBox1 JTextField1
JTextField2
myJComboBox2 JTextField1
JTextField2
following this example
public class DisplayPanel extends JFrame {
private JComboBox[] box;
JTextField[] field1, field2;
public DisplayPanel(){
super(BorderLayoutTest.class.getName());
setTitle("Simulation");
setSize(1000,500);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
initComponents();
}
private void createComponents(){
box = new JComboBox[3];
field1 = new JTextField[4];
field2 = new JTextField[5];
}
private void initComponents(){
setLayout(new GridLayout(0, 2));
for(int i = 0; i < 3; i++) {
JPanel panel = new JPanel(new BorderLayout());
box[i] =new JComboBox<>(new String[] { "field1", "field2"});
panel.add(box[i], BorderLayout.NORTH);
add(panel);
add(createPanelWithTextFields(panel));
box[i].setSelectedIndex(-1);
box[i].addActionListener(new CustomActionListener(box[i]));
}
}
private Component createPanelWithTextFields(JPanel panel) {
//need to keep the same layout as JComboBox
panel.setLayout(new GridLayout(0, 1));
for(int x=0; x<4; x++){
field1[x] = new JTextField("field1 Name " + (x+1));
field1[x].setVisible(false);
panel.add(field1[x]);
}
for(int x=0; x<5; x++){
field2[x] = new JTextField("field2 Name " + (x+1));
field2[x].setVisible(false);
panel.add(field2[x]);
}
return panel;
}
class CustomActionListener implements ActionListener {
JComboBox b;
public CustomActionListener(JComboBox u) {
super();
this.b = u;
}
public void actionPerformed(ActionEvent e) {
int numChosen = b.getSelectedIndex() + 1;
switch (numChosen){
case 1:
for(int x=0; x<4; x++)
field1[x].setVisible(true);
break;
case 2:
for(int x=0; x<5; x++)
field2[x].setVisible(true);
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new DisplayPanel().setVisible(true);
}
});
}
you are assigning new textfield to textfield array.but it contain only 4 textfields.but you call assigning more than 4 times.so what happening is last rextfield references get reassigning and you can't use them again.at the end of the the loop your field array contain reference to textfields of last panel.and that's why your see textfields on last panel even you select from combobox1.
how to fix ?
change this
field1 = new JTextField[4];
to this
field1 = new JTextField[4 * 3];
and then you don't need to reassign jtextfields .you have 3 panels and you have 4 textfields for each panel.
same for field2
here is an example .
public class DisplayPanel extends JFrame {
private JComboBox[] box;
JTextField[] field1, field2;
Color col[] = {Color.red, Color.GREEN, Color.blue};
int i = 0;
int counter = 0;
private int boxcount;
int field1counter = 0;
int field2counter = 0;
public DisplayPanel() {
//super(BorderLayoutTest.class.getName());
setTitle("Simulation");
setSize(1000, 500);
//setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
initComponents();
}
private void createComponents() {
boxcount = 3;
box = new JComboBox[1 * boxcount];
field1 = new JTextField[4 * boxcount];
field2 = new JTextField[5 * boxcount];
}
private void initComponents() {
setLayout(new GridLayout(0, 2));
for (int i = 0; i < 3; i++) {
JPanel panel = new JPanel(new BorderLayout());
box[i] = new JComboBox<>(new String[]{"field1", "field2"});
panel.add(box[i], BorderLayout.NORTH);
add(panel);
add(createPanelWithTextFields(panel));
box[i].setSelectedIndex(-1);
box[i].addActionListener(new CustomActionListener());
}
}
private Component createPanelWithTextFields(JPanel panelc) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBackground(col[i]);
System.out.println("......................");
for (int x = 0; x < 4; x++) {
System.out.println("iterating .." + (field1counter) + " counter " + counter);
field1[field1counter] = new JTextField("field1 Name " + (x + 1));
field1[field1counter].setVisible(false);
panel.add(field1[field1counter]);
field1counter++;
}
for (int x = 0; x < 5; x++) {
field2[field2counter] = new JTextField("field2 Name " + (x + 1));
field2[field2counter].setVisible(false);
panel.add(field2[field2counter]);
field2counter++;
}
i++;
counter++;
return panel;
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox b = (JComboBox) e.getSource();
int comboidenty = 0;
for (int k = 0; k < box.length; k++) {
if (box[k] == b) {
break;
}
comboidenty++;
}
System.out.println(((JPanel) (b.getParent())).getBackground());
int numChosen = b.getSelectedIndex() + 1;
System.out.println("hi " + comboidenty);
switch (numChosen) {
case 1:
for (int x = 0; x < 4; x++) {
System.out.println("field1 " + (comboidenty * 4 + x));
field1[comboidenty * 4 + x].setVisible(true);
}
break;
case 2:
for (int x = 0; x < 5; x++) {
System.out.println("field2 " + (comboidenty * 5 + x));
field2[comboidenty * 5 + x].setVisible(true);
}
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DisplayPanel().setVisible(true);
}
});
}
}
The first image shows what the GUI looks like when I just start it, the second shows what happens when I click around the board. The chess pieces show up at the top row after I click a piece and then click on a button on the top row. What is happening here?!
The code is below; this class is where I have most of my code. The rest of the classes are just loading images at this point. The Board constructor is called in the main to build the GUI.
public class BoardPanel extends JPanel {
public BoardPanel() {
createBoard();
}
private void createBoard(){
setLayout(new GridLayout(10, 10));
// Makes a 10 x 10 grid of black and white colors
for (int i = 0; i<10; i++){
for (int j = 0; j<10; j++){
square[i][j] = new JButton();
square[i][j].setRolloverEnabled(false);
if ((i+j)%2 == 0)
square[i][j].setBackground(Color.WHITE);
else
square[i][j].setBackground(Color.LIGHT_GRAY);
add(square[i][j]);
}
}
addLabels();
//Colors the corner squares
square[0][0].setBackground(new Color(155, 234, 242, 100));
square[0][9].setBackground(new Color(155, 234, 242, 100));
square[9][0].setBackground(new Color(155, 234, 242, 100));
square[9][9].setBackground(new Color(155, 234, 242, 100));
}
private void addLabels(){
//Adds labels to the ranks
for (int i =1 ; i< 9; i++){
square[i][0].setBackground(new Color(155, 234, 242, 100));
square[i][0].setText(rank[8-i]);
square[i][0].setHorizontalTextPosition(SwingConstants.RIGHT);
square[i][9].setBackground(new Color(155, 234, 242, 100));
square[i][9].setText(rank[8-i]);
square[i][9].setHorizontalTextPosition(SwingConstants.LEFT);
}
//Adds labels to the files
for (int j = 1; j<9;j++){
square[0][j].setBackground(new Color(155, 234, 242, 100));
square[0][j].setText(file[j-1]);
square[0][j].setVerticalTextPosition(SwingConstants.BOTTOM);
square[9][j].setBackground(new Color(155, 234, 242, 100));
square[9][j].setText(file[j-1]);
square[9][j].setVerticalTextPosition(SwingConstants.TOP);
}
JButton square[][] = new JButton[10][10];
String[] rank = {"1","2","3","4","5","6","7","8"};
String[] file = {"a","b","c","d","e","f","g","h"};
}
}
The main class
public class Board {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new BoardPanel());
frame.setVisible(true);
frame.setSize(900, 700);
}
}
Your problem is with the button thinking that it is fully opaque when it is in fact not opaque. As per Kleopatra in this answer, you must make the button non-opaque and take over the painting mechanisms
square[i][j] = new JButton() {
#Override // !! add this:
protected void paintComponent(Graphics g) {
if (!isOpaque() && getBackground().getAlpha() < 255) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g);
}
};
square[i][j].setRolloverEnabled(false);
square[i][j].setOpaque(false); // !! and also add this *******
As a side note, I wouldn't be using JButtons for this type of problem, but rather I'd be using JPanels, and would place my chess pieces as ImageIcons displayed in JLabels, labels that are added to or removed from the appropriate chess-board squares.
A board without buttons and without use of alpha colors:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class Board2 extends JPanel {
private static final int SIDE_LEN = 80;
private static final Dimension SQUARE_SZ = new Dimension(SIDE_LEN, SIDE_LEN);
private static final Color EDGE_COLOR = new Color(165, 245, 250);
private static final Color DARK_SQR_COLOR = Color.LIGHT_GRAY;
private static final Color LIGHT_SQR_COLOR = Color.WHITE;
private JPanel[][] chessSquares = new JPanel[8][8];
public Board2() {
setLayout(new GridLayout(10, 10)); // sorry for magic numbers
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if ((i == 0 || i == 9) && (j == 0 || j == 9)) {
add(createEdgePanel(""));
} else if (i == 0 || i == 9) {
String text = String.valueOf((char) (j + 'a' - 1));
add(createEdgePanel(text));
} else if (j == 0 || j == 9) {
String text = String.valueOf(8 - i + 1);
add(createEdgePanel(text));
} else {
JPanel panel = createSquare(i, j);
add(panel);
}
}
}
}
private JPanel createSquare(int i, int j) {
JPanel panel = new JPanel(new GridBagLayout());
Color c = (i % 2 == j % 2) ? LIGHT_SQR_COLOR : DARK_SQR_COLOR;
panel.setBackground(c);
panel.setPreferredSize(SQUARE_SZ);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private JPanel createEdgePanel(String text) {
JLabel label = new JLabel(text, SwingConstants.CENTER);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setBackground(EDGE_COLOR);
panel.setPreferredSize(SQUARE_SZ);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private static void createAndShowGui() {
Board2 mainPanel = new Board2();
JFrame frame = new JFrame("Board2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which on my system looks like:
Now with some pieces added:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class Board2 extends JPanel {
private static final int SIDE_LEN = 80;
private static final Dimension SQUARE_SZ = new Dimension(SIDE_LEN, SIDE_LEN);
private static final String SPRITE_PATH = "http://i.stack.imgur.com/memI0.png";
private static final int SPRITE_ROWS = 2;
private static final int SPRITE_COLS = 6;
private static final Color EDGE_COLOR = new Color(165, 245, 250);
private static final Color DARK_SQR_COLOR = Color.LIGHT_GRAY;
private static final Color LIGHT_SQR_COLOR = Color.WHITE;
private static final int ROWS = 8;
private JLabel[][] chessSquares = new JLabel[ROWS][ROWS];
private BufferedImage bigImage;
private List<Icon> icons = new ArrayList<>();
public Board2() throws IOException {
URL imgUrl = new URL(SPRITE_PATH);
bigImage = ImageIO.read(imgUrl);
int w = bigImage.getWidth() / SPRITE_COLS;
int h = bigImage.getHeight() / SPRITE_ROWS;
for (int i = 0; i < SPRITE_ROWS; i++) {
for (int j = 0; j < SPRITE_COLS; j++) {
int x = (j * bigImage.getWidth()) / SPRITE_COLS;
int y = (i * bigImage.getHeight()) / SPRITE_ROWS;
BufferedImage spriteImg = bigImage.getSubimage(x, y, w, h);
Icon spriteIcon = new ImageIcon(spriteImg);
icons.add(spriteIcon);
}
}
for (int i = 0; i < chessSquares.length; i++) {
for (int j = 0; j < chessSquares[i].length; j++) {
chessSquares[i][j] = new JLabel();
}
}
setLayout(new GridLayout(ROWS + 2, ROWS + 2)); // sorry for magic numbers
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if ((i == 0 || i == ROWS + 1) && (j == 0 || j == ROWS + 1)) {
add(createEdgePanel(""));
} else if (i == 0 || i == ROWS + 1) {
String text = String.valueOf((char) (j + 'a' - 1));
add(createEdgePanel(text));
} else if (j == 0 || j == ROWS + 1) {
String text = String.valueOf(ROWS - i + 1);
add(createEdgePanel(text));
} else {
JPanel panel = createSquare(i, j);
panel.add(chessSquares[i - 1][j - 1]);
add(panel);
}
}
}
setPieces(0, 0, 2); // rooks
setPieces(1, 0, 3); // knights
setPieces(2, 0, 4); // bishops
// kings and queens
chessSquares[0][3].setIcon(icons.get(1));
chessSquares[7][3].setIcon(icons.get(6 + 1));
chessSquares[0][4].setIcon(icons.get(0));
chessSquares[7][4].setIcon(icons.get(6 + 0));
// pawns
for (int i = 0; i < ROWS / 2; i++) {
setPieces(i, 1, 5);
}
}
private void setPieces(int colPos, int rowPos, int pieceIndex) {
chessSquares[rowPos][colPos].setIcon(icons.get(pieceIndex));
chessSquares[rowPos][ROWS - 1 - colPos].setIcon(icons.get(pieceIndex));
chessSquares[ROWS - 1 - rowPos][colPos].setIcon(icons.get(6 + pieceIndex));
chessSquares[ROWS - 1 - rowPos][ROWS - 1 - colPos].setIcon(icons
.get(6 + pieceIndex));
}
private void setPiece(int colPos, int pieceIndex) {
chessSquares[0][colPos].setIcon(icons.get(pieceIndex));
chessSquares[ROWS - 1][ROWS - 1 - colPos].setIcon(icons.get(6 + pieceIndex));
}
private JPanel createSquare(int i, int j) {
JPanel panel = new JPanel(new GridBagLayout());
Color c = (i % 2 == j % 2) ? LIGHT_SQR_COLOR : DARK_SQR_COLOR;
panel.setBackground(c);
panel.setPreferredSize(SQUARE_SZ);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private JPanel createEdgePanel(String text) {
JLabel label = new JLabel(text, SwingConstants.CENTER);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setBackground(EDGE_COLOR);
panel.setPreferredSize(SQUARE_SZ);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private static void createAndShowGui() {
Board2 mainPanel = null;
try {
mainPanel = new Board2();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("Board2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Hey all I am making a flight booking system and having this error when I click a seat for booking "AWT-EventQueue-0" java.lang.NullPointerException I think there is a mistake with my 2D Object initialization...
PS: is there a way I can get rid of the final in front of Seats[][] seats = new Seats[4][5];
Here is my Seats Class:
public class Seats {
private int row_number;
private boolean booked;
private Passenger myPassenger;
private String seat_name;
private String type;
private int column_number;
private long booking_nr;
public Seats(){
myPassenger = new Passenger();
booked = false;
}
public boolean isBooked() {
return booked;
}
public void setBooked(boolean booked) {
this.booked = booked;
}
}
and below is my GUI:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Book_GUI extends JFrame {
//private EconomyClass eco;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Book_GUI frame = new Book_GUI();
frame.setTitle("Economy Class");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Book_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
int left = 3;
int middle = 3;
int right = 4;
String[] singleRowAll = new String [left+middle+right];
for(int i = 1;i<singleRowAll.length;i++){singleRowAll[i] = "";}
singleRowAll[0] = "Window";
singleRowAll[left-1] = "Aisle";
singleRowAll[left] = "Aisle";
singleRowAll[left+middle-1] = "Aisle";
singleRowAll[left+middle] = "Aisle";
singleRowAll[left+middle+right-1] = "Window";
//eco = new EconomyClass(4,5,3,3,4);
final Seats[][] seats = new Seats[4][10];
for ( int i = 0; i < 4; i++) {
char c= 'A';
for ( int j = 0; j < 10; j++) {
final int x = i;
final int z = j;
final JButton btnBookFlight = new JButton(" " + (i+1) + c++ + " " + singleRowAll[j] );
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(seats[x][z].isBooked()){btnBookFlight.setBackground(Color.GREEN);}
seats[x][z].setBooked(true);
//JButton button = (JButton)arg0.getSource();
//button.setBackground(Color.RED);
// btnBookFlight.setBackground(Color.RED);
btnBookFlight.setOpaque(true);
}
});
contentPane.add(btnBookFlight);
}
}
contentPane.setLayout(new GridLayout(4, 10));
pack();
}
}
Thank you for reading and for your time!
You are not initializing the Seats[][] array. Try replacing the Constructor of Book_GUI.java with:
public Seats[][] seats = new Seats[4][10];
public Book_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
int left = 3;
int middle = 3;
int right = 4;
String[] singleRowAll = new String[left + middle + right];
for (int i = 1; i < singleRowAll.length; i++) {
singleRowAll[i] = "";
}
singleRowAll[0] = "Window";
singleRowAll[left - 1] = "Aisle";
singleRowAll[left] = "Aisle";
singleRowAll[left + middle - 1] = "Aisle";
singleRowAll[left + middle] = "Aisle";
singleRowAll[left + middle + right - 1] = "Window";
// eco = new EconomyClass(4,5,3,3,4);
//Delete this line:
//final Seats[][] seats = new Seats[4][5];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 5; j++) {
seats[i][j] = new Seats();
}
}
for (int i = 0; i < 4; i++) {
char c = 'A';
for (int j = 0; j < 10; j++) {
final int x = i;
final int z = j;
final JButton btnBookFlight = new JButton(" " + (i + 1) + c++
+ " " + singleRowAll[j]);
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (seats[x][z].isBooked()) {
btnBookFlight.setBackground(Color.GREEN);
}
seats[x][z].setBooked(true);
// JButton button = (JButton)arg0.getSource();
// button.setBackground(Color.RED);
// btnBookFlight.setBackground(Color.RED);
btnBookFlight.setOpaque(true);
}
});
contentPane.add(btnBookFlight);
}
}
contentPane.setLayout(new GridLayout(4, 10));
pack();
}
This should help :)
You are creating a new seat array, using new Seats[4][5], but that simply makes an empty array of references. you need to actually create a new seat that goes in each place in the array.