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)
Related
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 new to java and I am making a Whack a Mole game using a JFrame with JButtons. Currently, I have a 5x5 grid of buttons and that is as far as I got. I am having 3 of the buttons be X (to represent the mole) and 22 be O (to represent an empty hole). I would like for the buttons values to shuffle so that every 2 seconds the values are randomized. How might I go about doing this? Sorry for being such a novice, I literally started java a couple weeks back and JFrames still confuse me lol. Here is the code I currently have, thanks;
import javax.swing.*;
import java.awt.*;
public class Whack_A_Mole extends JFrame {
JButton[][] square = new JButton[5][5];
JButton button1, button2;
static JLabel label = new JLabel();
Whack_A_Mole() {
super("Whack a Mole");
JPanel p = new JPanel(new GridLayout(5,5));
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
square[i][j] = new JButton();
p.add(square[i][j]);
}
}
add(p, BorderLayout.CENTER);
p = new JPanel(new GridLayout(1,2));
setSize(600, 600);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
new Whack_A_Mole();
}
}
If you put the objects in an ArrayList, you can use the shuffle() method to shuffle their order. As to timing, either use Thread.sleep(millisecondsAmt) or a Timer. I prefer the util.Timer, especially when the action repeats indefinitely or for many repetitions.
Create a thread that will add update function into queue every 2 seconds.
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.util.Random;
public class Wack_A_Mole extends JFrame {
JButton[][] square = new JButton[5][5];
JButton button1, button2;
static JLabel label = new JLabel();
private Thread updateWoker;
Whack_A_Mole() {
super("Whack a Mole");
JPanel p = new JPanel(new GridLayout(5,5));
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
square[i][j] = new JButton();
p.add(square[i][j]);
}
}
add(p, BorderLayout.CENTER);
p = new JPanel(new GridLayout(1,2));
setSize(600, 600);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
void start(){
updateWoker=new Thread(new Runnable(){
public void run(){
Runnable r=new Runnable(){
public void run() {
buttonUpdate(); // call buttonUpdate every two seconds
}
};
while (true){
javax.swing.SwingUtilities.invokeLater(r);
try{Thread.sleep(2000);} catch (InterruptedException ex) {
return;
}
}
}
}
);
updateWoker.start();
}
public void buttonUpdate(){ // random update can be done in this function
Random r=new Random();
for(int i=0;i<square.length;i++){
for(int j=0;j<square[i].length;j++){
if(r.nextInt() %2==0)
square[i][j].setText("O");
else
square[i][j].setText("X");
}
}
}
public void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) { // making sure to stop the thread after gui closes
if(updateWoker.isAlive()){
updateWoker.interrupt();
}
dispose();
}
}
public static void main(String[] args) throws InterruptedException {
final Whack_A_Mole theTest=new Whack_A_Mole();
theTest.start();
}
}
I want to have a for loop, that can implement and add a specified number of JButtons the one after the other. I was trying to implement it and this is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ArrayForm extends JFrame implements ActionListener
{
JPanel numPanel = new JPanel();
JPanel opPanel = new JPanel();
JTextField textField = new JTextField(25);
JButton [] buttons = new JButton[10];
JButton [] OPbuttons = new JButton[6];
String num="";
String [] operation = {"+","-","*","/","=","C"};
public static void main(String[] args)
{ArrayForm fobject = new ArrayForm();}
public ArrayForm()
{
setLayout(new FlowLayout());
setSize(400,300);
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
numPanel.setPreferredSize(new Dimension(180,150));
numPanel.setLayout(new FlowLayout());
opPanel.setPreferredSize(new Dimension(200,70));
opPanel.setLayout(new FlowLayout());
for (int i = 0; i<10; i++)
{
//The code in here
}
for (int i = 0; i<6; i++)
{
//The code in here
}
add(textField);
this.textField.setEditable(false);
add(numPanel);
add(opPanel);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
}
}
Can you please help me with for loop part? where the first one is buttons array, and the second one is for OPbuttons array.
Your for loop part might be as follows:
for (int i = 0; i<10; i++)
{
buttons[i] = new JButton(""+i);
numPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
for (int i = 0; i<6; i++)
{
OPbuttons[i] = new JButton(operation[i]);
opPanel.add(OPbuttons[i]);
OPbuttons[i].addActionListener(this);
}
What i have understood, is that you are trying to add the buttons of a calculator automatically, within two different panels...
NB: don't forget to add the code for your Action Listener.
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
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();
}
}