There is a one J Frame in which i have put 2 panels & the Card layout is given to the both panels
by image J Frame having 2 panels one is
panel pane >>Where i an going to call panel1, panel2, panel3 where all that 3 panels have some controls like JtextField, jComboBox etc.
button pane >> in this the panel have button next & back when next is pressed (if panel pane Showing panel1 then) panel1 controls to be get validate
like that etc
code is as follow
package Code;
/**
*
* #author Rohini
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class InvoicePage extends JFrame implements ActionListener{
JLabel newInvoic, invoiceNol, invoiceNo;
JButton clinfoNext, payentryNext, termentryNext;
JButton clinfoBack, payentryBack, termentryBack;
JPanel buttonPane, clinfoBPane, payentryBPane, termentryBPane;
JPanel panelpane, client_info, invoice_entry, term_entry;
Container c = this.getContentPane();
CardLayout cardmain, cardbutton;
Font head = new Font("Times New Roman",Font.BOLD,20);
Font subheadb = new Font("Times New Roman",Font.BOLD,14);
Font subheadp = new Font("Times New Roman",Font.PLAIN,14);
public InvoicePage() throws HeadlessException {
super("Thane Bharat Sahakari Bank : New Invoice");
// initialization of variables
cardmain = new CardLayout();
cardbutton = new CardLayout();
newInvoic = new JLabel("New Invoice");
invoiceNol = new JLabel("Invoice No");
invoiceNo = new JLabel("DB Value of id");
clinfoNext = new JButton(" Next > > ");
payentryNext = new JButton(" Next > > ");
termentryNext = new JButton(" Next > > ");
clinfoBack = new JButton(" < < Back ");
payentryBack = new JButton(" < < Back ");
termentryBack = new JButton(" < < Back ");
buttonPane = new JPanel(cardbutton);
clinfoBPane = new JPanel(null);
payentryBPane = new JPanel(null);
termentryBPane = new JPanel(null);
panelpane = new JPanel(cardmain);
client_info = new clientInfo();
invoice_entry = new discription();
term_entry = new termentry();
// setting properties of variabels
panelpane.add(client_info,"Client_info");
panelpane.add(invoice_entry,"invoice_entry");
panelpane.add(term_entry,"term_entry");
buttonPane.add(clinfoBPane,"clinfoBpane");
buttonPane.add(payentryBPane,"payentryBPane");
buttonPane.add(termentryBPane,"termentryBPane");
clinfoBPane.add(clinfoBack);
clinfoBPane.add(clinfoNext);
payentryBPane.add(payentryBack);
payentryBPane.add(payentryNext);
termentryBPane.add(termentryBack);
termentryBPane.add(termentryNext);
newInvoic.setFont(head);
invoiceNol.setFont(subheadb);
invoiceNo.setFont(subheadp);
clinfoNext.addActionListener(this);
payentryNext.addActionListener(this);
termentryNext.addActionListener(this);
clinfoBack.addActionListener(this);
payentryBack.addActionListener(this);
termentryBack.addActionListener(this);
// setting Bounds
Bounds(0,0);
// Adding Components
c.add(newInvoic);
c.add(invoiceNol);
c.add(invoiceNo);
c.add(buttonPane);
c.add(panelpane);
// Form properties
cardbutton.show(buttonPane,"clinfoBpane");
cardmain.show(panelpane,"Client_info") ;
c.setLayout(null);
c.setBackground(Color.WHITE);
//clinfoBPane.setBackground(Color.WHITE);
this.setResizable(true);
this.setVisible(true);
setDefaultCloseOperation(3);
System.out.println("");
}
public void Bounds( int i, int j ){
if(i == 0){
newInvoic.setBounds(250,0,150,30);
invoiceNol.setBounds(400,30,100,25);
invoiceNo.setBounds(500,30,100,25);
buttonPane.setBounds(0,410,610,50);
panelpane.setBounds(0,50,610,350);
clinfoNext.setBounds(430,5,150,30);
clinfoBack.setBounds(25,5,150,30);
this.setSize(625,505);
this.setLocation(300,150);
}
else if(i == 1){
newInvoic.setBounds(350,0,150,30);
invoiceNol.setBounds(600,30,100,25);
invoiceNo.setBounds(700,30,100,25);
buttonPane.setBounds(0,440,830,50);
panelpane.setBounds(0,50,815,390);
if(j == 0){
payentryNext.setBounds(640,5,150,30);
payentryBack.setBounds(30,5,150,30);
}
else if(j == 1){
termentryNext.setBounds(640,5,150,30);
termentryBack.setBounds(30,5,150,30);
}
this.setSize(830,525);
this.setLocation(200,100);
}
else{
}
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == clinfoNext){
cardbutton.show(buttonPane,"payentryBPane");
cardmain.show(panelpane,"invoice_entry") ;
Bounds(1,0);
}
else if(ae.getSource() == clinfoBack){
this.dispose();
Mainfrm mf = new Mainfrm();
mf.setVisible(true);
}
else if((ae.getSource() == payentryNext)){
Bounds(1,1);
cardbutton.show(buttonPane,"termentryBPane");
cardmain.show(panelpane,"term_entry") ;
}
else if(ae.getSource() == payentryBack){
Bounds(0,0);
cardbutton.show(buttonPane,"clinfoBpane");
cardmain.show(panelpane,"Client_info") ;
}
else if(ae.getSource() == termentryBack){
cardbutton.show(buttonPane,"payentryBPane");
cardmain.show(panelpane,"invoice_entry") ;
Bounds(1,0);
}
else if(ae.getSource() == termentryNext){
JOptionPane.showConfirmDialog(this,"Are you sure that the invoice is over","Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, 0);
}
else{
}
}
public static void main(String []avi){
new InvoicePage();
}
}
yes!! i got the answer
actually the outside panel variables are need to be have a public scope
&
(see above code)
JPanel panelpane, client_info, invoice_entry, term_entry;
i have created the instance of JPanel & initiate it with the outside panel i.e
client_info = new clientInfo();
invoice_entry = new discription();
term_entry = new termentry();
instead of that the panels are doing
JPanel panelpane, client_info, invoice_entry, term_entry;
by trying this problem get solve
JPanel panelpane;
clientInfo client_info;
discription invoice_entry;
by this we can able to give the actionListner
Related
I'm trying to use sizeP for array. Make totBill equal to (array element selected) of margheritaPizza. But it does not change value at all. As if the listener is doing no good.
Is there something wrong in my ItemListener or the code as a whole? Any help will do. I'm just a 3rd year college and having troubles with this because I am self taught.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tryyy extends JFrame implements ItemListener{
final int [] margheritaPizza = {258, 450, 799, 999};
int totalBill = 0, sizeP = 0;
ButtonGroup pType = new ButtonGroup();
JRadioButton mPizza = new JRadioButton("Margherita Pizza");
ButtonGroup pSize = new ButtonGroup();
JRadioButton small = new JRadioButton("Small");
JRadioButton medium = new JRadioButton("Medium");
JRadioButton large = new JRadioButton("Large");
JRadioButton xl = new JRadioButton("Extra Large");
JLabel pizzaTypes = new JLabel ("Pizza Types");
JLabel sizes = new JLabel ("Sizes ");
JTextField totBill = new JTextField (5);
JPanel mainPanel = new JPanel();
JPanel pTypePanel = new JPanel();
JPanel pSizePanel = new JPanel();
JPanel sizePanel = new JPanel();
public tryyy(){
super ("PIZZA MENU");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(mainPanel);
add(pTypePanel);
add(sizePanel);
add(pSizePanel);
setLayout (new FlowLayout (FlowLayout.LEFT));
mainPanel.add(pizzaTypes);
pType.add(mPizza);
sizePanel.add(sizes);
pSize.add(small);
pSize.add(medium);
pSize.add(large);
pSize.add(xl);
pSizePanel.add(small);
pSizePanel.add(medium);
pSizePanel.add(large);
pSizePanel.add(xl);
add(totBill);
totBill.setText("$" + margheritaPizza[sizeP]);
totBill.setEnabled(true);
small.addItemListener(this);
medium.addItemListener(this);
large.addItemListener(this);
xl.addItemListener(this);
mainPanel.setLayout(new GridLayout(0,2));
pTypePanel.setLayout(new GridLayout(0,3));
pSizePanel.setLayout(new GridLayout(0,4));
sizePanel.setLayout(new GridLayout(1,0));
small.setSelected(true);
}
public static void main(String[] args) {
tryyy aFrame = new tryyy();
aFrame.setSize(325,500);
aFrame.setVisible(true);
}
#Override
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
int select = e.getStateChange();
if(source == small)
if (select == ItemEvent.SELECTED)
sizeP = 0;
else if (source == medium)
if (select == ItemEvent.SELECTED)
sizeP = 1;
else if (source == large)
if (select == ItemEvent.SELECTED)
sizeP = 2;
else
if (select == ItemEvent.SELECTED)
sizeP = 3;
}
}
Your code is a bit messy but your specific problem occurs because you don't change totBill text when button events occur. Try this.
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
Object source = e.getSource();
if(source == small){
sizeP = 0;
} else if (source == medium) {
sizeP = 1;
}else if (source == large) {
sizeP = 2;
}else {
sizeP = 3;
}
totBill.setText("$" + margheritaPizza[sizeP]);
}
}
A few things to consider:
You are not reassigning the correct text to the JTextField in your ItemListener. You are only changing pSize, but this will have no effect on the displayed textfield.
Always use braces, because otherwise you will run into behavior that might be unexpected. (In this case, in your if-blocks)
Class names start with uppercase letters.
You may want to revisit your layout, because right now, it is quite messy. In the end, you should not use fixed sizes for your components and let the layout manager do the work for you. ( Maybe check out the Using Layout Managers Tutorial)
For the selection of "Pizzas", maybe a JComboBox is more suitable if there will be more.
Maybe it's more fitting for you to use an ActionListener in combination with the setActionCommand() method on your Radio Buttons. (But this is probably opinion-based and will depend on your further use case)
See example below:
public class Try extends JFrame implements ActionListener {
....
....
small.setActionCommand("$" + margheritaPizza[0]);
small.addActionListener(this);
medium.setActionCommand("$" + margheritaPizza[1]);
medium.addActionListener(this);
large.setActionCommand("$" + margheritaPizza[2]);
large.addActionListener(this);
xl.setActionCommand("$" + margheritaPizza[3]);
xl.addActionListener(this);
.....
#Override
public void actionPerformed(ActionEvent e) {
totBill.setText(e.getActionCommand());
}
I have a built tictactoe in java but due to some reason the reset and the exit buttons are not working. I am unable to solve the problem. I have searched through other questions but unable to figure out the problem with my code. The code is in separate class. There is also main class that calls the object to run the program.
The array of buttons are working fine. O and X are exactly working as I want them to but the 2nd panel with the reset and the exit buttons is not working. The program is in GUI.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Frame1 implements ActionListener {
private JButton[] board;
private int turn;
private JButton reset;
private JButton exit;
public Frame1() {
turn = 1;
JFrame frm = new JFrame("Chess");
JButton reset = new JButton("Reset");
JButton exit = new JButton("Exit");
frm.setSize(300, 300);
JPanel LowerPanel = new JPanel();
LowerPanel.add(reset);
LowerPanel.add(exit);
exit.addActionListener(this);
reset.addActionListener(this);
board = new JButton[9];
JPanel CenterPanel = new JPanel();
CenterPanel.setLayout(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
board[i] = new JButton();
board[i].setFont(new Font("Arial", Font.BOLD, 72));
CenterPanel.add(board[i]);
board[i].addActionListener(this);
}
frm.add(CenterPanel, BorderLayout.CENTER);
frm.add(LowerPanel, BorderLayout.SOUTH);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == reset) {
for (int i = 0; i > 9; i++) {
board[i].setText(" ");
board[i].setEnabled(true);
turn = 1;
}
}
if (e.getSource() == exit) {
System.exit(0);
}
for (int i = 0; i < 9; i++) {
if (e.getSource() == board[i]) {
if (turn == 1) {
board[i].setText("X");
board[i].setEnabled(false);
} else {
board[i].setText("O");
board[i].setEnabled(false);
}
turn = (turn + 1) % 2;
return;
}
}
}
}
I want the buttons to work. if you could help me out to figure out the problem that would be a great help
Have a look at
JButton reset = new JButton("Reset");
JButton exit = new JButton("Exit");
You are assigning the buttons to local variables but in actionPerformed() you are accessing object properties.
Try
reset = new JButton("Reset");
exit = new JButton("Exit");
The actionPerformed method cannot access the reset and exit variables because they being instantiated as local variables by Frame1
JButton reset = new JButton("Reset");
JButton exit = new JButton("Exit");
As #Meini suggested try
reset = new JButton("Reset");
exit = new JButton("Exit");
This will set your global variables of reset and exit equal to the desired JButtons and allow the actionPerformed method to access them.
Also, fix your loop inside of the e.getSource() == reset if statement. The reset function won't work until you have addressed the i > 9 code. Since i starts at 0, the loop will not run since 0 is not greater than 9.
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();
So I am relatively new to Java and trying to create a checkers game using JButtons for the board and for the pieces. However I cannot seem to be able to remove a JButton via the ActionListener. Any advice would be appreciated.
public static void main(String[] args) {
checkersBeBitchin begin = new checkersBeBitchin();
}
public checkersBeBitchin(){
box.setLayout(new BorderLayout());
makeBoard();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(600,600);
setTitle("Checkers");
}
private void makeBoard() {
JPanel board = new JPanel();
board.setLayout(new GridLayout(8,8));
for (int i=0; i<8; i++){
for (int j=0; j<8; j++) {
squares[i][j] = new JButton();
ActionListener actionListener = new Board();
squares[i][j].addActionListener(actionListener);
if((i%2 != 0 && j%2 !=0) ||(i%2==0 && j%2 == 0) ){
squares[i][j].setBackground(Color.black);
pieceTracker[i][j]=0;
//System.out.println("Black"+i+","+j); debugging
if(i<3){
int blue = 1;
Icon piece = new ImageIcon(getClass().getResource("/resources/piece.png"));
JButton button = new JButton(piece);
//squares[i][j].setRolloverIcon("image dir") to make it prettier down the road.
squares[i][j].add(button);
pieceTracker[i][j]=blue;
ActionListener Listener = new Blue();
button.addActionListener(Listener);
}
else if (i>4){
int red=-1;
Icon piece = new ImageIcon(getClass().getResource("/resources/piece2.png"));
JButton button = new JButton(piece);
squares[i][j].add(button);
pieceTracker[i][j]=red;
ActionListener Listener = new Red();
button.addActionListener(Listener);
//squares[i][j].setRolloverSelectedIcon("/resources/piece2alt.png");
}
}
else{
squares[i][j].setBackground(Color.white);
pieceTracker[i][j]=0;
//System.out.println("White"+i+","+j); //debugging
}
board.add(squares[i][j]);
}
}
box.add(board, BorderLayout.CENTER);
}
private class Blue implements ActionListener{
public void actionPerformed (ActionEvent e){
System.out.println("You sexy Blue beast.");
Object x = e.getSource();
System.err.println(x);
squares.remove(x);
squares.remove? Should it read squares.remove(x)? Can we see the definition of squares? Is it an array? You must remove the button from the BOARD not the square, e.g. board.remove(x)
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();
}
}