Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- The buttons that the user interacts with need to be made, but
- since we don't know how many we need, they have to be named first.
- So right below the line where you create frame create the
- buttons: JButton[][] grid; The two sets of square brackets are
- there to say that the JButton's in the grid are kept in a
- two-dimensional format, if there were only one set of square
- brackets then it would simply be a line of JButton's, which
- still works, it's just easier to reference which button is being
- created or interacted with when it's two-dimensional.
- The JButton's have been named, but we still have to say how many
- buttons there are. You need to add a line of code in the
- constructor that sets the amount: grid=new JButton[width][length];
- Now that it's been determined that there will be a certain number
- of buttons, each must be created. The easiest way to do this is
- with two for loops, one for the x-axis, one for the y-axis. Inside
- the two loops we make a new button, and for ease of reference the
- example puts text inside each button so we know which button in
- the two-dimensional array is where. To create a button, inside
- the loop you need to put grid[x][y] = new JButton ("("+x+","+y+")");
- */
- /*
- LINKS:
- http://www.wikihow.com/Make-a-GUI-Grid-in-Java
- https://stackoverflow.com/questions/144892/how-to-centre-a-window-in-java
- */
- package com.samkough.main;
- import javax.swing.JFrame;
- import javax.swing.JButton;
- import java.awt.GridLayout;
- public class Grid
- {
- JFrame frame = new JFrame(); // creates frame
- JButton[][] grid; // names the grid of buttons
- public Grid(int width, int length)
- {
- // Sets the layout of frame
- frame.setLayout(new GridLayout(width, length));
- // Makes the frame close when you hit the 'x'
- // button in the top right hand corner
- grid = new JButton[width][length]; // allocate the size of grid
- for (int y = 0; y < length; y++)
- {
- for(int x = 0; x < width; x++)
- {
- grid[x][y] = new JButton("("+x+", "+y+")");
- frame.add(grid[x][y]); // adds button to grid
- }
- }
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- // Sets size of frame
- frame.setSize(800, 800);
- // Sets the frame visible
- frame.setVisible(true);
- frame.setLocationRelativeTo(null);
- frame.setTitle("GUI Grid");
- for (int y = 0; y < length; y++)
- {
- for (int x = 0; x < width; x++)
- {
- grid[x][y] = new JButton("("+x+", "+y+")");
- frame.add(grid[x][y]); // adds button to grid
- }
- }
- }
- public static void main(String args[])
- {
- new Grid(3,3); //makes new Grid with 2 parameters
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment