Jump to content

Grid layout help

- - - - -

  • Please log in to reply
7 replies to this topic

#1
seryoga

seryoga

    Newbie

  • Members
  • Pip
  • 4 posts
Hi Im looking to create a
grid that looks like this

Posted Image

but im not so good working with JPanels
Ive been thinking if its easier to use a for loop
to print this out but as I said not so good with JPanels

I have this code so far:


public class View extends JPanel implements MouseListener{


// the main board at the back

public void board()

{

setBackGround(Color.gray);

setSize(500, 400);

}


public void paintComponent(Graphics g)

{


int row; // 1 - 12 rows

int col; // 1 - 10 col

int x, y; // squares size


for(row = 0; row < 12; row++)

for (col = 0; col < 10; col++)

{

g.setColor(Color.GREEN);

}


public void getBooked()  // getBooked() is a method I use from another method that should 

                                   //   keep track on the status for all these squares

{

g.setColor(Color.YELLOW);

}


public void getBought()

{

g.setColor(Color.RED);

}



these squares could have 3 color state depending on 3 things
if they are available GREEN
if they are booked YELLOW
and all else RED

these three states are depending on two buttons
Book which if you press the marked square will be painted yellow
Buy which if you press the marked square will be painted red.
So if I were to create a class for these buttons




public class Buttons extends JPanel implement MouseListener 

{

JButton bookButton;

JButton buyButton;

JButton quitButton;


/*

Set the postion and size of each component by calling its

setBounds() method

*/

//im not sure how the position is going to be yet just!


bookButton.setBounds(300, 100, 66, 33);

buyButton.setBounds(300, 150, 66, 33);

quitButton.setBounds(300,130,66,33);


}



These squares should also be
abel to mark these squares with a black frame
and mark them as if you drag the arrow on the desktop
but only the rows.
and if you let go of the mouse it should have marked those
in the same row.


As I said, im not sure how to do this and I hope
i can get some help from here!

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Here's a class which you can use for the buttons.
public class GridButton extends JButton implements ActionListener {
    private boolean selected;

    public GridButton(int number) {
        super("" + number);
        setBackground(Color.GREEN);
        selected = false;
        setBorderPainted(false);
        addActionListener(this);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.BLACK);
        if (selected) {
            g2.setStroke(new BasicStroke(10));
        }
        g2.drawRect(0, 0, getWidth(), getHeight());
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public void actionPerformed(ActionEvent e) {
        selected = !selected;
    }
}
Now Build the gui by just adding 100 gridbuttons to a jpanel with a gridlayout. And those 3 other, normal, JButtons to another JPanel.
The gridPanel is added to a jframe with a BorderLayout.CENTER constraint.
The 3buttonspanel is added to a jframe with a BorderLayout.SOUTH constraint, or NORTH.

#3
seryoga

seryoga

    Newbie

  • Members
  • Pip
  • 4 posts
Hi oxano
than you for the reply
How do add buttons in that way
and form the square as in the center with button

do you use as I thought
row and column and build from
that by adding amount of buttons int columns
and int rows?

example I want to create a grid with 10 columns and 10 rows?

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
public class Gui extends JFrame(){

  public Gui(){

    super("frameTitle");

    pack(); //let java handle the size

  }

  public static void main(String[] args){

    Gui gui = new Gui();

    gui.setVisible(true);

  }

}
This will create your default frame.

Then you create a grid. You create the grid on a JPanel, and then add stuff to the JPanel. In the end you add the JPanel to the frame.

JPanel gridPanel = new JPanel( new GridLayout(10,0) );

for(int i=0 ; i<10 ; i++){

  for(int j=0 ; j<10 ; j++){

    gridPanel.add(new JButton("buttonText) );

  }

}

frame.add(gridPanel);

This code creates a jpanel with a grid, with 10 rows, columns is 0(undefined) so java will add a column if it needs one.

So, combining the 2 code snippets:

public class Gui extends JFrame(){

  public Gui(){

    super("frameTitle");


    JPanel gridPanel = new JPanel( new GridLayout(10,0) );

    for(int i=0 ; i<10 ; i++){

      for(int j=0 ; j<10 ; j++){

        gridPanel.add(new JButton("buttonText) );

      }

    }

    add(gridPanel);


    pack(); //let java handle the size

  }


  public static void main(String[] args){

    Gui gui = new Gui();

    gui.setVisible(true);

  }

}
This are just buttons. There's no code behind them, it won't do anything. The gridButton i provided can be used just like the jbutton (except that it doesn't take a string as parameter, but an integer. As you display a number anyway) But it has a little bit of code which enables you to select buttons, and you can ask the button if it's selected or not using .isSelected(); And setSelected(false); to remove the selection.

#5
seryoga

seryoga

    Newbie

  • Members
  • Pip
  • 4 posts
Okey so ive been thinking a little about this
status class that should store how these buttons are booked or not or sold


public class Status{

private String seatNumber;

public static boolean BOOKED, SOLD = false;

public static boolean AVAILABLE = true;

private int row = 12;

private int col = 10;


public void Seat(int row, int col)  // this should check which coordinates on this grid as available/ booked or sold

{


public boolean isBooked()

{

return BOOKED;

}


public boolean isAvailable()

{

return AILABLE;

}

public boolean isSold()

{

return SOLD;

}


how can I look by the x and y
coordinate in that grid and using this class
to store them and then print a main
method that uses both these classes

im not sure on how this class
can check the different buttons.

but isnt easier to make the grid
as squares instead of buttons
how can I make that?

this class is the controller that if you mark one
if the squares and hit the book button it shall
change color


public class Controller extends JFrame implements MouseListener {

private JLabel theater;

private JButton quit;

private JButton book;

private JButton sell;

private JComboBox date;


public void Controller()

{

setLayout(null);

setSize(100,200);

film = new JLabel("The Dark Knight");

quit = new JButton("Quit");

book = new JButton("Book");

sell = new JButton("Buy");


film.setBounds(60,30,120,30);

quit.setBounds(------);

quit.addMouseListener(this);

//should quit the whole program


book.setBounds(----);

book.addMouseListener(

// if you have marked a seat and hit this button it shall be painted yellow and stored in the status class


sell.setBounds();

sell.addMouseListener() 

// if you marked a seat and hit this button it shall be painted red and stored in the status class


add(quit);

add(book);

add(sell);

add(film);

how these should interact I have a hard time figure out.

these three classes shall be painted up by a main method

#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java

Quote

but isnt easier to make the grid
as squares instead of buttons
how can I make that?
So.. you want to manually draw the lines for a grid?

#7
seryoga

seryoga

    Newbie

  • Members
  • Pip
  • 4 posts
No the grids method seems to be the best way
thank you but how can I make that with the buttons
at the buttom and change color if you mark one of the buttons
and hit example book?

Is possible to also store that status on that specific place
in a Class Status thats how I wonder with buttons
something like

public class Status {

private int row = 12;

private int col = 10;

private boolean BOOKED, BOUGHT = false;

private boolean AVAILABLE = true;


public void getBooked(int row, int col)

{

return BOOKED;


}


public void getAvailable(int row, int col)

{

return AVAILABLE;

}


public void getBought(int row, int col)

{

return BOUGHT;

}




this class to keep track on
so you cant book the place once more
and keep status on all with a postion
int row and int col?

#8
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
I made the class Room:

public class Room {

    private Seat[][] seats;


    public Room() {

        seats = new Seat[10][10];

        for (int i = 0; i < 10; i++) {

            for (int j = 0; j < 10; j++) {

                seats[i][j] = new Seat(i, j);

            }

        }

    }


    public Seat[][] getSeats() {

        return seats;

    }


    public void book(int x, int y) {

        if (seats[x][y].getStatus() == AVAILABLE) {

            seats[x][y].book();

        }

    }


    public void buy(int x, int y) {

        if (seats[x][y].getStatus() == BOOKED) {

            seats[x][y].buy();

        }

    }    

}
Pretty simple i think. A room has seats (100), you can get the seats (needed for the GUI), you can book a seat at a certain position, and you can buy a seat.

The Seat class is also very simple:

public class Seat {

    private Status status;

    private int x, y;


    public Seat(int x, int y) {

        status = AVAILABLE;

        this.x = x;

        this.y = y;

    }


    public void book() {

        if (status == AVAILABLE) {

            status = BOOKED;

        }

    }


    public void buy() {

        if (status == BOOKED) {

            status = SOLD;

        }

    }


    public Status getStatus() {

        return status;

    }


    public int getX() {

        return x;

    }


    public int getY() {

        return y;

    }

}


It has a position (x,y). And a status(available, booked, sold). You can buy a seat, and book a seat. Before buying i check if it's booked, before booking i chekc if it's available.
+ some getters. getX and getY actually isn't used...

The status class(enum)

public enum Status {

    AVAILABLE,

    BOOKED,

    SOLD

}

..not much to say..

Thus far the model.
Gui:
GridButton:

public class GridButton extends JButton implements ActionListener {

    private boolean selected;     


    public GridButton(String text) {

        super(text);

        setBackground(Color.GREEN);

        selected = false;

        setBorderPainted(false);

        setFocusable(false);

        addActionListener(this);

    }


    @Override

    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;

        g2.setColor(Color.BLACK);

        if (selected) {

            g2.setStroke(new BasicStroke(5));

        }

        g2.drawRect(0, 0, getWidth(), getHeight());

    }


    public boolean isSelected() {

        return selected;

    }


    public void setSelected(boolean selected) {

        this.selected = selected;

    }


    public void actionPerformed(ActionEvent e) {

        selected = !selected;

    }

}

A very simple button-class, it has a boolean selected to know if the button is selected or not. The constructor takes a string that string is the text on the button.
In this case it's a number. I do setBorderPainted(false); AND setFocusable(false); So it looks less like a button.
It has methods to get and set the selected state (isSelected(), and setSelected() ) . Upon clicking it will change its selection state automatically (actionperformed method)
Then a small paintComponent method to draw a selection box around it if it's selected.

The main frame:


import gridHelp.model.Room;

import gridHelp.model.Seat;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;



public class View extends JFrame {

    private GridButton[][] buttons;

    private Room room;


    public View() {

       >Constructor..see further<

    }


    public void book() {

        for (int i = 0; i < buttons.length; i++) {

            for (int j = 0; j < buttons[i].length; j++) {

                if (buttons[i][j].isSelected()) {

                    room.book(i, j);

                    buttons[i][j].setSelected(false);

                }

            }

        }

        update(room.getSeats());

    }


    public void buy() {

        for (int i = 0; i < buttons.length; i++) {

            for (int j = 0; j < buttons[i].length; j++) {

                if (buttons[i][j].isSelected()) {

                    room.buy(i, j);

                    buttons[i][j].setSelected(false);

                }

            }

        }

        update(room.getSeats());

    }


    public void update(Seat[][] seats) {

        for (int i = 0; i < seats.length; i++) {

            for (int j = 0; j < seats[i].length; j++) {

                switch (seats[i][j].getStatus()) {

                    case AVAILABLE:

                        buttons[i][j].setBackground(Color.GREEN);

                        break;

                    case BOOKED:

                        buttons[i][j].setBackground(Color.YELLOW);

                        break;

                    case SOLD:

                        buttons[i][j].setBackground(Color.RED);

                        break;

                }

            }

        }

        repaint();

    }   

}

It has a book and buy method (when you click the book and buy button).
It will loop trough all the buttons, check if it's selected (isSelected() ) and then book or buy it.
Then deselect all buttons and call the update(..) method.
The update method will loop trough all the seats of the room, and dependant of the status, change the color of the button. Then repaint itself. Done.

I think that, even though it may be a lot of code. It's very simple code with easy methods.
.. And it all makes sence:
a room that has seats and the buy and book methods take an x and y parameter
a seat that has a status(available, booked, sold) also with a buy and book method.
a frame that has buttons, a book and buy method which will invoke book and buy on all the seats that correspond to each button that was selected.
buttons that can be selected, and upon selecting it has a black, broader border.


... and then there's the constructor of the frame... it's always ugly code :P

super();

        room = new Room();


        buttons = new GridButton[10][10];

        JPanel centerPanel = new JPanel(new GridLayout(10, 0));

        JPanel southPanel = new JPanel(new GridLayout(0, 3));


        for (int i = 0; i < 10; i++) {

            for (int j = 0; j < 10; j++) {

                GridButton gridbutton = new GridButton(""+ ((i * 10) + j + 1));

                buttons[i][j] = gridbutton;

                centerPanel.add(gridbutton);

            }

        }


        JButton bookButton = new JButton("book");

        bookButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                book();

            }

        });


        JButton buyButton = new JButton("buy");

        buyButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                buy();

            }

        });


        JButton quitButton = new JButton("quit");

        quitButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                dispose();

                System.exit(0);

            }

        });

        southPanel.add(bookButton);

        southPanel.add(buyButton);

        southPanel.add(quitButton);


        add(centerPanel, BorderLayout.CENTER);

        add(southPanel, BorderLayout.SOUTH);

        pack();






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users