JButton 2D Array

How do you add an array of JButtons to a JFrame?

Page 1 of 1

5 Replies - 11285 Views - Last Post: 26 September 2010 - 06:54 PM Rate Topic: -----

#1 x68zeppelin80x  Icon User is offline

  • D.I.C Addict

Reputation: 130
  • View blog
  • Posts: 576
  • Joined: 07-March 09

JButton 2D Array

Posted 25 September 2010 - 04:47 PM

I am trying to add an array of JButtons into a JFrame, I already have the conditions of each button.

I added an image of what the final output should look like.
Attached Image

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToe extends JFrame implements ActionListener {
    // Instance Variables
	public final int ROWS = 3;
	public final int COLS = 3;
    
    private JButton[][] button = new JButton[][]{{new JButton("0,0"), new JButton("0,1"), new JButton("0,2")}, 
    					         {new JButton("1,0"), new JButton("1,1"), new JButton("1,2")}, 
    						 {new JButton("2,0"), new JButton("2,1"), new JButton("2,2")}};
    private BorderLayout layout;
    private String letter = "";
    private int count = 0;
    private boolean win = false;
    
    public TicTacToe(){
    	// Create Window
    	super ("Tic-Tac-Toe");
    	
    	layout = new BorderLayout( 5, 5 ); // 5 pixel gaps
		setLayout( layout ); // set frame layout
		
		setSize(500,500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new BorderLayout(3,3));
    
		// Add Buttons To The Window
		add(button[3][3]);
    
		// Add The Action Listener To The Buttons
		button[3][3].addActionListener(this);
    
		// Make The Window Visible
    	setVisible(true);
    }
    
    public void actionPerformed(ActionEvent a) {
        count++;
        
        // Calculate Who's Turn It Is
        if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
        letter = "X";
        } else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10){
        letter = "O";
        }
        
        // Display X's or O's on the buttons
        if(a.getSource() == button[0][0]){
            button[0][0].setText(letter);
            button[0][0].setEnabled(false);
        } else if(a.getSource() == button[0][1]){
        	button[0][1].setText(letter);
        	button[0][1].setEnabled(false);
        } else if(a.getSource() == button[0][2]){
        	button[0][2].setText(letter);
        	button[0][2].setEnabled(false);
        } else if(a.getSource() == button[1][0]){
        	button[1][0].setText(letter);
        	button[1][0].setEnabled(false);
        } else if(a.getSource() == button[1][1]){
        	button[1][1].setText(letter);
        	button[1][1].setEnabled(false);
        } else if(a.getSource() == button[1][2]){
        	button[1][2].setText(letter);
        	button[1][2].setEnabled(false);
        } else if(a.getSource() == button[2][0]){
        	button[2][0].setText(letter);
        	button[2][0].setEnabled(false);
        } else if(a.getSource() == button[2][1]){
        	button[2][1].setText(letter);
        	button[2][1].setEnabled(false);
        } else if(a.getSource() == button[2][2]){
        	button[2][2].setText(letter);
        	button[2][2].setEnabled(false);
        }
        
        // Determine who wins
        // Horizontal wins
        	 if(button[0][0].getText() == button[0][1].getText() && button[0][1].getText() == button[0][2].getText() && button[0][0].getText() != ""){
            win = true;
        }
        else if(button[1][0].getText() == button[1][1].getText() && button[1][1].getText() == button[1][2].getText() && button[1][0].getText() != ""){
            win = true;
        }
        else if(button[2][0].getText() == button[2][1].getText() && button[2][1].getText() == button[2][2].getText() && button[2][0].getText() != ""){
            win = true;
        }
        
        // Vertical wins
        else if(button[0][0].getText() == button[1][0].getText() && button[1][0].getText() == button[2][0].getText() && button[0][0].getText() != ""){
            win = true;
        }
        else if(button[0][1].getText() == button[1][1].getText() && button[1][1].getText() == button[2][1].getText() && button[0][1].getText() != ""){
            win = true;
        }
        else if(button[0][2].getText() == button[1][2].getText() && button[1][2].getText() == button[2][2].getText() && button[0][2].getText() != ""){
            win = true;
        }
        
        // Diagonal wins
        else if(button[0][0].getText() == button[1][1].getText() && button[1][1].getText() == button[2][2].getText() && button[0][0].getText() != ""){
            win = true;
        }
        else if(button[0][2].getText() == button[1][1].getText() && button[1][1].getText() == button[2][0].getText() && button[0][2].getText() != ""){
            win = true;
        }
        else {
            win = false;
        }
        
        // Show a dialog if someone wins or the game is tie
        if(win == true){
            JOptionPane.showMessageDialog(null, letter + " WINS!");
        } else if(count == 9 && win == false){
            JOptionPane.showMessageDialog(null, "Tie Game!");
        }
    }
    
    public static void main(String[] args){
        new TicTacToe();
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: JButton 2D Array

#2 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: JButton 2D Array

Posted 25 September 2010 - 05:42 PM

Use the GridLayout layout, check this tutorial:
http://download.orac...ayout/grid.html
Was This Post Helpful? 0
  • +
  • -

#3 x68zeppelin80x  Icon User is offline

  • D.I.C Addict

Reputation: 130
  • View blog
  • Posts: 576
  • Joined: 07-March 09

Re: JButton 2D Array

Posted 25 September 2010 - 05:48 PM

View Postjapanir, on 25 September 2010 - 04:42 PM, said:

Use the GridLayout layout, check this tutorial:
http://download.orac...ayout/grid.html


It has to be a 2D array.

This post has been edited by x68zeppelin80x: 25 September 2010 - 05:49 PM

Was This Post Helpful? 0
  • +
  • -

#4 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: JButton 2D Array

Posted 25 September 2010 - 05:59 PM

What does that have to do with your requirements? Use a GridLayout(3,3) with your [3][3] array
Was This Post Helpful? 0
  • +
  • -

#5 x68zeppelin80x  Icon User is offline

  • D.I.C Addict

Reputation: 130
  • View blog
  • Posts: 576
  • Joined: 07-March 09

Re: JButton 2D Array

Posted 25 September 2010 - 06:46 PM

View PostKYA, on 25 September 2010 - 04:59 PM, said:

What does that have to do with your requirements? Use a GridLayout(3,3) with your [3][3] array


Thanks for the link man, I was a bit frustrated. :) I will try to turn the controls at the bottom (for gapList) into a "games won counter."

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToe extends JFrame implements ActionListener {
    // Instance Variables
	static final String gapList[] = {"0", "10", "15", "20"};
    final static int maxGap = 20;
    JComboBox horGapComboBox;
    JComboBox verGapComboBox;
    JButton applyButton = new JButton("Apply gaps");
    GridLayout grid = new GridLayout(3,3);
    
    private String letter = "";
    private int count = 0;
    private boolean win = false;
    
    JButton[][] button = new JButton[][]{{new JButton("0,0"), new JButton("0,1"), new JButton("0,2")}, 
			 {new JButton("1,0"), new JButton("1,1"), new JButton("1,2")}, 
			 {new JButton("2,0"), new JButton("2,1"), new JButton("2,2")}};
    
    public TicTacToe(String name) {
        super(name);
        setResizable(false);
    }
    
    public void initGaps() {
        horGapComboBox = new JComboBox(gapList);
        verGapComboBox = new JComboBox(gapList);
    }
    
    public void addComponentsToPane(final Container pane) {
        initGaps();
        final JPanel compsToExperiment = new JPanel();
        compsToExperiment.setLayout(grid);
        JPanel controls = new JPanel();
        controls.setLayout(new GridLayout(2,2)); 
	    
      //Add buttons to experiment with Grid Layout
        compsToExperiment.add(button[0][0]);
        compsToExperiment.add(button[0][1]);
        compsToExperiment.add(button[0][2]);
        compsToExperiment.add(button[1][0]);
        compsToExperiment.add(button[1][1]);
        compsToExperiment.add(button[1][2]);
        compsToExperiment.add(button[2][0]);
        compsToExperiment.add(button[2][1]);
        compsToExperiment.add(button[2][2]);
    
        //Add controls to set up horizontal and vertical gaps
        controls.add(new Label("Horizontal gap:"));
        controls.add(new Label("Vertical gap:"));
        controls.add(new Label(" "));
        controls.add(horGapComboBox);
        controls.add(verGapComboBox);
        controls.add(applyButton);

    
		// Add The Action Listener To The Buttons
        //JButton("1").addActionListener(this);
        button[0][0].addActionListener(this);
        button[0][1].addActionListener(this);
        button[0][2].addActionListener(this);
        button[1][0].addActionListener(this);
        button[1][1].addActionListener(this);
        button[1][2].addActionListener(this);
        button[2][0].addActionListener(this);
        button[2][1].addActionListener(this);
        button[2][2].addActionListener(this);

        //Process the Apply gaps button press
        applyButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            //Get the horizontal gap value
            String horGap = (String)horGapComboBox.getSelectedItem();
            //Get the vertical gap value
            String verGap = (String)verGapComboBox.getSelectedItem();
            //Set up the horizontal gap value
            grid.setHgap(Integer.parseInt(horGap));
            //Set up the vertical gap value
            grid.setVgap(Integer.parseInt(verGap));
            //Set up the layout of the buttons
            grid.layoutContainer(compsToExperiment);
        }
    });
    pane.add(compsToExperiment, BorderLayout.NORTH);
    pane.add(new JSeparator(), BorderLayout.CENTER);
    pane.add(controls, BorderLayout.SOUTH);
}


    
	public void actionPerformed(ActionEvent event) {
        count++;
        
        // Calculate Who's Turn It Is
        if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
        letter = "X";
        } else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10){
        letter = "O";
        }
        
        // Display X's or O's on the buttons
        if(event.getSource() == button[0][0]){
            button[0][0].setText(letter);
            button[0][0].setEnabled(false);
        } else if(event.getSource() == button[0][1]){
        	button[0][1].setText(letter);
        	button[0][1].setEnabled(false);
        } else if(event.getSource() == button[0][2]){
        	button[0][2].setText(letter);
        	button[0][2].setEnabled(false);
        } else if(event.getSource() == button[1][0]){
        	button[1][0].setText(letter);
        	button[1][0].setEnabled(false);
        } else if(event.getSource() == button[1][1]){
        	button[1][1].setText(letter);
        	button[1][1].setEnabled(false);
        } else if(event.getSource() == button[1][2]){
        	button[1][2].setText(letter);
        	button[1][2].setEnabled(false);
        } else if(event.getSource() == button[2][0]){
        	button[2][0].setText(letter);
        	button[2][0].setEnabled(false);
        } else if(event.getSource() == button[2][1]){
        	button[2][1].setText(letter);
        	button[2][1].setEnabled(false);
        } else if(event.getSource() == button[2][2]){
        	button[2][2].setText(letter);
        	button[2][2].setEnabled(false);
        }
        
        // Determine who wins
        // Horizontal wins
        	 if(button[0][0].getText() == button[0][1].getText() && button[0][1].getText() == button[0][2].getText() && button[0][0].getText() != ""){
            win = true;
        }
        else if(button[1][0].getText() == button[1][1].getText() && button[1][1].getText() == button[1][2].getText() && button[1][0].getText() != ""){
            win = true;
        }
        else if(button[2][0].getText() == button[2][1].getText() && button[2][1].getText() == button[2][2].getText() && button[2][0].getText() != ""){
            win = true;
        }
        
        // Vertical wins
        else if(button[0][0].getText() == button[1][0].getText() && button[1][0].getText() == button[2][0].getText() && button[0][0].getText() != ""){
            win = true;
        }
        else if(button[0][1].getText() == button[1][1].getText() && button[1][1].getText() == button[2][1].getText() && button[0][1].getText() != ""){
            win = true;
        }
        else if(button[0][2].getText() == button[1][2].getText() && button[1][2].getText() == button[2][2].getText() && button[0][2].getText() != ""){
            win = true;
        }
        
        // Diagonal wins
        else if(button[0][0].getText() == button[1][1].getText() && button[1][1].getText() == button[2][2].getText() && button[0][0].getText() != ""){
            win = true;
        }
        else if(button[0][2].getText() == button[1][1].getText() && button[1][1].getText() == button[2][0].getText() && button[0][2].getText() != ""){
            win = true;
        }
        else {
            win = false;
        }
        
        // Show a dialog if someone wins or the game is tie
        if(win == true){
            JOptionPane.showMessageDialog(null, letter + " WINS!");
        } else if(count == 9 && win == false){
            JOptionPane.showMessageDialog(null, "Tie Game!");
        }
    } 
    
    private static void createAndShowGUI() {
        //Create and set up the window.
        TicTacToe frame = new TicTacToe("Tic-Tac-Toe");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Set up the content pane.
        frame.addComponentsToPane(frame.getContentPane());
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    
    public static void main(String[] args) {
        /* Use an appropriate Look and Feel */
        try {
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        /* Turn off metal's use of bold fonts */
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}


This post has been edited by x68zeppelin80x: 25 September 2010 - 07:46 PM

Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: JButton 2D Array

Posted 26 September 2010 - 06:54 PM

Geeeezzz you make it complicated for nothing

JPanel p = new JPanel(new GridLayout(3,3));
for(int i = 0; i < button.length; i++) {
  for(int j = 0; j < button[i].length; j++) {
    p.add(button[i][j]);
  }
}


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1