Remove the gap between components in gridBagLayout - java

This is my class:
public class Main extends JFrame{
private Container container;
private GridBagConstraints cons;
private JPanel panelDisplay;
private int curX = 0, curY = 0;
public Main() {
initComp();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Main ex = new Main();
ex.setVisible(true);
}
});
}
private void initComp()
{
container = this.getContentPane();
container.setLayout(new GridBagLayout());
cons = new GridBagConstraints();
cons.gridx = 0;
cons.gridy = 0;
container.add(new PanelNot(), cons);
panelDisplay = new JPanel();
panelDisplay.setBackground(Color.blue);
panelDisplay.setPreferredSize(new Dimension(600, 400));
panelDisplay.setLayout(new GridBagLayout());
cons.gridx = 1;
cons.gridy = 0;
container.add(panelDisplay, cons);
for (int i = 0; i < 15; i++) // display 15 components
{
displayNot();
}
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting the default close operation of JFrame
this.pack();
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private void displayNot()
{
setLocGrid();
panelDisplay.add(new Not1(), cons);
}
private void setLocGrid()
{
if(curX==11) // maximum component to be display in 1 row is 11
{
curY += 1;
curX = 0;
}
cons.gridx = curX;
cons.gridy = curY;
cons.anchor = GridBagConstraints.FIRST_LINE_START;
cons.weightx = 1.0;
cons.weighty = 1.0;
curX += 1;
}
}
this is the output:
Just ignore the left panel. My problem is in the right panel which is, there is a gap between one component (component: Not1) to the other. i have set the preferedSize of each component to x=20 and y=30 as you can see in every component's background where the color is gray. So my question is, how to make the gap disappear?
UPDATE : my expectation:

Start by getting rid of cons.weightx and cons.weightx
private void setLocGrid() {
if (curX == 11) // maximum component to be display in 1 row is 11
{
curY += 1;
curX = 0;
}
cons.gridx = curX;
cons.gridy = curY;
cons.anchor = GridBagConstraints.FIRST_LINE_START;
//cons.weightx = 1.0;
//cons.weighty = 1.0;
curX += 1;
}
This will get you something like...
Now, you need some kind of filler that can push the components to the top/left position, for example...
for (int i = 0; i < 15; i++) // display 15 components
{
displayNot();
}
cons.gridy++;
cons.gridx = 12; // Based on you conditions in setLocGrid
cons.weightx = 1;
cons.weighty = 1;
JPanel filler = new JPanel();
filler.setOpaque(false);
panelDisplay.add(filler, cons);
Which will give you something like...

Related

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.

Dynamically replacing a panel of buttons

This is my first trial in java Swing. The issue am having is recreating the calendar panel every time the month changes. I would like to have the panelRightDown repopulated when addMonth is called (when > or < is clicked). I have tried calling revalidate, invalidate, repaint in addMonth but everything just goes haywire. The same methods ought to be implemented while calculating the year. Any help would be appreciated. More so, a better approach to this is highly welcome.
public class Gui extends JFrame {
private final int windowWidth = 700;
private final int windowHeight = 600;
private final Container container;
private final JPanel panelLeft = new JPanel();
private final JPanel panelRight = new JPanel();
private final GridBagConstraints gridBagConstraints = new GridBagConstraints();
private final int verticalSpacerSize = 8;
private final int horizontalSpacerSize = 15;
private Border lowerEtchedBorder =
BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
// -----
protected boolean controlsOnTop;
protected boolean removeOnDaySelection;
protected Calendar currentDisplayDate;
protected JButton prevMonth;
protected JButton nextMonth;
protected JButton prevYear;
protected JButton nextYear;
protected JTextField textField;
protected List<ActionListener> popupListeners =
new ArrayList<ActionListener>();
protected Popup popup;
protected SimpleDateFormat dayName = new SimpleDateFormat("d");
protected SimpleDateFormat monthName = new SimpleDateFormat("MMMM");
protected String iconFile = "datepicker.gif";
protected String[] weekdayNames =
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
JPanel datePanel = new JPanel();
JPanel panelRightDown = new JPanel();
JPanel controlsPanel;
// -----
// Constructor to setup the GUI components and event handlers
public Gui() {
//-----
currentDisplayDate = Calendar.getInstance();
controlsOnTop = true;
removeOnDaySelection = true;
//createPanel();
// Retrieve the content-pane of the top-level container JFrame
// All operations done on the content-pane
container = getContentPane();
container.setLayout(new BorderLayout());
//container.setMinimumSize(new Dimension(windowWidth, windowHeight));
createMenuBar();
createStatusBar();
JPanel fullPane = new JPanel();
fullPane.setLayout(new GridBagLayout());
// Spacer
container.add(Box.createVerticalStrut(
4), BorderLayout.NORTH);
container.add(fullPane, BorderLayout.CENTER);
fullPane.setMinimumSize(new Dimension(windowWidth, windowHeight));
// Position Left and Right panels
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 0.3;
gridBagConstraints.weighty = 1.0;
fullPane.add(panelLeft, gridBagConstraints);
gridBagConstraints.gridx = 1;
gridBagConstraints.weightx = 0;
fullPane.add(Box.createHorizontalStrut(
15), gridBagConstraints);
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 2;
gridBagConstraints.weightx = 0.9;
fullPane.add(panelRight, gridBagConstraints);
configurePanelLeft(panelLeft);
configurePanelRight(panelRight);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Prod - Reminder");
setSize(windowWidth, windowHeight);
setLocationRelativeTo(null);
setVisible(true);
addWindowListener(new Terminator());
}
public void setDate(String date) {
currentDisplayDate = Calendar.getInstance();
editDate(date);
}
public void setDate(Calendar date) {
currentDisplayDate = date;
//createPanel();
validate();
repaint();
}
public void setDate(int month, int day, int year) {
currentDisplayDate = Calendar.getInstance();
currentDisplayDate.set(expandYear(year), month - 1, day);
//createPanel();
validate();
repaint();
}
protected int expandYear(int year) {
if (year < 100) { // 2 digit year
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int current2DigitYear = currentYear % 100;
int currentCentury = currentYear / 100 * 100;
// set 2 digit year range +20 / -80 from current year
int high2DigitYear = (current2DigitYear + 20) % 100;
if (year <= high2DigitYear) {
year += currentCentury;
}
else {
year += (currentCentury - 100);
}
}
return year;
}
public void setControlsOnTop(boolean flag) {
controlsOnTop = flag;
//createPanel();
repaint();
}
public Calendar getCalendarDate() {
return currentDisplayDate;
}
public Date getDate() {
return currentDisplayDate.getTime();
}
public String getFormattedDate() {
return Integer.toString(getMonth()) + "/" +
Integer.toString(getDay()) + "/" +
Integer.toString(getYear());
}
public int getMonth() {
return currentDisplayDate.get(Calendar.MONTH) + 1;
}
public int getDay() {
return currentDisplayDate.get(Calendar.DAY_OF_MONTH);
}
public int getYear() {
return currentDisplayDate.get(Calendar.YEAR);
}
protected JPanel createControls() {
JPanel c = new JPanel();
c.setBorder(BorderFactory.createRaisedBevelBorder());
c.setFocusable(true);
c.setLayout(new FlowLayout(FlowLayout.CENTER));
prevYear = new JButton("<<");
c.add(prevYear);
prevYear.setMargin(new Insets(0,0,0,0));
prevYear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addYear(-1);
}
});
prevMonth = new JButton("<");
c.add(prevMonth);
prevMonth.setMargin(new Insets(0,0,0,0));
prevMonth.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addMonth(-1);
}
});
textField = new JTextField(getFormattedDate(), 10);
c.add(textField);
textField.setEditable(true);
textField.setEnabled(true);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editDate(textField.getText());
}
});
nextMonth = new JButton(">");
c.add(nextMonth);
nextMonth.setMargin(new Insets(0,0,0,0));
nextMonth.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addMonth(+1);
}
});
nextYear = new JButton(">>");
c.add(nextYear);
nextYear.setMargin(new Insets(0,0,0,0));
nextYear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
addYear(+1);
}
});
return c;
}
protected JPanel configureDatePicker() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
datePanel.setFocusable(true);
datePanel.setLayout(gridbag);
String month = monthName.format(currentDisplayDate.getTime());
String year = Integer.toString(getYear());
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 7;
c.gridheight = 1;
JLabel title = new JLabel(month + " " + year);
datePanel.add(title, c);
Font font = title.getFont();
// Font titleFont = new Font(font.getName(), font.getStyle(),
// font.getSize() + 2);
Font weekFont = new Font(font.getName(), font.getStyle(),
font.getSize() - 2);
title.setFont(font);
c.gridy = 1;
c.weightx = 0.1;
c.weighty = 0.1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
for (c.gridx = 0; c.gridx < 7; c.gridx++) {
JLabel label = new JLabel(
weekdayNames[c.gridx], SwingConstants.CENTER);
datePanel.add(label, c);
label.setFont(weekFont);
}
Calendar draw = (Calendar) currentDisplayDate.clone();
draw.set(Calendar.DATE, 1);
draw.add(Calendar.DATE, -draw.get(Calendar.DAY_OF_WEEK) + 1);
int monthInt = currentDisplayDate.get(Calendar.MONTH);
// monthInt = 0;
// System.out.println("Current month: " + monthInt);
c.gridwidth = 1;
c.gridheight = 1;
int width = getFontMetrics(weekFont).stringWidth(" Wed ");
int width1 = getFontMetrics(weekFont).stringWidth("Wed");
int height = getFontMetrics(weekFont).getHeight() +
(width - width1);
for (c.gridy = 2; c.gridy < 8; c.gridy++) {
for (c.gridx = 0; c.gridx < 7; c.gridx++) {
JButton dayButton;
// System.out.print("Draw month: " + draw.get(Calendar.MONTH));
if (draw.get(Calendar.MONTH) == monthInt) {
String dayString = dayName.format(draw.getTime());
if (draw.get(Calendar.DAY_OF_MONTH) < 10) {
dayString = " " + dayString;
}
dayButton = new JButton(dayString);
} else {
dayButton = new JButton();
dayButton.setEnabled(false);
}
// System.out.println(", day: " + dayName.format(draw.getTime()));
datePanel.add(dayButton, c);
Color color = dayButton.getBackground();
if ((draw.get(Calendar.DAY_OF_MONTH) == getDay()) &&
(draw.get(Calendar.MONTH) == monthInt)) {
dayButton.setBackground(Color.yellow);
// dayButton.setFocusPainted(true);
// dayButton.setSelected(true);
} else
dayButton.setBackground(color);
dayButton.setFont(weekFont);
dayButton.setFocusable(true);
//dayButton.setPreferredSize(new Dimension(width, height));
//dayButton.setMargin(new Insets(0,0,0,0));
dayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeDay(e.getActionCommand());
}
});
//if (dateChange != null)
// dayButton.addActionListener(dateChange);
draw.add(Calendar.DATE, +1);
}
// if (draw.get(Calendar.MONTH) != monthInt) break;
}
return datePanel;
}
public void addMonth(int month) {
currentDisplayDate.add(Calendar.MONTH, month);
datePanel.invalidate();
controlsPanel.invalidate();
panelRightDown.validate();
datePanel = configureDatePicker();
controlsPanel = createControls();
panelRightDown.removeAll();
panelRightDown.add(controlsPanel);
panelRightDown.add(datePanel);
validate();
repaint();
}
public void addYear(int year) {
currentDisplayDate.add(Calendar.YEAR, year);
validate();
repaint();
}
public void editDate(String date) {
parseDate(date);
//createPanel();
validate();
repaint();
}
protected void parseDate(String date) {
String[] parts = date.split("/");
switch (parts.length) {
case 3:
currentDisplayDate.set(Calendar.MONTH,
Integer.valueOf(parts[0]) - 1);
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(parts[1]));
currentDisplayDate.set(Calendar.YEAR,
expandYear(Integer.valueOf(parts[2])));
break;
case 2:
currentDisplayDate = Calendar.getInstance();
currentDisplayDate.set(Calendar.MONTH,
Integer.valueOf(parts[0]) - 1);
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(parts[1]));
break;
default:
// invalid date
currentDisplayDate = Calendar.getInstance();
break;
}
}
public void changeDay(String day) {
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(day.trim()));
textField.setText(getFormattedDate());
if (!removeOnDaySelection) {
//createPanel();
//validate();
repaint();
}
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit");
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener((ActionEvent event) -> {
System.exit(0);
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
}
private void createStatusBar() {
// create the status bar panel and shove it down the bottom of the frame
JPanel statusPanel = new JPanel();
statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
container.add(statusPanel, BorderLayout.SOUTH);
statusPanel.setPreferredSize(new Dimension(container.getWidth(), 20));
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
JLabel statusLabel = new JLabel("status");
statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
statusPanel.add(statusLabel);
}
public void configurePanelLeft(JPanel panel) {
// Configure Left-side panels
// Top panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 0.3;
gridBagConstraints.weighty = 0.3;
JPanel panelLeftTop = new JPanel();
panelLeftTop.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.YELLOW));
panel.setLayout(new GridBagLayout());
panel.add(panelLeftTop, gridBagConstraints);
// Display Area
JTextArea displayItem = new JTextArea("Hello, left top!");
displayItem.setBorder(lowerEtchedBorder);
displayItem.setLineWrap(true);
displayItem.setBackground(panel.getBackground());
displayItem.setWrapStyleWord(true);
//displayItem.setEditable(false);
panelLeftTop.setLayout(new BorderLayout());
JScrollPane topScrollPane = new JScrollPane();
topScrollPane.getVerticalScrollBar().setUnitIncrement(3);
topScrollPane.setViewportView(displayItem);
topScrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelLeftTop.add(topScrollPane);
// Spacer
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0;
panel.add(Box.createVerticalStrut(
verticalSpacerSize), gridBagConstraints);
// Bottom panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.7;
JPanel panelLeftDown = new JPanel();
panelLeftDown.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLUE));
panelLeftDown.setLayout(new GridBagLayout());
for (int i = 0; i < 50; i++) {
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = i;
gridBagConstraints.weightx = 0.3;
//gridBagConstraints.weighty = 1.0;
String textValue = "Area: "+ i
+" This is a very long wrapped text, "
+ "which I expect to be an example of text in a label. "
+ "I really hope it works well."
+ "The Scroll Bar comes when your text goes beyond "
+ "the bounds of your view area. "
+ "Don't use Absolute Positioning, for such a small "
+ "talk at hand, always prefer Layout Managers, "
+ "do read the first para of the first link, "
+ "to know the advantage of using a Layout Manager.";
JTextArea textArea = new JTextArea(textValue);
textArea.setBorder(lowerEtchedBorder);
textArea.setLineWrap(true);
textArea.setBackground(panel.getBackground());
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
displayItem.setText(textValue);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
topScrollPane.getVerticalScrollBar().setValue(0);
}
});
}
#Override
public void mousePressed(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseReleased(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseEntered(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseExited(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
panelLeftDown.add(textArea, gridBagConstraints);
}
JScrollPane scrollPane = new JScrollPane(panelLeftDown,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelLeftDown.setAutoscrolls(true);
scrollPane.setPreferredSize(new Dimension(300,800));
scrollPane.getVerticalScrollBar().setUnitIncrement(3);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollPane.getVerticalScrollBar().setValue(0);
}
});
panel.add(scrollPane, gridBagConstraints);
}
public void configurePanelRight(JPanel panel) {
// Configure right-side panels
// Top panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.1;
JPanel panelRightTop = new JPanel();
panelRightTop.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.YELLOW));
panelRightTop.add(new JLabel("Hello, right top!"));
panel.setLayout(new GridBagLayout());
panel.add(panelRightTop, gridBagConstraints);
// Spacer
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0;
panel.add(Box.createVerticalStrut(
verticalSpacerSize), gridBagConstraints);
// Bottom panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.9;
panelRightDown.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLUE));
//panelRightDown.add(new JLabel("Hello, right down!"));
panel.add(panelRightDown, gridBagConstraints);
panel.add(panelRightDown, gridBagConstraints);
// Date Picker
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.1;
panelRightDown.setLayout(new BorderLayout());
datePanel = configureDatePicker();
controlsPanel = createControls();
panelRightDown.add(controlsPanel, BorderLayout.NORTH);
panelRightDown.add(datePanel, BorderLayout.CENTER);
}
private ListCellRenderer<? super String> getRenderer() {
return new DefaultListCellRenderer(){
#Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel listCellRendererComponent =
(JLabel) super.getListCellRendererComponent(
list, value, index, isSelected,cellHasFocus);
listCellRendererComponent.setBorder(
lowerEtchedBorder);
listCellRendererComponent.setEnabled(true);
return listCellRendererComponent;
}
};
}
public static void main(String[] args) {
// Run the GUI construction in the Event-Dispatching thread for thread-safety
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui(); // Let the constructor do the job
}
});
}
}

Drawing with paintComponent in JScrollPanel

I'm actually stuck on something strange. I have a JFrame with a JScrollPane containing a jPanel far larger than the actual screen. I draw squares in colums and I want theses squares to go over the right border of the jPanel. (So that they will appear as you scroll to the right.) But the squares painted with the method paintComponents just stop at the visible ViewPort of the JScrollPane.
Here is my code for the JScrollPane inside of the JFrame:
public void initComponents(){
mainPanel = new DrawPanel(dim);
this.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
JScrollPane jsp = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jsp.setLayout(new ScrollPaneLayout());
jsp.setViewportView(mainPanel);
jsp.getVerticalScrollBar().setUnitIncrement(20);
jsp.setBorder(BorderFactory.createEmptyBorder());
jsp.setPreferredSize(new Dimension(dim.width,dim.height -taskBarSize));
jsp.setMinimumSize(new Dimension(dim.width,dim.height -taskBarSize));
jsp.setMaximumSize(new Dimension(dim.width,dim.height -taskBarSize));
this.getContentPane().add(jsp, gbc);
this.getContentPane().revalidate();
this.getContentPane().repaint();
}
And here is my JPanel class :
public class DrawPanel extends JPanel {
private Dimension dim;
private Integer numberPanels = 7;
private Double startPointX;
private Double startPointY;
private Double heightRow;
private Double heightPanel;
public DrawPanel(Dimension d) {
this.dim = d;
//this.setBackground(Color.BLACK);
calculateStartPoint();
}
public void calculateStartPoint() {
startPointX = (dim.getWidth() / 10) * 1;
startPointY = (dim.getHeight() / 10) * 1;
heightRow = (dim.getHeight() * 0.8) / numberPanels;
heightPanel = heightRow - 10;
double colums = 366/numberPanels;
this.setPreferredSize(new Dimension((int)(heightRow *((int)colums + 1)), dim.height ));
this.setMinimumSize(new Dimension((int)(heightRow *((int)colums + 1)), dim.height ));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GRAY);
for (int i = 1; i <= 366; i++) {
// Si c'est le dernier d'une colonne
if (i%numberPanels == 0 && i != 0) {
g.fillRect(startPointX.intValue(), startPointY.intValue(), heightPanel.intValue(),
heightPanel.intValue());
startPointX = startPointX + heightRow;
startPointY = startPointY - ((numberPanels -1) * heightRow);
// Si c'est encore dans la meme colonne
} else {
g.fillRect(startPointX.intValue(), startPointY.intValue(), heightPanel.intValue(),
heightPanel.intValue());
startPointY = startPointY + heightRow;
}
}
}
}
At startup:
When I move the scrollPane:
Also, on resizing everything disapreas. Also I had to see that when scrolling back, the already painted squares disapeared, as if everything out of screen disppears.
Thanks for anybody who has some time for this.
Your problem is that you need to recalculate the starting points every time the painting is done. Else the variables keep increasing unnecessarily. So add two lines:
#Override
protected void paintComponent(Graphics g) { // should be protected
super.paintComponent(g);
// need to re-initialize variables within this
startPointX = (dim.getWidth() / 10) * 1;
startPointY = (dim.getHeight() / 10) * 1;
FYI, in the future, please post a MCVE with your question. For example, this is the MCVE that I made out of your code, code that now can be copied, pasted and run by anyone:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class Foo02 extends JPanel {
private DrawPanel mainPanel;
private Dimension dim = new Dimension(200, 200);
public Foo02() {
initComponents();
}
public void initComponents() {
mainPanel = new DrawPanel(dim);
// !! this.getContentPane().setLayout(new GridBagLayout());
setLayout(new GridBagLayout()); // !!
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
JScrollPane jsp = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jsp.setLayout(new ScrollPaneLayout());
jsp.setViewportView(mainPanel);
jsp.getVerticalScrollBar().setUnitIncrement(20);
jsp.setBorder(BorderFactory.createEmptyBorder());
jsp.setPreferredSize(new Dimension(dim.width, dim.height));
jsp.setMinimumSize(new Dimension(dim.width, dim.height));
jsp.setMaximumSize(new Dimension(dim.width, dim.height));
add(jsp, gbc);
revalidate();
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
Foo02 mainPanel = new Foo02();
JFrame frame = new JFrame("Foo02");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class DrawPanel extends JPanel {
private Dimension dim;
private Integer numberPanels = 7;
private Double startPointX;
private Double startPointY;
private Double heightRow;
private Double heightPanel;
public DrawPanel(Dimension d) {
this.dim = d;
// this.setBackground(Color.BLACK);
calculateStartPoint();
}
public void calculateStartPoint() {
startPointX = (dim.getWidth() / 10) * 1;
startPointY = (dim.getHeight() / 10) * 1;
heightRow = (dim.getHeight() * 0.8) / numberPanels;
heightPanel = heightRow - 10;
double colums = 366 / numberPanels;
this.setPreferredSize(new Dimension((int) (heightRow * ((int) colums + 1)), dim.height));
this.setMinimumSize(new Dimension((int) (heightRow * ((int) colums + 1)), dim.height));
}
#Override
protected void paintComponent(Graphics g) { // should be protected
super.paintComponent(g);
// need to re-initialize variables within this
startPointX = (dim.getWidth() / 10) * 1;
startPointY = (dim.getHeight() / 10) * 1;
g.setColor(Color.GRAY);
for (int i = 1; i <= 366; i++) {
// Si c'est le dernier d'une colonne
if (i % numberPanels == 0 && i != 0) {
g.fillRect(startPointX.intValue(), startPointY.intValue(), heightPanel.intValue(),
heightPanel.intValue());
startPointX = startPointX + heightRow;
startPointY = startPointY - ((numberPanels - 1) * heightRow);
// Si c'est encore dans la meme colonne
} else {
g.fillRect(startPointX.intValue(), startPointY.intValue(), heightPanel.intValue(),
heightPanel.intValue());
startPointY = startPointY + heightRow;
}
}
}
}

My GUI is acting really weird

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();
}
});
}
}

2 Player Checkers Game (Java)

In my Springbreak holiday I started to write Checkers Game. I have created my CheckersBoard but I couldn't write MouseListener part. Can you help me with this part? I'm not pretty sure how to implement this part? Is MouseListener correct? Or should I choose another Listener? I have googled but couldn't any clue.
Thank you so much.
public class CheckersGUI {
private final JPanel gui = new JPanel(new BorderLayout(3, 3));
private JButton[][] Squares = new JButton[8][8];
private JPanel Board;
private final JLabel message = new JLabel(
"Ready to play!");
private static final String COLS = "ABCDEFGH";
private ImageIcon brown = new ImageIcon("brown.jpg");
private ImageIcon red = new ImageIcon("red.png");
CheckersGUI() {
create();
//create ButtonHandler
/* ButtonHandler handler = new ButtonHandler();
for (int i=0; i<Squares.length; i++){
for (int j=0; i<Squares[0].length; i++){
Squares[i][j].addMouseListener(handler);
}
}
}
private class ButtonHandler implements MouseListener{
public void MouseClicked ( MouseEvent event){
}*/
}
public final void create() {
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
JToolBar tools = new JToolBar();
tools.setFloatable(false);
gui.add(tools, BorderLayout.PAGE_START);
Action newGameAction = new AbstractAction("New") {
#Override
public void actionPerformed(ActionEvent e) {
setupNewGame();
}
};
tools.add(newGameAction);
// TODO - add functionality!
tools.addSeparator();
tools.add(message);
gui.add(new JLabel(""), BorderLayout.LINE_START);
Board = new JPanel(new GridLayout(0, 9)) ;
Board.setBorder(new CompoundBorder(
new EmptyBorder(8,8,8,8),
new LineBorder(Color.BLACK)
));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(Board);
gui.add(boardConstrain);
// create the chess board squares
Insets buttonMargin = new Insets(0, 0, 0, 0);
for (int ii = 0; ii < Squares.length; ii++) {
for (int jj = 0; jj < Squares[ii].length; jj++) {
JButton b = new JButton();
b.setMargin(buttonMargin);
ImageIcon icon = new ImageIcon(
new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));
b.setIcon(icon);
if ((jj % 2 == 1 && ii % 2 == 1)
|| (jj % 2 == 0 && ii % 2 == 0)) {
b.setBackground(Color.WHITE);
} else {
b.setBackground(Color.BLACK);
}
Squares[jj][ii] = b;
}
}
/*
* fill the chess board
*/
Board.add(new JLabel(""));
// fill the top row
for (int ii = 0; ii < 8; ii++) {
Board.add(
new JLabel(COLS.substring(ii, ii + 1),
SwingConstants.CENTER));
}
// fill the black non-pawn piece row
for (int ii = 0; ii < 8; ii++) {
for (int jj = 0; jj < 8; jj++) {
switch (jj) {
case 0:
Board.add(new JLabel("" + (9-(ii + 1)),
SwingConstants.CENTER));
default:
Board.add(Squares[jj][ii]);
}
}
}
}
public final JComponent getGui() {
return gui;
}
/**
* Initializes the icons of the initial chess board piece places
*/
private final void setupNewGame() {
message.setText("Make your move!");
for (int ii = 0; ii < 8; ii++) {
Squares[ii][1].setIcon(red);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][2].setIcon(red);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][5].setIcon(brown);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][6].setIcon(brown);
}
}
public static void main(String[] args) {
CheckersGUI cg = new CheckersGUI();
JFrame f = new JFrame("Checkers");
f.add(cg.getGui());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
f.setResizable(false);
f.setVisible(true);
}
}
You can add an ActionListener to each button. If the button is pressed (actually, when it is released) the actionPerformed method will be called.
Add the following to your code, to make each square red after it has been clicked:
public static class ButtonHandler implements ActionListener {
private JButton b;
public ButtonHandler(JButton b) {
this.b = b;
}
#Override
public void actionPerformed(ActionEvent e) {
b.setBackground(Color.red);
}
}
This is the handler. Notice that each handler instance will be associated with a button.
Now, create and add a new ButtonHandler to each button after it has been created:
JButton b = new JButton();
...
b.addActionListener(new ButtonHandler(b));
You can change the implementation of actionPerformed.
Example: Add a method getCurrentPlayer() to actionPerformed, then, if the current player is player one, change the color to blue, else, change the color to red.
I trust this will help you to achieve what you need.

Categories

Resources