I am trying to make an actual timer that keeps track of the time in my Minesweeper game. However, I don't know how to code my actionPerformed method in order to set the timer start and the timer end.
I want the timer to start once the player clicks on a button in the mine field, and I want the timer to end when the player wins or loses.
I did do a gameEnd method that determines when the player wins or loses, but like I said, I just don't know how to code the actionPerformed method.
import java.util.Scanner;
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
public class Minesweeper extends JFrame implements ActionListener {
public static Scanner myScanner = new Scanner (System.in);
public static Random random = new Random ();
JPanel pan1 = new JPanel ();
JPanel pan2 = new JPanel ();
JPanel pan3 = new JPanel ();
JPanel pan1_1 = new JPanel ();
JPanel pan1_2 = new JPanel ();
JPanel pan1_3 = new JPanel ();
JPanel pan1_3_D = new JPanel ();
JButton button [][];
JButton Save = new JButton ("Save");
JButton Load = new JButton ("Load");
JButton New = new JButton ("New");
JButton One = new JButton ("1");
JButton Two = new JButton ("2");
JButton Three = new JButton ("3");
JButton R = new JButton ("R");
JLabel instruction = new JLabel ("Instruction Panel");//changeable
JLabel timeLabel = new JLabel ();
JLabel score = new JLabel ("Score");//it is only temporary
static Timer timer;
public Minesweeper (int row, int column) {
button = new JButton [row][column];
GridLayout gl_pan1 = new GridLayout (1, 3);
GridLayout gl_pan2 = new GridLayout (row, column);
GridLayout gl = new GridLayout (2, 1);//gl is for the 3 sub-panels in pan1
GridLayout gl_pan1_3_D = new GridLayout (1, 4);
pan1.setLayout (gl_pan1);
pan2.setLayout (gl_pan2);
pan1_1.setLayout (gl);
pan1_2.setLayout (gl);
pan1_3.setLayout (gl);
pan1_3_D.setLayout (gl_pan1_3_D);
setTitle ("Minesweeper");
JPanel frameBorder = (JPanel)getContentPane ();
frameBorder.setLayout (new BoxLayout (getContentPane (), BoxLayout.Y_AXIS));
frameBorder.setBorder (new BevelBorder (BevelBorder.LOWERED));
pan1.setBorder (new EtchedBorder (EtchedBorder.LOWERED));
pan2.setBorder (new EtchedBorder (EtchedBorder.LOWERED));
pan3.setBorder (new EtchedBorder (EtchedBorder.LOWERED));
Save.setMinimumSize (new Dimension (25, 50));
Save.setPreferredSize (new Dimension (25, 50));
Save.setMaximumSize (new Dimension (25, 50));
Load.setMinimumSize (new Dimension (25, 50));
Load.setPreferredSize (new Dimension (25, 50));
Load.setMaximumSize (new Dimension (25, 50));
New.setMinimumSize (new Dimension (25, 50));
New.setPreferredSize (new Dimension (25, 50));
New.setMaximumSize (new Dimension (25, 50));
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
button [r][c] = new JButton ();
button [r][c].setMinimumSize (new Dimension (20, 40));
button [r][c].setPreferredSize (new Dimension (20, 40));
button [r][c].setMaximumSize (new Dimension (20, 40));
pan2.add (button [r][c]);
button [r][c].addActionListener (this);
}
}
pan1_1.add (Save);
pan1_1.add (Load);
pan1_2.add (timeLabel);
pan1_2.add (score);
pan1_3.add (New);
pan1_3_D.add (One);
pan1_3_D.add (Two);
pan1_3_D.add (Three);
pan1_3_D.add (R);
pan1_3.add (pan1_3_D);
Save.addActionListener (this);
Load.addActionListener (this);
New.addActionListener (this);
One.addActionListener (this);
Two.addActionListener (this);
Three.addActionListener (this);
R.addActionListener (this);
pan1.add (pan1_1);
pan1.add (pan1_2);
pan1.add (pan1_3);
pan3.add (instruction);
frameBorder.add (pan1);
frameBorder.add (pan2);
frameBorder.add (pan3);
setContentPane (frameBorder);
pack ();
setVisible (true);
}
private void setTimerText (String sTime) {
timeLabel.setText (sTime);
}
public void actionPerformed (ActionEvent e) {
}
public static void main (String args []) throws Exception {
int row = 10;
int column = 10;
new Minesweeper (row, column);
int current_row = 5;
int current_col = 5;
int percentage = 10; //this is subject to change
int number_of_mines = (int)(row*column*percentage*0.01);
int mine_position [] = new int [number_of_mines];
boolean revealed [][] = new boolean [row][column]; //whether the button is revealed or not
boolean mines [][] = new boolean [row][column]; //whether there is a mine or not
int revealed_number [][] = new int [row][column]; //the number that should appear on the revealed button
int counter = 0; //this is for the gameEnd method
boolean end = false; //whether the game is ended or not
}
public static void gameEnd (int row, int column, boolean revealed [][], boolean mines [][], int number_of_mines, int counter, boolean end) {
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
if (mines [r][c] == false && revealed [r][c] == true) {
counter++;
}
else if (mines [r][c] == true && revealed [r][c] == true) {
System.out.println ("Sorry, you lost because you clicked on a mine.");
end = true;
break;
}
}
}
if (counter == (row*column-number_of_mines)) {
System.out.println ("Congratulations! You won the game!");
end = true;
}
}
}
timer.scheduleAtFixedRate(task, 1000, 1000);
where task is an instance of a class overriding java.util.TimerTask.
In its run() method (abstract in TimerTask), you would update the timer label (keep an eye on multithreading!), and in endGame, you call
timer.cancel();
Related
I was stucked in the same place for almost 1 day still I can't find where's the error on my code. Need your guys to help, this is my code. (Quite a bit lengthy)
My JFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CircleProject extends JFrame implements ActionListener{
JTextField xTextField1;
JTextField yTextField1;
JTextField textFieldRadiusLeft;
JTextField xTextField2;
JTextField yTextField2;
JTextField textFieldRadiusRight;
JButton redraw;
public static void main(String[] args) {
CircleProject frame = new CircleProject();
frame.setResizable(true);
frame.setVisible(true);
frame.setSize(580, 700);
frame.setTitle("YONG JING PING FINAL PROJECT");
}
public CircleProject() {
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel theTitle = new JLabel("Two Circles Intersect?");
JLabel intersection = new JLabel("");
titlePanel.add(theTitle);
titlePanel.add(intersection);
JPanel contentPanel = new JPanel(new GridLayout(2, 1));
JPanel userInputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JPanel gridPanel = new JPanel(new GridLayout(1, 2, 8, 0));
JPanel leftInputPanel = new JPanel(new GridLayout(4, 1));
JLabel inputTitle1 = new JLabel("Enter circle 1 info: ");
inputTitle1.setHorizontalAlignment(JLabel.CENTER);
JPanel xInputPanelLeft = new JPanel();
xTextField1 = new JTextField(5);
xInputPanelLeft.add(new JLabel("Center X: "));
xInputPanelLeft.add(xTextField1);
JPanel yInputPanelLeft = new JPanel();
yTextField1 = new JTextField(5);
yInputPanelLeft.add(new JLabel("Center Y: "));
yInputPanelLeft.add(yTextField1);
JPanel radiusLeft = new JPanel();
textFieldRadiusLeft = new JTextField(5);
radiusLeft.add(new JLabel("Radius: "));
radiusLeft.add(textFieldRadiusLeft);
leftInputPanel.add(inputTitle1);
leftInputPanel.add(xInputPanelLeft);
leftInputPanel.add(yInputPanelLeft);
leftInputPanel.add(radiusLeft);
leftInputPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JPanel rightInputPanel = new JPanel(new GridLayout(4, 1));
JLabel inputTitle2 = new JLabel("Enter circle 2 info: ");
inputTitle2.setHorizontalAlignment(JLabel.CENTER);
JPanel xInputPanelRight = new JPanel();
xTextField2 = new JTextField(5);
xInputPanelRight.add(new JLabel("Center X: "));
xInputPanelRight.add(xTextField2);
JPanel yInputPanelRight = new JPanel();
yTextField2 = new JTextField(5);
yInputPanelRight.add(new JLabel("Center Y: "));
yInputPanelRight.add(yTextField2);
JPanel radiusRight = new JPanel();
textFieldRadiusRight = new JTextField(5);
radiusRight.add(new JLabel("Radius: "));
radiusRight.add(textFieldRadiusRight);
rightInputPanel.add(inputTitle2);
rightInputPanel.add(xInputPanelRight);
rightInputPanel.add(yInputPanelRight);
rightInputPanel.add(radiusRight);
rightInputPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
gridPanel.add(leftInputPanel);
gridPanel.add(rightInputPanel);
userInputPanel.add(gridPanel);
contentPanel.add(new DrawPanel());
contentPanel.add(userInputPanel);
redraw = new JButton("Redraw Circles");
redraw.setEnabled(true);
redraw.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(redraw);
setLayout(new BorderLayout());
add(titlePanel, BorderLayout.NORTH);
add(contentPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
DrawPanel drawCircle = new DrawPanel();
#Override
public void actionPerformed(ActionEvent e) {
this.setVisible(false);
if (e.getSource() == redraw) {
CircleProject frame2 = new CircleProject();
frame2.setResizable(false);
frame2.setVisible(true);
frame2.setSize(580,700);
frame2.setTitle("YONG JING PING FINAL PROJECT");
String text = xTextField1.getText();
int x1 = Integer.parseInt(text);
String text1 = xTextField2.getText();
int x2 = Integer.parseInt(text1);
String text2 = yTextField1.getText();
int y1 = Integer.parseInt(text2);
String text3 = yTextField2.getText();
int y2 = Integer.parseInt(text3);
String text4 = textFieldRadiusLeft.getText();
int r1 = Integer.parseInt(text4);
String text5 = textFieldRadiusRight.getText();
int r2 = Integer.parseInt(text5);
drawCircle.setCenterColumn1(x1, y1, r1);
drawCircle.setCenterColumn2(x2, y2, r2);
}
}
}
My Drawpanel Class:
import javax.swing.*;
import java.awt.*;
public class DrawPanel extends JPanel{
// the coordinate's variables is the start point of it.
int coordinateX1=50, coordinateX2=300, coordinateY1=50, coordinateY2=50, radius1=0, radius2=0, length1=200, length2=200;
public void setCenterColumn1(int x, int y, int radius1){
this.coordinateX1 = x-radius1;
this.coordinateY1 = y-radius1;
this.radius1 = radius1;
length1 = radius1*2;
System.out.println(coordinateX1);
System.out.println(coordinateY1);
System.out.println(length1);
System.out.println(coordinateX2);
System.out.println(coordinateY2);
System.out.println(length2);
System.out.println("-------1-------");
repaint();
}
public void setCenterColumn2(int x, int y, int radius2){
this.coordinateX2=x-radius2;
this.coordinateY2=y-radius2;
this.radius2=radius2;
length2 = radius2*2;
System.out.println(coordinateX1);
System.out.println(coordinateY1);
System.out.println(length1);
System.out.println(coordinateX2);
System.out.println(coordinateY2);
System.out.println(length2);
System.out.println("-------2-------");
repaint();
}
public DrawPanel(){
setBackground(Color.WHITE);
}
// error from here, when redraw pressed this paintComponent does not
// show up the new circle.
#Override
public void paintComponent (Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
// Circle for column 1
g.drawOval(coordinateX1,coordinateY1,length1,length1);
// Circle for column 2
g.drawOval(coordinateX2,coordinateY2,length2,length2);
System.out.println(coordinateX1);
System.out.println(coordinateY1);
System.out.println(length1);
System.out.println(coordinateX2);
System.out.println(coordinateY2);
System.out.println(length2);
System.out.println("-------3-------");
}
}
My expected result is the circle will be changed after the user input the centre coordinate of the circle and clicked redraw btn.
The problem is that you are not using never your variable drawCircle (line:
DrawPanel drawCircle = new DrawPanel();)
And when you use inside actionPerformed method, you never use that variable because it's created another instance of Circle Project. (line: CircleProject frame2 = new CircleProject();)
The drawCircle variable is from the current class you are running,so, when you instance again CircleProject, the changes inside that variabe will not have effect.
To fix that, it's not necessary to instance again, you only must use that variable.
The first thing you will have to do inside the Constructor CircleProject():
....
userInputPanel.add(gridPanel);
contentPanel.add(drawCircle);
contentPanel.add(userInputPanel);
....
The change here was only one, because you have contentPanel.add(new DrawPanel()); and that's not correct (as I said, you never are using the variable drawCircle), so, instead, you have to change it for contentPanel.add(drawCircle);
On the other hand, to avoid instancing the CircleProject you will have to remove some lines in the actionPerformed method, like:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == redraw) {
String text = xTextField1.getText();
int x1 = Integer.parseInt(text);
String text1 = xTextField2.getText();
int x2 = Integer.parseInt(text1);
String text2 = yTextField1.getText();
int y1 = Integer.parseInt(text2);
String text3 = yTextField2.getText();
int y2 = Integer.parseInt(text3);
String text4 = textFieldRadiusLeft.getText();
int r1 = Integer.parseInt(text4);
String text5 = textFieldRadiusRight.getText();
int r2 = Integer.parseInt(text5);
drawCircle.setCenterColumn1(x1, y1, r1);
drawCircle.setCenterColumn2(x2, y2, r2);
}
}
I tried the program and it worked for me! I hope this also works for you :D
Hi guys I'm using Eclipse and I'm trying to create a Connect4 Game Grid , which is an JPanel gridArray [6] [7]. I later add the different Panels for buttons and the grid into a main panel and add it into my frame.
My Problem:
I want to fill the gridArray JPanel with Pictures of an empty field(white color) but first of all i want to create a new Panel and insert it into my gridArray through a loop until gridArray has all 42 Panels inside it and is fully filled. I have my Code below but somehow it doesnt work, although my logic should be fine.
I tried it with using a helper Function to create a new JPanel and call the function for each loop in fillGrid();, basically calling it 42 times but it still wont work...
I will gladly appreciate some help!
package connect4;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GridTest extends JFrame {
JFrame mainWindow;
JPanel buttonPanel, mainPanel;
JPanel gridPanel;
JPanel emptyPanel;
JPanel panel1;
ImageIcon emptyBox;
JPanel[][] gridArray;
JLabel emptyLabel;
JButton arrow1,arrow2,arrow3,arrow4,arrow5,arrow6,arrow7;
public GridTest() {
createGameGrid();
fillGrid();
}
public void createGameGrid() {
//creating window and mainpanel
mainWindow = new JFrame("Connect 4");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
//defining top panel with 7 buttons;
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 7));
arrow1 = new JButton("V");
arrow2 = new JButton("V");
arrow3 = new JButton("V");
arrow4 = new JButton("V");
arrow5 = new JButton("V");
arrow6 = new JButton("V");
arrow7 = new JButton("V");
buttonPanel.add(arrow1);
buttonPanel.add(arrow2);
buttonPanel.add(arrow3);
buttonPanel.add(arrow4);
buttonPanel.add(arrow5);
buttonPanel.add(arrow6);
buttonPanel.add(arrow7);
//create Grind Panel
gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(6,7));
mainPanel.add(buttonPanel, BorderLayout.NORTH);
mainPanel.add(gridPanel, BorderLayout.SOUTH);
mainWindow.add(mainPanel);
mainWindow.pack();
mainWindow.setLocationRelativeTo(null);
mainWindow.setVisible(true);
}
private JPanel greateOnePanel(){
//here we need to insert the icon which is in empty box into a newly created panel
//ifirst wanted to insert black panels do ensure it works as intended but it doesnt
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.setSize(50,50);
return panel;
}
//here we need to fill the grid with the panels created above from left to right...
public void fillGrid() {
for(int j = 0; j < 6; j++) {
for (int k = 0; k < 7; k++) {
gridPanel.add(greateOnePanel());
}
}
}
public static void main(String[] args) {
new GridTest();
}
}
i tried it with this method using gridArray, but it throws NullPointer Exeptions and wont fill the grid with simple textlabels "Hallo" (just for testing purposes)
public void fillGrid() {
for(int j = 0; j < 6; j++) {
for (int k = 0; k < 7; k++) {
JLabel label = new JLabel("Hallo");
gridArray[j][k] = new JPanel();
gridArray[j][k].setSize(50, 50);
gridArray[j][k].setBackground(Color.RED);
gridArray[j][k].add(label);
gridPanel.add(gridArray[j][k]);
}
}
}
Here is a short, self contained, code that should help with various aspects of the task.
There is no need for a panel in each cell. The only thing it helped with was setting a BG color. That can be done in a label as long as the background is set to opaque.
This code defines a SquareLabel which overrides getPreferredSize() to return the maximum of preferred width and height as the value of both (usually it is the width).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class SquareLabelGrid {
int rows = 6;
int cols = 7;
JLabel[][] labelArray = new JLabel[cols][rows];
Font bigFont = new Font(Font.SANS_SERIF, Font.BOLD, 30);
Insets labelInsets;
SquareLabelGrid() {
JPanel gameBoard = new JPanel(new GridLayout(rows, cols));
// a border to make the cell boundaries more clear and add
// some space around the text
Border border = new CompoundBorder(
new LineBorder(Color.BLACK),new EmptyBorder(4,4,4,4));
for (int yy = 0; yy < rows; yy++) {
for (int xx = 0; xx < cols; xx++) {
JLabel l = getColoredSquareLabel(xx, yy);
labelArray[xx][yy] = l;
gameBoard.add(l);
l.setBorder(border);
}
}
JOptionPane.showMessageDialog(null, gameBoard);
}
private JLabel getColoredSquareLabel(int x, int y) {
SquareLabel label = new SquareLabel(
String.format("%1s,%1s", (x+1), (y+1)));
label.setFont(bigFont);
label.setOpaque(true); // so we can see the BG color
label.setBackground(Color.ORANGE); // I prefer orange!
// make the GUI less 'crowded'
label.setBorder(new EmptyBorder(4,4,4,4));
return label;
}
public static void main(String[] args) {
Runnable r = () -> {
new SquareLabelGrid();
};
SwingUtilities.invokeLater(r);
}
}
class SquareLabel extends JLabel {
SquareLabel(String label) {
super(label);
}
/* This will create a square component that accounts for the
size of the String / Icon it contains. No guesswork! */
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int w = d.width;
int h = d.height;
int sz = w > h ? w : h;
return new Dimension(sz, sz);
}
}
The problem is that you have not initialized the grid array .
Otherwise it will throw Null pointer exception.
JPanel[][] gridArray = new JPanel[6][8];
Also set the preferred size of main panel to make the grids visible .
mainPanel.setPreferredSize(new Dimension(400, 200));
Here is what i can see when I run your code with the modifications mentioned here .
Also please execute it from main with following code .
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GridTest();
}
});
}
I am trying to get a text input from a JTextField and displaying it on a JTextField when a button is clicked. Can anyone help please?
I know I am supposed to use getText and setText but not quite sure how I can implement this when the button is clicked. Please have a look at the code below.
Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class CyberPet extends JFrame
implements ActionListener {
private JButton makePetButton,hungryButton, randomButton;
private JPanel panel;
private JLabel label, petName, flyLabel;
private JTextArea responseArea;
private JTextField textField;
int x =10;
int y=10;
int xMax = 700;
int yMax = 500;
public static void main (String[] args) {
CyberPet frame = new CyberPet();
frame.setSize(700, 500);
frame.createGUI();
frame.show();
frame.getContentPane().setBackground(Color.blue);
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout() );
JPanel buttonGUI = new JPanel();
panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 300));
panel.setLocation(500, 300);
panel.setBackground(Color.white);
panel.setLayout(null);
window.add(panel);
buttonGUI = new JPanel();
buttonGUI.setPreferredSize(new Dimension(400, 100));
buttonGUI.setLocation(200, 100);
buttonGUI.setBackground(Color.white);
window.add(buttonGUI);
label = new JLabel();
label.setBackground(Color.white);
Image img = new ImageIcon (this.getClass().getResource("/frog.gif")).getImage();
label.setIcon(new ImageIcon(img));
label.setLocation(400, 0);
label.setSize(80, 80);
panel.add(label);
flyLabel = new JLabel();
flyLabel.setBackground(Color.black);
Image img1 = new ImageIcon (this.getClass().getResource("/fly.gif")).getImage();
flyLabel.setIcon(new ImageIcon(img1));
flyLabel.setLocation(10, 10);
flyLabel.setSize(50, 50);
panel.add(flyLabel);
petName = new JLabel("Enter Pet Name!");
buttonGUI.add(petName);
textField = new JTextField("");
textField.setPreferredSize(new Dimension(100, 30));
textField.setLocation(200, 60);
textField.addActionListener(this);
buttonGUI.add(textField);
makePetButton = new JButton("Make Pet");
makePetButton.setLocation(160, 60);
makePetButton.addActionListener(this);
buttonGUI.add(makePetButton);
hungryButton = new JButton("Hungry!");
hungryButton.setLocation(280, 60);
hungryButton.setSize(100, 30);
hungryButton.addActionListener(this);
buttonGUI.add(hungryButton);
responseArea = new JTextArea("Pet Status");
buttonGUI.add(responseArea);
}
// ***** nb line of 4 spaces after insert
public void actionPerformed(ActionEvent event) {
//Move down
if (event.getSource() == makePetButton)
{
}
//Move Up
if (event.getSource() == hungryButton)
{
if (y > 10){
y=y-20;
label.setLocation(x, y);
}
}
//Makes the Pet
if (event.getSource() == makePetButton)
{
if (x > 10){
x=x-20;
label.setLocation(x, y);
}
}
//Move Right
if (event.getSource() == textField)
{
if (x < 280){
x=x+20;
label.setLocation(x, y);
}
}
//Move random
if(event.getSource() == randomButton)
{
Random rnd = new Random();
int xMax = panel.getWidth()-label.getWidth();
int yMax = panel.getHeight()-label.getHeight();
x = rnd.nextInt(xMax+10);
y = rnd.nextInt(yMax+10);
label.setLocation(x,y);
}
}
}
You have the eventHandler, so just call responseArea.setText(textField.getText()) when handling the click on the appropriate button.
I want to change the size of buttons. I want to set a SQUARE type view of each button but unfortunately it is giving a rectangular look. I am getting a square type look only if I set the number of rows to 20 or 25. Right now my GUI looks like the following: .
I have tried to change it from buttons[i][j].setMaximumSize(new Dimension( 20, 20)) , Where buttons is the name of array. I have also tried buttons[i][j].setsize but still it has no effect on it. I am setting it from : bPanel.setLayout(new GridLayout(x,y)) and I thing this is the main cause of the problem. Can any one also tell me that how can I set it to layout manager?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.event.*;
import javax.swing.JFrame;
import sun.util.calendar.Gregorian;
public class Final_GUI extends JFrame implements ActionListener {
JLabel label;
ButtonGroup cbg;
JRadioButton radio_1;
JRadioButton radio_2;
JRadioButton radio_3;
JCheckBox checkbox_1;
JCheckBox checkbox_2;
JCheckBox checkbox_3;
JScrollPane scrollpane_1;
JComboBox combobox_1;
JList list_1;
JScrollPane sp_list_1;
JComboBox combobox_2;
JButton Orange;
JButton Exit;
JLabel for_text;
int x=200;
int y=100;
int check [][]= new int [x][y];
JFrame frame = new JFrame();
JButton[][] buttons = new JButton[x][y];
JPanel mPanel = new JPanel();
JPanel bPanel = new JPanel();
JPanel cPanel = new JPanel();
JTextArea scoreKeeper = new JTextArea();
int[][] intArray = new int[x][y];
public Final_GUI() {
butGen();
score();
Final_GUILayout customLayout = new Final_GUILayout();
getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
getContentPane().setLayout(customLayout);
label = new JLabel("Shortest Path Finding Algorithm");
getContentPane().add(label);
cbg = new ButtonGroup();
radio_1 = new JRadioButton("radio_1", false);
cbg.add(radio_1);
getContentPane().add(radio_1);
radio_2 = new JRadioButton("radio_2", false);
cbg.add(radio_2);
getContentPane().add(radio_2);
radio_3 = new JRadioButton("radio_3", false);
cbg.add(radio_3);
getContentPane().add(radio_3);
checkbox_1 = new JCheckBox("checkbox_1");
getContentPane().add(checkbox_1);
checkbox_2 = new JCheckBox("checkbox_2");
getContentPane().add(checkbox_2);
checkbox_3 = new JCheckBox("checkbox_3");
getContentPane().add(checkbox_3);
bPanel.setLayout(new GridLayout(x,y));
mPanel.setLayout(new BorderLayout());
mPanel.add(bPanel, BorderLayout.CENTER);
scrollpane_1 = new JScrollPane(mPanel);
scrollpane_1.setViewportView(mPanel);
getContentPane().add(scrollpane_1);
combobox_1 = new JComboBox();
combobox_1.addItem("Size1");
combobox_1.addItem("Size2");
getContentPane().add(combobox_1);
DefaultListModel listModel_list_1 = new DefaultListModel();
listModel_list_1.addElement("Black");
listModel_list_1.addElement("Green");
list_1 = new JList(listModel_list_1);
sp_list_1 = new JScrollPane(list_1);
getContentPane().add(sp_list_1);
combobox_2 = new JComboBox();
combobox_2.addItem("Additional Data");
combobox_2.addItem("Additional Data2");
getContentPane().add(combobox_2);
Orange = new JButton("Orange");
getContentPane().add(Orange);
Exit = new JButton("Exit");
getContentPane().add(Exit);
for_text = new JLabel("Just For some text");
getContentPane().add(for_text);
setSize(getPreferredSize());
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private void butGen()
{
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
buttons[i][j] = new JButton(String.valueOf(i)+"x"+String.valueOf(j));
buttons[i][j].setActionCommand("button" +i +"_" +j);
buttons[i][j].addActionListener(this);
buttons[i][j].setMaximumSize(new Dimension( 20, 20));
bPanel.add(buttons[i][j]);
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().contains("button"))
{
String str = e.getActionCommand().replaceAll("button", "");
System.out.println(str);
String[] v = str.split("_");
int i = Integer.parseInt(v[0]);
int j = Integer.parseInt(v[1]);
intArray[i][j]++;
if(check[i][j]!=1){
buttons[i][j].setBackground(Color.black);
check[i][j]=1;
}
else{
buttons[i][j].setBackground(null);
check[i][j]=0;
}
System.out.println(e.getActionCommand() +" " +(i) +" " +(j));
score();
if(checkbox_1.isSelected())
{
buttons[i][j].setBackground(Color.GREEN);
}
}
}
private void score()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
buttons[i][j].setText("");
}
public static void main(String args[]) {
Final_GUI window = new Final_GUI();
window.setTitle("SHORTEST PATH FINDING ALGORITHM");
window.setBackground(Color.black);
// window.setSize(800, 300);
window.setResizable(true);
window.resize(200, 500);
window.pack();
window.show();
}
}
GUI LAYOUT
class Final_GUILayout implements LayoutManager {
public Final_GUILayout() {
}
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
Dimension dim = new Dimension(0, 0);
Insets insets = parent.getInsets();
dim.width = 1053 + insets.left + insets.right;
dim.height = 621 + insets.top + insets.bottom;
return dim;
}
public Dimension minimumLayoutSize(Container parent) {
Dimension dim = new Dimension(0,0);
return dim;
}
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
Component c;
c = parent.getComponent(0);
if (c.isVisible()) {c.setBounds(insets.left+368,insets.top+24,304,64);}
c = parent.getComponent(1);
if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+120,72,24);}
c = parent.getComponent(2);
if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+144,72,24);}
c = parent.getComponent(3);
if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+168,72,24);}
c = parent.getComponent(4);
if (c.isVisible()) {c.setBounds(insets.left+88,insets.top+120,72,24);}
c = parent.getComponent(5);
if (c.isVisible()) {c.setBounds(insets.left+88,insets.top+144,72,24);}
c = parent.getComponent(6);
if (c.isVisible()) {c.setBounds(insets.left+88,insets.top+168,72,24);}
c = parent.getComponent(7);//Panel
if (c.isVisible()) {
c.setBounds(insets.left+168,insets.top+120,704,488);
}
c = parent.getComponent(8);
if (c.isVisible()) {c.setBounds(insets.left+880,insets.top+120,160,160);}
c = parent.getComponent(9);
if (c.isVisible()) {c.setBounds(insets.left+24,insets.top+232,128,216);}
c = parent.getComponent(10);
if (c.isVisible()) {c.setBounds(insets.left+880,insets.top+296,160,216);}
c = parent.getComponent(11);
if (c.isVisible()) {c.setBounds(insets.left+904,insets.top+528,112,24);}
c = parent.getComponent(12);
if (c.isVisible()) {c.setBounds(insets.left+888,insets.top+568,144,32);}
c = parent.getComponent(13);
if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+472,120,48);}
}
}
GridLayout works by providing equal amount of space to each of the components, making each component fill each cell.
Take a look at How to use GridLayout for more details.
If you want a LayoutManager that provides you with the finest of control, but which will (unless you tell it otherwise) use the components preferred/minimum/maximum size hints, you should consider trying something like GridBagLayout instead
Take a look at How to use GridBagLayout for more details
Using GridBagLayout you can set the size of the components inside.
Another way to do it would be to create a custom button inherited from JButton class and overwrite the method SetSize(int width, int height) and setting width=height.
You can do something like this:
public class SquareButton extends JButton{
#Override
public void setSize(int width, int height) {
super.setSize(width, width);
}
}
With that, you are defining a new class of JButton that inherits all the methods from JButton, but all the instances of this SquareButton class will have the same width and height.
Maybe you don't need to do it, but I think it works. On the other hand, using this new class you don't be able to set another size relationship for your buttons.
Another way could be to create a new method in the new SquareButton class to set your desired size (or relationship width/height), instead of overwrite the SetSize(int width, int height).
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class tictac2 implements ActionListener{
static boolean blue = true; //used to keep track of turns. if true, blue's turn, else, red's turn. Blue is x, red is o
static int bWins = 0, rWins = 0;
JFrame mainWindow;
JPanel board;
JButton[] buttons;
public tictac2() {
init();
}
private void init() {
try { //Try to set the L&F to system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.toString();
System.out.println("Couln't change look and feel. Using default");
}
mainWindow = new JFrame("Tic Tac Toe!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setSize(800,600);
JMenuBar bar = new JMenuBar(); //Menu bar init
JMenu file = new JMenu("File");
JMenuItem newGame = new JMenuItem("New Game"), quitItem = new JMenuItem("Quit");
file.add(newGame);
file.addSeparator();
file.add(quitItem);
bar.add(file);
mainWindow.getContentPane().add(bar, BorderLayout.NORTH); //Menu bar done
newGameBoard(); //New Game Board
JPanel infoPane = new JPanel();
infoPane.setLayout(new GridLayout(1,3));
JLabel turn = new JLabel("Blue Player's Turn"), spacer = new JLabel(""), score = new JLabel("Blue: 0, Red: 0");
infoPane.add(turn);
infoPane.add(spacer);
infoPane.add(score);
mainWindow.getContentPane().add(infoPane,BorderLayout.SOUTH);
newGame.addActionListener(this); //Add action listeners
quitItem.addActionListener(this);
}
private void newGameBoard() {
board = new JPanel(); //Game Pane init
board.setLayout(new GridLayout(3,3));
buttons = new JButton[9];
for (int i = 0; i <9; i++){
buttons[i] = new JButton("");
buttons[i].setOpaque(true);
buttons[i].setFont(new Font("sansserif", Font.BOLD, 90));
board.add(buttons[i]);
buttons[i].addActionListener(this);
}
mainWindow.getContentPane().add(board,BorderLayout.CENTER); //Finish game pane init
}
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton j = (JButton)e.getSource();
j.setForeground(tictac2.blue ? Color.BLUE:Color.RED);
j.setText(tictac2.blue ? "X" : "O");
j.setEnabled(false);
tictac2.blue = !tictac2.blue;
}
else if (e.getSource() instanceof JMenuItem){
JMenuItem j = (JMenuItem) e.getSource();
if (j.getText().equals("Quit")) {
System.exit(0);
}
else if (j.getText().equals("New Game")) {
board.removeAll();
mainWindow.remove(board);
board = null;
for (int i = 0; i < 9; i++) {
buttons[i] = null;
}
newGameBoard();
tictac2.bWins = 0;
tictac2.rWins = 0;
tictac2.blue = true;
mainWindow.repaint(100);
}
}
}
public static void main(String[] args) {
new tictac2();
}
}
I am working on a tic tac toe program. In it I have 2 buttons. Whenever I hit new game, the newGameBoard function is supposed to run and make a new board. However, the screen just goes blank! I can't figure it out and would appreciate help. Sorry if I am not posting in the correct format, I am new here.
Thanks so much!
Move mainWindow.setVisible(true) to the end of init(). You don't want to set the frame to visible until you've added everything to it. That way it will validate and layout its subcomponents.
Another solution is to manually call mainWindow.validate() at the end of init(). That's what you have to do if you add components to the frame after making it visible.
use paintAll() or validate() on mainWindow:
mainWindow.validate();
instead of :
mainWindow.repaint(100);
validate and paintAll() as described in API doc.
Your changed code looks like:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TicTac2 implements ActionListener{
static boolean blue = true; //used to keep track of turns. if true, blue's turn, else, red's turn. Blue is x, red is o
static int bWins = 0, rWins = 0;
JFrame mainWindow;
JPanel board;
JButton[] buttons;
public TicTac2() {
init();
}
private void init() {
try { //Try to set the L&F to system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.toString();
System.out.println("Couln't change look and feel. Using default");
}
mainWindow = new JFrame("Tic Tac Toe!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setSize(800,600);
JMenuBar bar = new JMenuBar(); //Menu bar init
JMenu file = new JMenu("File");
JMenuItem newGame = new JMenuItem("New Game"), quitItem = new JMenuItem("Quit");
file.add(newGame);
file.addSeparator();
file.add(quitItem);
bar.add(file);
mainWindow.getContentPane().add(bar, BorderLayout.NORTH); //Menu bar done
newGameBoard(); //New Game Board
JPanel infoPane = new JPanel();
infoPane.setLayout(new GridLayout(1,3));
JLabel turn = new JLabel("Blue Player's Turn"), spacer = new JLabel(""), score = new JLabel("Blue: 0, Red: 0");
infoPane.add(turn);
infoPane.add(spacer);
infoPane.add(score);
mainWindow.getContentPane().add(infoPane,BorderLayout.SOUTH);
newGame.addActionListener(this); //Add action listeners
quitItem.addActionListener(this);
}
private void newGameBoard() {
board = new JPanel(); //Game Pane init
board.setLayout(new GridLayout(3,3));
buttons = new JButton[9];
for (int i = 0; i <9; i++){
buttons[i] = new JButton("");
buttons[i].setOpaque(true);
buttons[i].setFont(new Font("sansserif", Font.BOLD, 90));
board.add(buttons[i]);
buttons[i].addActionListener(this);
}
mainWindow.getContentPane().add(board,BorderLayout.CENTER); //Finish game pane init
}
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton j = (JButton)e.getSource();
j.setForeground(TicTac2.blue ? Color.BLUE:Color.RED);
j.setText(TicTac2.blue ? "X" : "O");
j.setEnabled(false);
TicTac2.blue = !TicTac2.blue;
}
else if (e.getSource() instanceof JMenuItem){
JMenuItem j = (JMenuItem) e.getSource();
if (j.getText().equals("Quit")) {
System.exit(0);
}
else if (j.getText().equals("New Game")) {
board.removeAll();
mainWindow.remove(board);
board = null;
for (int i = 0; i < 9; i++) {
buttons[i] = null;
}
newGameBoard();
TicTac2.bWins = 0;
TicTac2.rWins = 0;
TicTac2.blue = true;
mainWindow.validate();
//mainWindow.repaint();
}
}
}
public static void main(String[] args) {
new TicTac2();
}
}