Selected variables doesn't change on pong game - Swing - java

I'm trying to make a pong game by using Swing. I have a menu screen where you can change your preferences such as music, game speed and you can choose multiplayer options etc. But when I made a choice, their values don't change. I have my mainmenu class and computer class.
For ex: I want to change the difficulty which means changing the AI's speed but I wasn't be able to do it. I am looking forward for an answer, maybe it's so simple but I can't see it.
This is my code:
public class MenuPanel
{
ScoreBoard sc = new ScoreBoard();
private JFrame mainFrame;
private JFrame optionsFrame;
private JPanel menuPanel;
private JPanel optionsPanel;
private JFrame gameEndFrame;
private JPanel gameEndPanel;
JCheckBox twoPlayer;
// creating the swing components and containers,
// there are two frames to swap between them,
// we tried to use cardLayout but it didn't work for us.
public MenuPanel() {
mainFrame = new JFrame("Welcome To Pong Game");
mainFrame.setSize(700,700);
mainFrame.setLayout(new CardLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuPanel = new JPanel(null);
menuPanel.setSize(700,700);
menuPanel.setVisible(true);
mainFrame.add(menuPanel);
optionsFrame = new JFrame("Settings");
optionsFrame.setSize(700, 700);
optionsFrame.setLayout(new CardLayout());
optionsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel optionsPanel = new JPanel(null) ;
optionsPanel.setSize(700,700);
optionsPanel.setVisible(true);
optionsFrame.add(optionsPanel);
// mainPanel components
ImageIcon ic1 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Actions-player-play-icon.png");
ImageIcon ic2 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Settings-L-icon.png");
ImageIcon ic3 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\cup-icon.png");
ImageIcon ic4 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Button-Close-icon.png");
ImageIcon ic5 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\ice-2025937_960_720.jpg");
ImageIcon ic6 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\tenis1.png");
JLabel mainLabel = new JLabel();
Font font = new Font("Papyrus", Font.BOLD,26);
mainLabel.setFont(font);
mainLabel.setForeground(Color.RED);
mainLabel.setText("PONG GAME");
JButton startButton = new JButton("Start Game");
JButton optionsButton = new JButton("Options");
JButton leaderButton = new JButton("Leaderboard");
JButton exitButton = new JButton("Exit");
JButton icb1 = new JButton(ic1);
JButton icb2 = new JButton(ic2);
JButton icb3 = new JButton(ic3);
JButton icb4 = new JButton(ic4);
JButton icb6 = new JButton(ic6);
// at first, we tried to keep our buttons and labels in panels
// but then we didn't add an image to label as the background
// so we created a JLabel to set its image as the background, we may remove it later.
JLabel mn = new JLabel(ic5);
mn.setBackground(Color.BLUE);
mn.setBounds(1, 1, 700, 700);
Font font3 = new Font("Calibri", Font.PLAIN, 20);
twoPlayer = new JCheckBox();
twoPlayer.setFont(font3);
twoPlayer.setForeground(Color.DARK_GRAY);
twoPlayer.setText(" MultiPlayer");
twoPlayer.setBounds(200, 350, 220, 40);
menuPanel.add(mn);
mn.add(mainLabel);
mn.add(startButton);
mn.add(optionsButton);
mn.add(leaderButton);
mn.add(exitButton);
mn.add(icb1);
mn.add(icb2);
mn.add(icb3);
mn.add(icb4);
mn.add(icb6);
mn.add(twoPlayer);
mainFrame.setVisible(true);
// the components added by their coordinates to make them look formal
mainLabel.setBounds(210, 100, 220, 40);
startButton.setBounds(200, 150, 220, 40);
optionsButton.setBounds(200, 200, 220, 40);
leaderButton.setBounds(200, 250, 220, 40);
exitButton.setBounds(200, 300, 220, 40);
icb1.setBounds(150, 150, 40, 40);
icb2.setBounds(150, 200, 40, 40);
icb3.setBounds(150, 250, 40, 40);
icb4.setBounds(150, 300, 40, 40);
icb6.setBounds(150,350,40,40);
startButton.setBorder(BorderFactory.createRaisedBevelBorder());
optionsButton.setBorder(BorderFactory.createRaisedBevelBorder());
leaderButton.setBorder(BorderFactory.createRaisedBevelBorder());
exitButton.setBorder(BorderFactory.createRaisedBevelBorder());
// optionsPanel components
JButton doneButton = new JButton("Done");
doneButton.setBounds(150,330,220,40);
doneButton.setBorder(BorderFactory.createRaisedBevelBorder());
Font font1 = new Font("Calibri", Font.PLAIN,24);
Font font2 = new Font("Calibri", Font.BOLD,19);
JLabel st = new JLabel();
st.setFont(font1);
st.setForeground(Color.DARK_GRAY);
st.setText("-OPTIONS-");
JLabel difficulty = new JLabel("Difficulty: ");
difficulty.setFont(font2);
difficulty.setForeground(Color.DARK_GRAY);
JLabel music = new JLabel("Sound: ");
music.setFont(font2);
music.setForeground(Color.DARK_GRAY);
JLabel gSpeed = new JLabel("Game Speed: ");
gSpeed.setFont(font2);
gSpeed.setForeground(Color.DARK_GRAY);
JLabel screen = new JLabel(ic5);
screen.setBackground(Color.BLUE);
screen.setBounds(1, 1, 700, 700);
JRadioButton rb1 = new JRadioButton("Easy");
JRadioButton rb2 = new JRadioButton("Normal");
JRadioButton rb3 = new JRadioButton("Hard");
JRadioButton rb4 = new JRadioButton("On");
JRadioButton rb5 = new JRadioButton("Off");
JRadioButton rb6 = new JRadioButton("x");
JRadioButton rb7 = new JRadioButton("2x");
JRadioButton rb8 = new JRadioButton("3x");
ButtonGroup bg1 = new ButtonGroup();
ButtonGroup bg2 = new ButtonGroup();
ButtonGroup bg3 = new ButtonGroup();
bg1.add(rb1);
bg1.add(rb2);
bg1.add(rb3);
bg2.add(rb4);
bg2.add(rb5);
bg3.add(rb6);
bg3.add(rb7);
bg3.add(rb8);
optionsPanel.add(screen);
screen.add(difficulty);
screen.add(st);
screen.add(gSpeed);
screen.add(rb1);
screen.add(rb2);
screen.add(rb3);
screen.add(rb4);
screen.add(rb5);
screen.add(rb6);
screen.add(rb7);
screen.add(rb8);
screen.add(music);
screen.add(doneButton);
st.setBounds(200,100,220,40);
difficulty.setBounds(100,150,90,40);
music.setBounds(100,200,90,40);
gSpeed.setBounds(100, 250, 120, 40);
rb1.setBounds(200,150,60,40);
rb2.setBounds(260,150,80,40);
rb3.setBounds(340, 150, 60, 40);
rb4.setBounds(200, 200, 50, 40);
rb5.setBounds(250,200,50,40);
rb6.setBounds(220, 250, 50, 40);
rb7.setBounds(270, 250, 50, 40);
rb8.setBounds(320, 250, 50, 40);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Pong pong = new Pong();
sound("Marimba-music");
mainFrame.dispose();
if(twoPlayer.isSelected()) {
pong.c.isTwoPlayer = true;
}
else {
pong.c.isTwoPlayer = false;
}
}
});
optionsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainFrame.setVisible(false);
optionsFrame.setVisible(true);
}
});
doneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsFrame.dispose();
Pong pong = new Pong();
if(rb1.isSelected())
{
pong.c.setUp(-10);;
pong.c.setDown(10);
}
else if(rb2.isSelected())
{
pong.c.setUp(-11);
pong.c.setDown(11);
}
else if(rb3.isSelected())
{
pong.c.setUp(-30);
pong.c.setDown(30);
}
if(rb4.isSelected())
{
sound("Marimba-music");
}
else if(rb5.isSelected())
{
soundStop("Marimba-music");
}
if(rb6.isSelected())
{
GamePanel g = new GamePanel();
g.x = 50;
}
else if(rb7.isSelected())
{
GamePanel g = new GamePanel();
g.x = 75;
}
else if(rb8.isSelected())
{
GamePanel g = new GamePanel();
g.x = 100;
System.out.println(g.x);
}
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
mainFrame.dispose();
}
});
}
public void sound(String nm)
{
AudioStream BGM;
try {
InputStream test = new FileInputStream("./" +nm+".wav");
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
}
catch(IOException error) {
JOptionPane.showMessageDialog(null, error.getMessage());
}
}
public void soundStop(String nm)
{
AudioStream BGM;
try {
InputStream test = new FileInputStream("./" +nm+".wav");
BGM = new AudioStream(test);
AudioPlayer.player.stop(BGM);
}
catch(IOException error) {
JOptionPane.showMessageDialog(null, error.getMessage());
}
}
}
My Computer.class:
public class Computer
{
private GamePanel field;
private int y = Pong.WINDOW_HEIGHT / 2;
private int yCh = 0;
private int up = -10;
private int down = 10;
private int width = 20;
private int height = 90;
boolean isTwoPlayer = false;
public Computer() {
}
public void update(Ball b) {
if(y + height > Pong.WINDOW_HEIGHT)
{
y = Pong.WINDOW_HEIGHT - height;
}
else if(y < 0)
{
y = 0;
}
if(!isTwoPlayer) {
if(b.getY() < y+height && y >= 0)
{
yCh = up;
}
else if(b.getY() > y && y + height <= Pong.WINDOW_HEIGHT)
{
yCh = down;
}
y = y + yCh;
}
else {
y = y + yCh;
}
}
public void setYPosition(int speed) {
yCh = speed;
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRoundRect(450, y, width, height, 10, 10);
}
public int getX() {
return 450;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getUp() {
return up;
}
public int getDown() {
return down;
}
public void setUp(int up) {
this.up = up;
}
public void setDown(int down) {
this.down = down;
}

I don't know how your whole program is structured. But in this piece of code:
doneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsFrame.dispose();
Pong pong = new Pong();
You create a new instance of Pong class and set the values of the new created instance.
This instance is not used anywhere else. You may need to use a instance of Pong that is already in use, or make other classes use the new created instance.

Related

Show an Array of JButtons one after another with a timer [JAVA SWING]

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;
};
}
}```

Transform my Java Swing program to an MVC program?

I was given the task to come up with a small game in Swing and implement it as an MVC (Model View Control) program. I'm new to MVC. So far I've finished the whole program in 1 Java file (View), what code do I need to change and insert in the Model file, in order for it to become MVC?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
public class MemoryGameView extends JFrame {
private JPanel gamePanel, settingsPanel, scorePanel;
private JButton[] button = new JButton[16];
private JButton start;
private JPanel buttonPanel, buttonPanel2;
private JPanel difficultyPanel, difficultyPanel2;
private JLabel difficultyLabel;
private ButtonGroup difficultyButtonGroup;
private JRadioButton[] difficultyButton = new JRadioButton[4];
private int difficulty = 0;
private JComboBox guiColorChanger;
private String[] guiColor = new String[2];
private JPanel guiColorChangerPanel;
private JLabel guiColorChangerLabel;
private JPanel currentScorePanel, currentScorePanel2, highScorePanel, highScorePanel2;
private JLabel currentScoreLabel, currentScoreLabel2, highScoreLabel, highScoreLabel2;
private int currentScore;
private int highScore = 0;
private int[] arrayAuto;
private int[] arrayUser;
private int counter;
private Timer timer;
private Color babyBlue = new Color(137, 156, 240);
private Color brightRed = new Color(255, 69, 0);
private Color limeGreen = new Color(50, 205, 50);
private Color whiteBlue = new Color(240, 240, 255);
private Color blackBlue = new Color(0, 0, 15);
public MemoryGameView() {
super();
init();
}
public void init() {
setTitle("Memory Game - by Marc");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1200, 500);
setLocationRelativeTo(null);
setLayout(new GridLayout(1, 3));
settingsPanel = new JPanel(new BorderLayout());
gamePanel = new JPanel(new GridBagLayout());
scorePanel = new JPanel(new BorderLayout());
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
add(settingsPanel);
add(gamePanel);
add(scorePanel);
//GAME PANEL (CENTER) -----------------------------------------------------------------------------------------------------
//GAME GRID PANEL:
buttonPanel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int x = 0; x < 16; x++) {
button[x] = new JButton();
button[x].setBackground(babyBlue);
button[x].setEnabled(false);
button[x].addActionListener(new AttemptMemoryGame());
button[x].setActionCommand(x + "");
buttonPanel.add(button[x]);
}
buttonPanel2 = new JPanel();
buttonPanel2.setBackground(Color.WHITE);
buttonPanel2.setPreferredSize(new Dimension(320, 320));
buttonPanel.setPreferredSize(new Dimension(312, 312));
buttonPanel2.add(buttonPanel);
GridBagConstraints buttonGBC = new GridBagConstraints();
buttonGBC.gridy = 0;
buttonGBC.insets = new Insets(10, 10, 0, 10);
gamePanel.add(buttonPanel2, buttonGBC);
//START BUTTON:
start = new JButton("START");
start.setBackground(Color.ORANGE);
start.setPreferredSize(new Dimension(200, 40));
GridBagConstraints startGBC = new GridBagConstraints();
startGBC.gridy = 1;
startGBC.insets.top = 20;
startGBC.insets.bottom = 20;
gamePanel.add(start, startGBC);
start.addActionListener(new CreateMemoryGame());
timer = new Timer(750, new TimerListener());
//SETTINGS PANEL (LEFT) ----------------------------------------------------------------------------------------------
//GUI COLOR PANEL:
guiColor[0] = "Light";
guiColor[1] = "Dark";
guiColorChangerPanel = new JPanel(new GridBagLayout());
guiColorChangerPanel.setBackground(whiteBlue);
settingsPanel.add(guiColorChangerPanel, BorderLayout.NORTH);
guiColorChanger = new JComboBox(guiColor);
guiColorChanger.setBackground(Color.WHITE);
guiColorChanger.setPreferredSize(new Dimension(200, 30));
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints guiColorChangerGBC = new GridBagConstraints();
guiColorChangerGBC.gridy = 1;
guiColorChangerGBC.insets = new Insets(0, 20, 0, 50);
guiColorChangerGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChanger, guiColorChangerGBC);
guiColorChangerLabel = new JLabel("GUI Color Mode:");
GridBagConstraints guiColorChangerLabelGBC = new GridBagConstraints();
guiColorChangerLabelGBC.gridy = 0;
guiColorChangerLabelGBC.insets = new Insets(30, 20, 5, 0);
guiColorChangerLabelGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChangerLabel, guiColorChangerLabelGBC);
guiColorChanger.addActionListener(new ChangeColorsGUI());
guiColorChanger.setFocusable(false);
//GAME DIFFICULTY PANEL:
difficultyPanel2 = new JPanel(new GridBagLayout());
difficultyPanel2.setBackground(whiteBlue);
settingsPanel.add(difficultyPanel2, BorderLayout.SOUTH);
difficultyLabel = new JLabel("Difficulty:");
GridBagConstraints difficultyLabelGBC = new GridBagConstraints();
difficultyLabelGBC.gridy = 0;
difficultyLabelGBC.insets = new Insets(30, 0, 5, 50);
difficultyLabelGBC.anchor = GridBagConstraints.WEST;
difficultyPanel2.add(difficultyLabel, difficultyLabelGBC);
difficultyPanel = new JPanel(new GridBagLayout());
difficultyPanel.setBackground(Color.WHITE);
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints difficultyPanelGBC = new GridBagConstraints();
difficultyPanelGBC.gridy = 1;
difficultyPanelGBC.insets = new Insets(0, 0, 75, 100);
difficultyPanel2.add(difficultyPanel, difficultyPanelGBC);
GridBagConstraints difficultyGBC = new GridBagConstraints();
difficultyGBC.insets = new Insets(5, 5, 5, 5);
difficultyGBC.anchor = GridBagConstraints.WEST;
difficultyButton[0] = new JRadioButton("Easy [3]");
difficultyButton[1] = new JRadioButton("Normal [5]");
difficultyButton[2] = new JRadioButton("Hard [7]");
difficultyButton[3] = new JRadioButton("Impossible [9]");
difficultyButtonGroup = new ButtonGroup();
for (int x = 0; x < 4; x++) {
difficultyButton[x].setBackground(Color.WHITE);
difficultyButton[x].setActionCommand(x + "");
difficultyGBC.gridy = x;
difficultyPanel.add(difficultyButton[x], difficultyGBC);
difficultyButtonGroup.add(difficultyButton[x]);
difficultyButton[x].addActionListener(new SelectDifficulty());
}
//SCORE PANEL (RIGHT) --------------------------------------------------------------------------------------------------------
//CURRENT SCORE:
currentScorePanel2 = new JPanel(new GridBagLayout());
currentScorePanel2.setBackground(whiteBlue);
scorePanel.add(currentScorePanel2, BorderLayout.NORTH);
currentScoreLabel2 = new JLabel("Score: ");
GridBagConstraints currentScoreLabelGBC = new GridBagConstraints();
currentScoreLabelGBC.gridx = 0;
currentScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
currentScoreLabelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScoreLabel2, currentScoreLabelGBC);
currentScorePanel = new JPanel(new GridBagLayout());
currentScorePanel.setBackground(Color.WHITE);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints currentScorePanelGBC = new GridBagConstraints();
currentScorePanelGBC.insets = new Insets(100, 0, 100, 100);
currentScorePanelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScorePanel, currentScorePanelGBC);
currentScoreLabel = new JLabel(" ");
currentScoreLabelGBC.gridx = 1;
currentScorePanel.add(currentScoreLabel, currentScoreLabelGBC);
//HIGHSCORE:
highScorePanel2 = new JPanel(new GridBagLayout());
highScorePanel2.setBackground(whiteBlue);
scorePanel.add(highScorePanel2, BorderLayout.SOUTH);
highScoreLabel2 = new JLabel("Highscore: ");
GridBagConstraints highScoreLabelGBC = new GridBagConstraints();
highScoreLabelGBC.gridx = 0;
highScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
highScoreLabelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScoreLabel2, highScoreLabelGBC);
highScorePanel = new JPanel(new GridBagLayout());
highScorePanel.setBackground(Color.WHITE);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints highScorePanelGBC = new GridBagConstraints();
highScorePanelGBC.insets = new Insets(100, 0, 100, 100);
highScorePanelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScorePanel, highScorePanelGBC);
highScoreLabel = new JLabel(" ");
highScoreLabelGBC.gridx = 1;
highScorePanel.add(highScoreLabel, highScoreLabelGBC);
pack();
setVisible(true);
}
public class CreateMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (difficulty != 0) {
counter = 0;
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(false);
}
for (JButton b: button) {
b.setBackground(babyBlue);
b.setEnabled(false);
}
start.setEnabled(false);
arrayAuto = new int[difficulty];
arrayAuto[0] = (int)(Math.random() * 16);
for (int x = 1; x < difficulty; x++) {
arrayAuto[x] = (int)(Math.random() * 16);
while (arrayAuto[x] == arrayAuto[x - 1]) {
arrayAuto[x] = (int)(Math.random() * 16);
}
}
arrayUser = Arrays.copyOf(arrayAuto, arrayAuto.length);
button[arrayAuto[0]].setBackground(limeGreen);
timer.start();
} else {
Object[] options = {"OK"};
JOptionPane.showOptionDialog(null, "Please select a Difficulty.", "ERROR", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
}
}
}
public class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
button[arrayAuto[0]].setBackground(babyBlue);
arrayAuto = Arrays.copyOfRange(arrayAuto, 1, arrayAuto.length);
if (arrayAuto.length == 0) {
timer.stop();
for (JButton b: button) {
b.setEnabled(true);
}
} else {
button[arrayAuto[0]].setBackground(limeGreen);
}
}
}
public class AttemptMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (Integer.parseInt(ae.getActionCommand()) == arrayUser[counter]) {
if (counter != 0) {
button[arrayUser[counter - 1]].setBackground(babyBlue);
}
button[arrayUser[counter]].setBackground(limeGreen);
counter++;
currentScore += difficulty;
currentScoreLabel.setText(" " + currentScore + " ");
} else {
if (currentScore > highScore) {
highScore = currentScore;
highScoreLabel.setText(" " + highScore + " ");
}
currentScore = 0;
currentScoreLabel.setText(" ");
for (int x = 0; x < difficulty; x++) {
button[arrayUser[x]].setBackground(brightRed);
}
start.setEnabled(true);
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
for (JButton b: button) {
b.setEnabled(false);
}
}
if (counter == arrayUser.length) {
start.setEnabled(true);
for (int x = 0; x < counter - 1; x++) {
button[arrayUser[x]].setBackground(limeGreen);
}
for (JButton b: button) {
b.setEnabled(false);
}
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
}
}
}
public class SelectDifficulty implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(0 + "")) {
difficulty = 3;
} else if (ae.getActionCommand().equals(2 + "")) {
difficulty = 7;
} else if (ae.getActionCommand().equals(3 + "")) {
difficulty = 9;
} else {
difficulty = 5;
}
}
}
public class ChangeColorsGUI implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (guiColorChanger.getSelectedItem() == guiColor[0]) {
guiColorChanger.setBackground(Color.WHITE);
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
buttonPanel.setBackground(Color.WHITE);
guiColorChangerPanel.setBackground(whiteBlue);
buttonPanel2.setBackground(Color.WHITE);
guiColorChanger.setForeground(Color.BLACK);
guiColorChangerLabel.setForeground(Color.BLACK);
difficultyPanel.setBackground(Color.WHITE);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.WHITE);
rb.setForeground(Color.BLACK);
}
difficultyLabel.setBackground(whiteBlue);
difficultyLabel.setForeground(Color.BLACK);
difficultyPanel2.setBackground(whiteBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
scorePanel.setBackground(whiteBlue);
currentScoreLabel.setBackground(Color.WHITE);
currentScoreLabel.setForeground(Color.BLACK);
currentScoreLabel2.setForeground(Color.BLACK);
currentScorePanel.setBackground(whiteBlue);
currentScorePanel2.setBackground(whiteBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
highScoreLabel.setBackground(Color.WHITE);
highScoreLabel.setForeground(Color.BLACK);
highScoreLabel2.setForeground(Color.BLACK);
highScorePanel.setBackground(whiteBlue);
highScorePanel2.setBackground(whiteBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
} else {
guiColorChanger.setBackground(Color.BLACK);
settingsPanel.setBackground(blackBlue);
gamePanel.setBackground(Color.BLACK);
scorePanel.setBackground(blackBlue);
buttonPanel.setBackground(Color.BLACK);
guiColorChangerPanel.setBackground(blackBlue);
buttonPanel2.setBackground(Color.BLACK);
guiColorChanger.setForeground(Color.WHITE);
guiColorChangerLabel.setForeground(Color.WHITE);
difficultyPanel.setBackground(Color.BLACK);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.BLACK);
rb.setForeground(Color.WHITE);
}
difficultyLabel.setBackground(blackBlue);
difficultyLabel.setForeground(Color.WHITE);
difficultyPanel2.setBackground(blackBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.WHITE));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
scorePanel.setBackground(blackBlue);
currentScoreLabel.setBackground(Color.BLACK);
currentScoreLabel.setForeground(Color.WHITE);
currentScoreLabel2.setForeground(Color.WHITE);
currentScorePanel.setBackground(blackBlue);
currentScorePanel2.setBackground(blackBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
highScoreLabel.setBackground(Color.BLACK);
highScoreLabel.setForeground(Color.WHITE);
highScoreLabel2.setForeground(Color.WHITE);
highScorePanel.setBackground(blackBlue);
highScorePanel2.setBackground(blackBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
}
}
}
public static void main(String[] args) {
new MemoryGameView();
}
}
I really appreciate any help! (#camickr? :D)
Edit: I only need to do the files Model and View, no Controller needed.
Here is something to get you started. Define a a Model class that holds the information and logic the View needs.
In this simple demo I implemented a model that has only one attribute the View needs namely difficulty :
class Model{
private int difficulty = 0; //why not set a default value ?
Model(){
}
int getDifficulty() {
return difficulty;
}
void setDifficulty(int difficulty) {
this.difficulty = difficulty;
}
}
Now introduce a View class which is almost identical to MemoryGameView with one important difference: it has an instance of Model and uses it.
(Another difference is a design preference and not a must: unlike MemoryGameView it has a JFrame and it does not extend one.):
class View {
private JPanel gamePanel, settingsPanel, scorePanel;
private final JButton[] button = new JButton[16];
private JButton start;
private JPanel buttonPanel, buttonPanel2;
private JPanel difficultyPanel, difficultyPanel2;
private JLabel difficultyLabel;
private ButtonGroup difficultyButtonGroup;
private final JRadioButton[] difficultyButton = new JRadioButton[4];
private JComboBox guiColorChanger;
private final String[] guiColor = new String[2];
private JPanel guiColorChangerPanel;
private JLabel guiColorChangerLabel;
private JPanel currentScorePanel, currentScorePanel2, highScorePanel, highScorePanel2;
private JLabel currentScoreLabel, currentScoreLabel2, highScoreLabel, highScoreLabel2;
private int currentScore;
private int highScore = 0;
private int[] arrayAuto,arrayUser;
private int counter;
private Timer timer;
private final Color babyBlue = new Color(137, 156, 240);
private final Color brightRed = new Color(255, 69, 0);
private final Color limeGreen = new Color(50, 205, 50);
private final Color whiteBlue = new Color(240, 240, 255);
private final Color blackBlue = new Color(0, 0, 15);
private final Model model;
public View(Model model) {
this.model = model;
init();
}
public void init() {
JFrame frame = new JFrame("Memory Game - by Marc");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200, 500);
frame.setLocationRelativeTo(null);
frame.setLayout(new GridLayout(1, 3));
settingsPanel = new JPanel(new BorderLayout());
gamePanel = new JPanel(new GridBagLayout());
scorePanel = new JPanel(new BorderLayout());
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
frame.add(settingsPanel);
frame.add(gamePanel);
frame.add(scorePanel);
//GAME PANEL (CENTER) -----------------------------------------------------------------------------------------------------
//GAME GRID PANEL:
buttonPanel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int x = 0; x < 16; x++) {
button[x] = new JButton();
button[x].setBackground(babyBlue);
button[x].setEnabled(false);
button[x].addActionListener(new AttemptMemoryGame());
button[x].setActionCommand(x + "");
buttonPanel.add(button[x]);
}
buttonPanel2 = new JPanel();
buttonPanel2.setBackground(Color.WHITE);
buttonPanel2.setPreferredSize(new Dimension(320, 320));
buttonPanel.setPreferredSize(new Dimension(312, 312));
buttonPanel2.add(buttonPanel);
GridBagConstraints buttonGBC = new GridBagConstraints();
buttonGBC.gridy = 0;
buttonGBC.insets = new Insets(10, 10, 0, 10);
gamePanel.add(buttonPanel2, buttonGBC);
//START BUTTON:
start = new JButton("START");
start.setBackground(Color.ORANGE);
start.setPreferredSize(new Dimension(200, 40));
GridBagConstraints startGBC = new GridBagConstraints();
startGBC.gridy = 1;
startGBC.insets.top = 20;
startGBC.insets.bottom = 20;
gamePanel.add(start, startGBC);
start.addActionListener(new CreateMemoryGame());
timer = new Timer(750, new TimerListener());
//SETTINGS PANEL (LEFT) ----------------------------------------------------------------------------------------------
//GUI COLOR PANEL:
guiColor[0] = "Light";
guiColor[1] = "Dark";
guiColorChangerPanel = new JPanel(new GridBagLayout());
guiColorChangerPanel.setBackground(whiteBlue);
settingsPanel.add(guiColorChangerPanel, BorderLayout.NORTH);
guiColorChanger = new JComboBox(guiColor);
guiColorChanger.setBackground(Color.WHITE);
guiColorChanger.setPreferredSize(new Dimension(200, 30));
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints guiColorChangerGBC = new GridBagConstraints();
guiColorChangerGBC.gridy = 1;
guiColorChangerGBC.insets = new Insets(0, 20, 0, 50);
guiColorChangerGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChanger, guiColorChangerGBC);
guiColorChangerLabel = new JLabel("GUI Color Mode:");
GridBagConstraints guiColorChangerLabelGBC = new GridBagConstraints();
guiColorChangerLabelGBC.gridy = 0;
guiColorChangerLabelGBC.insets = new Insets(30, 20, 5, 0);
guiColorChangerLabelGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChangerLabel, guiColorChangerLabelGBC);
guiColorChanger.addActionListener(new ChangeColorsGUI());
guiColorChanger.setFocusable(false);
//GAME DIFFICULTY PANEL:
difficultyPanel2 = new JPanel(new GridBagLayout());
difficultyPanel2.setBackground(whiteBlue);
settingsPanel.add(difficultyPanel2, BorderLayout.SOUTH);
difficultyLabel = new JLabel("Difficulty:");
GridBagConstraints difficultyLabelGBC = new GridBagConstraints();
difficultyLabelGBC.gridy = 0;
difficultyLabelGBC.insets = new Insets(30, 0, 5, 50);
difficultyLabelGBC.anchor = GridBagConstraints.WEST;
difficultyPanel2.add(difficultyLabel, difficultyLabelGBC);
difficultyPanel = new JPanel(new GridBagLayout());
difficultyPanel.setBackground(Color.WHITE);
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints difficultyPanelGBC = new GridBagConstraints();
difficultyPanelGBC.gridy = 1;
difficultyPanelGBC.insets = new Insets(0, 0, 75, 100);
difficultyPanel2.add(difficultyPanel, difficultyPanelGBC);
GridBagConstraints difficultyGBC = new GridBagConstraints();
difficultyGBC.insets = new Insets(5, 5, 5, 5);
difficultyGBC.anchor = GridBagConstraints.WEST;
difficultyButton[0] = new JRadioButton("Easy [3]");
difficultyButton[1] = new JRadioButton("Normal [5]");
difficultyButton[2] = new JRadioButton("Hard [7]");
difficultyButton[3] = new JRadioButton("Impossible [9]");
difficultyButtonGroup = new ButtonGroup();
for (int x = 0; x < 4; x++) {
difficultyButton[x].setBackground(Color.WHITE);
difficultyButton[x].setActionCommand(x + "");
difficultyGBC.gridy = x;
difficultyPanel.add(difficultyButton[x], difficultyGBC);
difficultyButtonGroup.add(difficultyButton[x]);
difficultyButton[x].addActionListener(new SelectDifficulty());
}
//SCORE PANEL (RIGHT) --------------------------------------------------------------------------------------------------------
//CURRENT SCORE:
currentScorePanel2 = new JPanel(new GridBagLayout());
currentScorePanel2.setBackground(whiteBlue);
scorePanel.add(currentScorePanel2, BorderLayout.NORTH);
currentScoreLabel2 = new JLabel("Score: ");
GridBagConstraints currentScoreLabelGBC = new GridBagConstraints();
currentScoreLabelGBC.gridx = 0;
currentScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
currentScoreLabelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScoreLabel2, currentScoreLabelGBC);
currentScorePanel = new JPanel(new GridBagLayout());
currentScorePanel.setBackground(Color.WHITE);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints currentScorePanelGBC = new GridBagConstraints();
currentScorePanelGBC.insets = new Insets(100, 0, 100, 100);
currentScorePanelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScorePanel, currentScorePanelGBC);
currentScoreLabel = new JLabel(" ");
currentScoreLabelGBC.gridx = 1;
currentScorePanel.add(currentScoreLabel, currentScoreLabelGBC);
//HIGHSCORE:
highScorePanel2 = new JPanel(new GridBagLayout());
highScorePanel2.setBackground(whiteBlue);
scorePanel.add(highScorePanel2, BorderLayout.SOUTH);
highScoreLabel2 = new JLabel("Highscore: ");
GridBagConstraints highScoreLabelGBC = new GridBagConstraints();
highScoreLabelGBC.gridx = 0;
highScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
highScoreLabelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScoreLabel2, highScoreLabelGBC);
highScorePanel = new JPanel(new GridBagLayout());
highScorePanel.setBackground(Color.WHITE);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints highScorePanelGBC = new GridBagConstraints();
highScorePanelGBC.insets = new Insets(100, 0, 100, 100);
highScorePanelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScorePanel, highScorePanelGBC);
highScoreLabel = new JLabel(" ");
highScoreLabelGBC.gridx = 1;
highScorePanel.add(highScoreLabel, highScoreLabelGBC);
frame.pack();
frame.setVisible(true);
}
public class CreateMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (model.getDifficulty() != 0) {
counter = 0;
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(false);
}
for (JButton b: button) {
b.setBackground(babyBlue);
b.setEnabled(false);
}
start.setEnabled(false);
arrayAuto = new int[model.getDifficulty()];
arrayAuto[0] = (int)(Math.random() * 16);
for (int x = 1; x < model.getDifficulty(); x++) {
arrayAuto[x] = (int)(Math.random() * 16);
while (arrayAuto[x] == arrayAuto[x - 1]) {
arrayAuto[x] = (int)(Math.random() * 16);
}
}
arrayUser = Arrays.copyOf(arrayAuto, arrayAuto.length);
button[arrayAuto[0]].setBackground(limeGreen);
timer.start();
} else {
Object[] options = {"OK"};
JOptionPane.showOptionDialog(null, "Please select a Difficulty.", "ERROR", JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
}
}
}
public class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
button[arrayAuto[0]].setBackground(babyBlue);
arrayAuto = Arrays.copyOfRange(arrayAuto, 1, arrayAuto.length);
if (arrayAuto.length == 0) {
timer.stop();
for (JButton b: button) {
b.setEnabled(true);
}
} else {
button[arrayAuto[0]].setBackground(limeGreen);
}
}
}
public class AttemptMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (Integer.parseInt(ae.getActionCommand()) == arrayUser[counter]) {
if (counter != 0) {
button[arrayUser[counter - 1]].setBackground(babyBlue);
}
button[arrayUser[counter]].setBackground(limeGreen);
counter++;
currentScore += model.getDifficulty();
currentScoreLabel.setText(" " + currentScore + " ");
} else {
if (currentScore > highScore) {
highScore = currentScore;
highScoreLabel.setText(" " + highScore + " ");
}
currentScore = 0;
currentScoreLabel.setText(" ");
for (int x = 0; x < model.getDifficulty(); x++) {
button[arrayUser[x]].setBackground(brightRed);
}
start.setEnabled(true);
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
for (JButton b: button) {
b.setEnabled(false);
}
}
if (counter == arrayUser.length) {
start.setEnabled(true);
for (int x = 0; x < counter - 1; x++) {
button[arrayUser[x]].setBackground(limeGreen);
}
for (JButton b: button) {
b.setEnabled(false);
}
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
}
}
}
public class SelectDifficulty implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(0 + "")) {
model.setDifficulty(3);
} else if (ae.getActionCommand().equals(2 + "")) {
model.setDifficulty(7);
} else if (ae.getActionCommand().equals(3 + "")) {
model.setDifficulty(9);
} else {
model.setDifficulty(5);
}
}
}
public class ChangeColorsGUI implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (guiColorChanger.getSelectedItem() == guiColor[0]) {
guiColorChanger.setBackground(Color.WHITE);
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
buttonPanel.setBackground(Color.WHITE);
guiColorChangerPanel.setBackground(whiteBlue);
buttonPanel2.setBackground(Color.WHITE);
guiColorChanger.setForeground(Color.BLACK);
guiColorChangerLabel.setForeground(Color.BLACK);
difficultyPanel.setBackground(Color.WHITE);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.WHITE);
rb.setForeground(Color.BLACK);
}
difficultyLabel.setBackground(whiteBlue);
difficultyLabel.setForeground(Color.BLACK);
difficultyPanel2.setBackground(whiteBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
scorePanel.setBackground(whiteBlue);
currentScoreLabel.setBackground(Color.WHITE);
currentScoreLabel.setForeground(Color.BLACK);
currentScoreLabel2.setForeground(Color.BLACK);
currentScorePanel.setBackground(whiteBlue);
currentScorePanel2.setBackground(whiteBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
highScoreLabel.setBackground(Color.WHITE);
highScoreLabel.setForeground(Color.BLACK);
highScoreLabel2.setForeground(Color.BLACK);
highScorePanel.setBackground(whiteBlue);
highScorePanel2.setBackground(whiteBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
} else {
guiColorChanger.setBackground(Color.BLACK);
settingsPanel.setBackground(blackBlue);
gamePanel.setBackground(Color.BLACK);
scorePanel.setBackground(blackBlue);
buttonPanel.setBackground(Color.BLACK);
guiColorChangerPanel.setBackground(blackBlue);
buttonPanel2.setBackground(Color.BLACK);
guiColorChanger.setForeground(Color.WHITE);
guiColorChangerLabel.setForeground(Color.WHITE);
difficultyPanel.setBackground(Color.BLACK);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.BLACK);
rb.setForeground(Color.WHITE);
}
difficultyLabel.setBackground(blackBlue);
difficultyLabel.setForeground(Color.WHITE);
difficultyPanel2.setBackground(blackBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.WHITE));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
scorePanel.setBackground(blackBlue);
currentScoreLabel.setBackground(Color.BLACK);
currentScoreLabel.setForeground(Color.WHITE);
currentScoreLabel2.setForeground(Color.WHITE);
currentScorePanel.setBackground(blackBlue);
currentScorePanel2.setBackground(blackBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
highScoreLabel.setBackground(Color.BLACK);
highScoreLabel.setForeground(Color.WHITE);
highScoreLabel2.setForeground(Color.WHITE);
highScorePanel.setBackground(blackBlue);
highScorePanel2.setBackground(blackBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
}
}
}
}
MemoryGameView becomes the controller, and it is as simple as:
public class MemoryGameView{
public MemoryGameView() {
Model model = new Model();
View view = new View(model);
}
public static void main(String[] args) {
new MemoryGameView();
}
}
Follow this link for a complete working prototype.
To continue: refactor more attributes (data and logic) from View to Model.
You may need to add listener so View can listen to changes in Model.
Side note: if indeed no Controller needed you can simply eliminate MemoryGameView and refactor its functionality to a main method:
public static void main(String[] args) {
Model model = new Model();
View view = new View(model);
}
but I wouldn't recommend it.
The following members might go into the model class:
difficulty
currentScore
highScore
arrayAuto
arrayUser
counter
Effectively the "pure" information.
The view should contain only ui code, i.e. Swing-Code. Since the game loop (timer) might be regarded as business code it would probably be a good idea to move it to the controller.
I did a quick google about swing and mvc: You might try to use existing frameworks like this for mvc.

adding and removing panels when rectangles intersect

I'm making a game and when the user is in one of the game map panels he should enter the game once the character rectangle intersects with the game button rectangle on the map. The user navigates the character using the arrow keys.
I have the following code in the keyPressed method for one of the map panels (its the same for the rest) and the button (game1) reacts to the intersection as it should but the add and remove statements aren't adding or removing the respective panels:
Rectangle rb1 = character.getBounds();
Rectangle rb2 = game1.getBounds();
if (rb1.intersects(rb2)){
game1.setText("Int");
game1.setBackground(Color.red);
remove(sp);
add(g1, "Center");
validate();
repaint();
}
Initially I thought putting that block in the keyPressed method was what's causing the issue but when i moved it, the game1 button stopped reacting entirely. Any help is welcomed and appreciated :)
Here is the code in that panel:
public class SportsPanel extends javax.swing.JPanel implements KeyListener {
JButton homeButton2;
JButton game1;
JButton game2;
JButton game3;
JButton game4;
JButton game5;
SportsPanel sp;
JLabel character;
CharacterMenu cm;
ControlPanel cp;
game1 g1;
game2 g2;
game3 g3;
game4 g4;
game5 g5;
JTextField scoreField;
int c =1;
int x = 100;
int y = 100;
public SportsPanel() {
cm = new CharacterMenu();
g1 = new game1();
g2 = new game2();
g3 = new game3();
g4 = new game4();
g5 = new game5();
setLayout(null);
setBackground(Color.white);
homeButton2 = new JButton("Back to Main Menu");
add(homeButton2);
homeButton2.setBounds(10, 629, 150, 40);
character = new JLabel("");
character.setBounds(x, y, 100, 100);
add(character);
game1 = new JButton("Game 1");
add(game1);
game1.setBounds(200,200, 100, 20);
game2 = new JButton("Game 2");
add(game2);
game2.setBounds(340, 20, 100, 20);
game3 = new JButton("Game 3");
add(game3);
game3.setBounds(120,458, 100, 20);
game4 = new JButton("Game 4");
add(game4);
game4.setBounds(458,269, 100, 20);
game5 = new JButton("Game 5");
add(game5);
game5.setBounds(2, 500, 100, 20);
setFocusable(true);
addKeyListener(this);
scoreField = new JTextField(" Time elapsed: ");
scoreField.setBounds(10, 10, 150, 50);
add(scoreField);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
requestFocusInWindow();
Image myImage = Toolkit.getDefaultToolkit().getImage("images/sports.png");
g.drawImage(myImage, 0, 0, 925, 699, this);
if(c == 1){
ImageIcon lion1 = new ImageIcon("images/lion.png");
ImageIcon newSize = new ImageIcon(((lion1).getImage()).getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH));
character.setText("");
character.setIcon(newSize);
}
if(c == 2){
ImageIcon franklin1 = new ImageIcon("images/franklin.png");
ImageIcon newSize = new ImageIcon(((franklin1).getImage()).getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH));
character.setText("");
character.setIcon(newSize);
}
if(c == 3){
ImageIcon saquon1 = new ImageIcon("images/saquon.png");
ImageIcon newSize = new ImageIcon(((saquon1).getImage()).getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH));
character.setText("");
character.setIcon(newSize);
}
}
#Override
public void keyTyped(KeyEvent evt) {
}
#Override
public void keyPressed(KeyEvent evt) {
System.out.println("Key pressed");
int kk = evt.getKeyCode();
if (kk == evt.VK_LEFT)
{
x = x - 5;;
}
if (kk == evt.VK_RIGHT)
{
x = x + 5;
}
if (kk == evt.VK_UP)
{
y = y - 5;
}
if (kk == evt.VK_DOWN)
{
y = y + 5;
}
character.setBounds(new Rectangle(x, y, 100, 100));
Rectangle rb1 = character.getBounds();
Rectangle rb2 = game1.getBounds();
if (rb1.intersects(rb2)){
game1.setText("Int");
game1.setBackground(Color.red);
remove(sp);
add(g1, "Center");
validate();
repaint();
}
}
#Override
public void keyReleased(KeyEvent evt) {
}
}

Giving mulitple Jbuttons the same actionListener

I have written a 2x2x2 rubiks cube solver and I want to make the experience for the user entering their cube better, currently they enter numbers which are assigned to colors of the cube. For example 0 could represent white, 1 could represent yellow etc. I have been working on a GUI that is a 2d cube made of buttons that when they are clicked change loop over an array of colors. This is what I have so far but I can't get the actionListener to apply to all the buttons.
public static void main(String[] args) {
final int WINDOW_HEIGHT = 500;
final int WINDOW_WIDTH = 700;
//create a window
window.setTitle("First Window");
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setResizable(false);
allButtons();
}
private static void allButtons(){
panel.setLayout(null);
window.add(panel);
final JButton button[]=new JButton[23];
for(int i=0;i<button.length;i++){
button[i] = new JButton();
}
panel.add(button[0]);
button[0].setBounds(30, 30, 60, 60);
final Color[] ColorArray = {Color.WHITE, Color.ORANGE,Color.GREEN,Color.RED,Color.BLUE,Color.YELLOW};
button[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
final int stickerNum = 24;
if(stickerNum <= 3){
for(Color i : ColorArray){
button[0].setBackground(i);
cube[Side][0] = 0;
}
}
}
});
}
Just assign the ActionListener instance to a variable and add that to JButtons in a loop.
public static void main(String[] args) {
final int WINDOW_HEIGHT = 500;
final int WINDOW_WIDTH = 700;
//create a window
window.setTitle("First Window");
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setResizable(false);
allButtons();
}
private static void allButtons(){
panel.setLayout(null);
window.add(panel);
final JButton button[]=new JButton[23];
for(int i=0;i<button.length;i++){
button[i] = new JButton();
}
panel.add(button[0]);
button[0].setBounds(30, 30, 60, 60);
final Color[] ColorArray = {Color.WHITE, Color.ORANGE,Color.GREEN,Color.RED,Color.BLUE,Color.YELLOW};
ActionListener actionListener = new ActionListener(){
public void actionPerformed(ActionEvent e){
final int stickerNum = 24;
if(stickerNum <= 3){
for(Color i : ColorArray){
button[0].setBackground(i);
cube[Side][0] = 0;
}
}
}
};
for(int i=0;i<button.length;i++){
button[i].addActionListener( actionListener);
}
}
You can just create an ButtonListener class like below which stores an index. Then you just add a new instance of the listener to every button.
public static void main(String[] args) {
final int WINDOW_HEIGHT = 500;
final int WINDOW_WIDTH = 700;
//create a window
window.setTitle("First Window");
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setResizable(false);
allButtons();
}
private static void allButtons() {
panel.setLayout(null);
window.add(panel);
final JButton button[]=new JButton[23];
for(int i=0;i<button.length;i++){
button[i] = new JButton();
}
panel.add(button[0]);
button[0].setBounds(30, 30, 60, 60);
final Color[] ColorArray = {Color.WHITE, Color.ORANGE,Color.GREEN,Color.RED,Color.BLUE,Color.YELLOW};
class ButtonListener implements ActionListener {
private int buttonIndex;
public ButtonListener(int buttonIndex) {
this.buttonIndex = buttonIndex;
}
#Override
public void actionPerformed(ActionEvent e) {
final int stickerNum = 24;
if(stickerNum <= 3){
for(Color i : ColorArray){
button[buttonIndex].setBackground(i);
cube[Side][0] = 0;
}
}
}
}
for(int i = 0; i < button.length; i++) {
button[i].addActionListener(new ButtonListener(i));
}
}

BufferedImage for captured chess pieces does not display on my JPanel

Please am developing a chess game using Java. I am having problems trying to display captured chess pieces, this pieces are held in a bufferedImage. when i run and print the variable of the bufferedImage it isn't null and doesn't display the image on the JPanel.
In addition my list of captured chess piece stored in a "List capturedPiece" and is working fine, also the paths to the images are correct. The only problem is that the image stored on the bufferedImage doesn't displaying.
Here is my code
package chessgame.gui;
public class BrownPlayerPanel extends JPanel {
private Rectangle yellowPawnRect, yellowKnightRect, yellowBishopRect,
yellowRookRect, yellowQueenRect;
private Rectangle brownPawnRect, brownKnightRect, brownBishopRect,
brownRookRect, brownQueenRect;
private List<Piece> capturedPieces;
BufferedImage figurineLayer, counterLayer;
boolean firstPaint = true;
private ImageFactory fact;
BufferedImage piecetest;
public BrownPlayerPanel() {
initComponents();
fact = new ImageFactory();
}
public void setCapturedPieces(List<Piece> piece) {
capturedPieces = piece;
//System.out.println(capturedPieces);
if (counterLayer != null) {
clearBufferedImage(counterLayer);
}
if (figurineLayer != null) {
clearBufferedImage(figurineLayer);
}
updateLayers();
repaint();
}
private void initRects(int width, int height) {
int gridWidth = width / 5;
int gridHeight = height / 2;
yellowPawnRect = new Rectangle(0, 0, gridWidth, gridHeight);
yellowKnightRect = new Rectangle(gridWidth, 0, gridWidth, gridHeight);
yellowBishopRect = new Rectangle(gridWidth * 2, 0, gridWidth, gridHeight);
yellowRookRect = new Rectangle(gridWidth * 3, 0, gridWidth, gridHeight);
yellowQueenRect = new Rectangle(gridWidth * 4, 0, gridWidth, gridHeight);
brownPawnRect = new Rectangle(0, gridHeight, gridWidth, gridHeight);
brownKnightRect = new Rectangle(gridWidth, gridHeight, gridWidth,gridHeight);
brownBishopRect = new Rectangle(gridWidth * 2, gridHeight, gridWidth,gridHeight);
brownRookRect = new Rectangle(gridWidth * 3, gridHeight, gridWidth,gridHeight);
brownQueenRect = new Rectangle(gridWidth * 4, gridHeight, gridWidth,gridHeight);
}
public void clearBufferedImage(BufferedImage image) {
Graphics2D g2d = image.createGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.setColor(new Color(0, 0, 0, 0));
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
g2d.dispose();
}
private void updateLayers() {
int yPC = 0, yNC = 0, yBC = 0, yRC = 0, yQC = 0;
int bPC = 0, bNC = 0, bBC = 0, bRC = 0, bQC = 0;
if (firstPaint) {
int width = this.getWidth();
int height = this.getHeight();
figurineLayer = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
counterLayer = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
capturedPieces = new ArrayList<Piece>();
initRects(width, height);
firstPaint = false;
}
int width = this.getWidth();
int height = this.getHeight();
int gridWidth = width / 5;
for (Piece piece : capturedPieces) {
if (piece.getColor() == Piece.YELLOW_COLOR) {
if (piece.getType() == Piece.TYPE_PAWN) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR, Piece.TYPE_PAWN),yellowPawnRect);
yPC++;
}
if (piece.getType() == Piece.TYPE_KNIGHT) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_KNIGHT),yellowKnightRect);
yNC++;
}
if (piece.getType() == Piece.TYPE_BISHOP) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_BISHOP),yellowBishopRect);
yBC++;
}
if (piece.getType() == Piece.TYPE_ROOK) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR, Piece.TYPE_ROOK), yellowRookRect);
yRC++;
}
if (piece.getType() == Piece.TYPE_QUEEN) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_QUEEN), yellowQueenRect);
yQC++;
}
}
if (piece.getColor() == Piece.BROWN_COLOR) {
if (piece.getType() == Piece.TYPE_PAWN) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_PAWN),brownPawnRect);
System.out.println(getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_PAWN).getWidth());
bPC++;
}
if (piece.getType() == Piece.TYPE_KNIGHT) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_KNIGHT),brownKnightRect);
bNC++;
}
if (piece.getType() == Piece.TYPE_BISHOP) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_BISHOP),brownBishopRect);
bBC++;
}
if (piece.getType() == Piece.TYPE_ROOK) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_ROOK),brownRookRect);
bRC++;
}
if (piece.getType() == Piece.TYPE_QUEEN) {
drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_QUEEN), brownQueenRect);
bQC++;
}
}
}
if (yPC > 1) {
drawCounterIntoLayer(counterLayer, yPC, yellowPawnRect);
}
if (yNC > 1) {
drawCounterIntoLayer(counterLayer, yNC, yellowKnightRect);
}
if (yBC > 1) {
drawCounterIntoLayer(counterLayer, yBC, yellowBishopRect);
}
if (yRC > 1) {
drawCounterIntoLayer(counterLayer, yRC, yellowRookRect);
}
if (yQC > 1) {
drawCounterIntoLayer(counterLayer, yQC, yellowQueenRect);
}
if (bPC > 1) {
drawCounterIntoLayer(counterLayer, bPC, brownPawnRect);
}
if (bNC > 1) {
drawCounterIntoLayer(counterLayer, bNC, brownKnightRect);
}
if (bBC > 1) {
drawCounterIntoLayer(counterLayer, bBC, brownBishopRect);
}
if (bRC > 1) {
drawCounterIntoLayer(counterLayer, bRC, brownRookRect);
}
if (bQC > 1) {
drawCounterIntoLayer(counterLayer, bQC, brownQueenRect);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(figurineLayer, 10,10, this);
g2d.drawImage(counterLayer, null, this);
}
private void drawCounterIntoLayer(BufferedImage canvas, int count,Rectangle whereToDraw) {
Graphics2D g2d = canvas.createGraphics();
g2d.setFont(new Font("Arial", Font.BOLD, 12));
g2d.setColor(Color.black);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
FontMetrics textMetrics = g2d.getFontMetrics();
String countString = Integer.toString(count);
int xCoord = whereToDraw.x + whereToDraw.width - textMetrics.stringWidth(countString);
int yCoord = whereToDraw.y + whereToDraw.height;
g2d.drawString(countString, xCoord, yCoord);
g2d.dispose();
}
private void drawImageIntoLayer(BufferedImage canvas, BufferedImage item,Rectangle r) {
Graphics2D g2d = canvas.createGraphics();
g2d.drawImage(item, r.x, r.y, r.width, r.height, this);
g2d.dispose();
}
private void initComponents() {
setName("Form");
setBounds(0, 0, 250, 146);
setBorder(new LineBorder(new Color(139, 69, 19)));
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGap(0, 698, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGap(0, 448, Short.MAX_VALUE)
);
setLayout(groupLayout);
setBackground(Color.black);
}
private BufferedImage getFigurineImage(int color, int type) {
BufferedImage ImageToDraw = null;
try {
String filename = "";
filename += (color == Piece.YELLOW_COLOR ? "Yellow" : "Brown");
switch (type) {
case Piece.TYPE_BISHOP:
filename += "b";
break;
case Piece.TYPE_KING:
filename += "k";
break;
case Piece.TYPE_KNIGHT:
filename += "n";
break;
case Piece.TYPE_PAWN:
filename += "p";
break;
case Piece.TYPE_QUEEN:
filename += "q";
break;
case Piece.TYPE_ROOK:
filename += "r";
break;
}
filename += ".png";
URL urlPiece = getClass().getResource("/chessgame/res/" + filename);
ImageToDraw = ImageIO.read(urlPiece);
} catch (IOException io) {
}
return ImageToDraw;
}
}
ChessWindow Class:
public class ChessWindow extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private BoardGUI boardgui;
private Game game;
JPanel panel_1;
public JLabel lblNewLabel;
private XmlRpcServer server;
private static final int PLAYER_OPTION_SWING = 1;
private static final int PLAYER_OPTION_AI = 2;
private static final int PLAYER_OPTION_NETWORK = 3;
String gameIdOnServer, gamePassword;
public ChessWindow(int yellowPlayerOption, int brownPlayerOption,Game game, String gameIdOnServer, String gamePassword) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 776, 583);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNewGame = new JMenuItem("New Game");
mnFile.add(mntmNewGame);
JSeparator separator = new JSeparator();
mnFile.add(separator);
JSeparator separator_1 = new JSeparator();
mnFile.add(separator_1);
JSeparator separator_2 = new JSeparator();
mnFile.add(separator_2);
JMenuItem mntmAccount = new JMenuItem("Account");
mnFile.add(mntmAccount);
JSeparator separator_10 = new JSeparator();
mnFile.add(separator_10);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
JMenu mnTactics = new JMenu("Tactics");
menuBar.add(mnTactics);
JMenuItem mntmTactics = new JMenuItem("Tactics 1");
mnTactics.add(mntmTactics);
JMenuItem mntmTactics_1 = new JMenuItem("Tactics 2");
mnTactics.add(mntmTactics_1);
JMenu mnServer = new JMenu("Server");
menuBar.add(mnServer);
JMenuItem mntmServerStatus = new JMenuItem("Server Status");
mntmServerStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//String gameId = "Game ID:" + server.getGameIdOnServer();
JOptionPane.showMessageDialog(boardgui,
server.gameIdOnServer,
"A plain message",
JOptionPane.PLAIN_MESSAGE);
}
});
mnServer.add(mntmServerStatus);
JMenuItem mntmServerLog = new JMenuItem("Server Log");
mntmServerLog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JavaConsole console = new JavaConsole();
console.frame.setVisible(true);
console.frame.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
}
});
mnServer.add(mntmServerLog);
JMenuItem mntmViewOnlinePlayers = new JMenuItem("View Online Players");
mnServer.add(mntmViewOnlinePlayers);
JMenu mnStatistics = new JMenu("Statistics");
menuBar.add(mnStatistics);
JMenuItem mntmHumanStatsAgainst = new JMenuItem("Human Stats Against Computer");
mnStatistics.add(mntmHumanStatsAgainst);
JSeparator separator_8 = new JSeparator();
mnStatistics.add(separator_8);
JMenuItem mntmComputerStatsAgainst = new JMenuItem("Computer Stats Against Itself");
mnStatistics.add(mntmComputerStatsAgainst);
JSeparator separator_9 = new JSeparator();
mnStatistics.add(separator_9);
JMenuItem mntmHumanStatsAgains = new JMenuItem("Human Stats Agains Human");
mnStatistics.add(mntmHumanStatsAgains);
JMenuItem mntmAlgorithmInformation = new JMenuItem("Algorithm Information");
mnStatistics.add(mntmAlgorithmInformation);
JMenu mnOptions = new JMenu("Options");
menuBar.add(mnOptions);
JMenu mnTest = new JMenu("Test");
mnOptions.add(mnTest);
JMenuItem mntmPiecePosition = new JMenuItem("Piece Position");
mnTest.add(mntmPiecePosition);
JMenuItem mntmPieceMoves = new JMenuItem("Piece Moves");
mnTest.add(mntmPieceMoves);
JSeparator separator_11 = new JSeparator();
mnOptions.add(separator_11);
JMenuItem mntmConsole = new JMenuItem("Console");
mntmConsole.addActionListener(new ConsoleController());
mnOptions.add(mntmConsole);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmRulesOfChess = new JMenuItem("Rules of Chess");
mnHelp.add(mntmRulesOfChess);
JMenuItem mntmAbout = new JMenuItem("About");
mnHelp.add(mntmAbout);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
panel.setBounds(0, 0, 50, 50);
lblNewLabel = new JLabel("text");
panel.add(lblNewLabel);
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.1);
contentPane.add(splitPane, BorderLayout.CENTER);
game = new Game();
boardgui = new BoardGUI(game);
splitPane.setLeftComponent(boardgui);
GameConfig(yellowPlayerOption, brownPlayerOption, game, gameIdOnServer, gamePassword, boardgui);
StatusPanel panel_1 = new StatusPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
boardgui.lblGameState = new JLabel();
panel_1.add(boardgui.lblGameState);
JPanel panel_2 = new JPanel();
splitPane.setRightComponent(panel_2);
panel_2.setBounds(0, 0, 50, 300);
panel_2.setLayout(null);
BrownPlayerPanel brown = new BrownPlayerPanel();
panel_2.add(brown);
MovesHistoryPanel moveDisplay = new MovesHistoryPanel();
moveDisplay.setBorder(new LineBorder(new Color(139, 69, 19)));
panel_2.add(moveDisplay);
YellowPlayerPanel yellow = new YellowPlayerPanel();
yellow.setBorder(new LineBorder(new Color(139, 69, 19)));
panel_2.add(yellow);
}
}
Given these things you stated are true:
when i run and print the variable of the bufferedImage it isn't null
In addition my list of captured chess piece stored in a "List capturedPiece" and is working fine
also the paths to the images are correct.
A common problem will custom painting that the panel that the painting is being done on has not default preferred size (0x0). A panel only get increased preferred size based on more components being added to it. In the case of custom painting on a panel, you need to give the panel an explicit preferred size by overriding getPreferredSize()
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
Without this, it can be hit or miss, whether or not you will see the contents of the panel. The determining factory is the layout manager of the parent container. Some layout managers will respect the preferred size (in which case, you won't see the contents) and some that won't respect preferred size (in which case, the panel will stretch to fit the container - where you may see the contents). Generally when custom painting, you always want to override the method. Have a look at this post to get an idea of which layout managers respect preferred sizes and which ones don't
If that doesn't work, I suggest you post an MCVE that we can run and test. Leave out all the unnecessary code that doesn't pertain to this problem. I'd sat just create a separate program that has nothing to do with your program, just a couple simple images being drawn to a panel, and add it to a frame. Something simple recreates the problem.
UPDATE
Don't use null layouts! Use layout managers.. Your layout a null for the container you want to add the panel in question to, but you can't do that without setting the bounds. But forget that. Like I said, don't use null layouts. Learn to use the layout managers in the link. Let them do the position and sizing for you.

Categories

Resources