views:

382

answers:

2

My question related to previous post http://stackoverflow.com/questions/2374295/how-to-fill-color-in-grid-boxes-randomly

How can I get Cartesian Coordinate (x,y) of each of the boxes filled by color in Gridbaglayout. For example, if the size of the panel is 300 x 300, and the row and column is set to 5 x 5, Is there any way we will know the coordinate and not only by looking on the column and row?

http://www.freeimagehosting.net/image.php?a6ec309bd0.jpg

EDITED: complete code

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Grid extends JPanel{

    public static void main(String[] args){
        JFrame jf=new JFrame();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.add(new Grid());
        jf.pack();
        jf.setVisible(true);
    }

    public Grid (){
        setPreferredSize(new Dimension(300,300)); 
        setBackground(Color.BLACK);

        final Color BACKGROUND = Color.WHITE;  
        final Color[] colors = new Color[]
             {Color.BLACK, Color.CYAN, Color.MAGENTA, Color.YELLOW,
              Color.GREEN, Color.RED, Color.ORANGE, Color.BLUE, Color.PINK, Color.LIGHT_GRAY};

        final int ROWS = 5;
        final int COLS = 5;

        setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.weightx = 1d;
        gc.weighty = 1d;
        gc.insets = new Insets(0, 0, 1, 1);
        gc.fill = GridBagConstraints.BOTH;     

        // fill the whole panel with labels
        Label[][] label = new Label[ROWS][COLS]; 
        for( int r=0 ; r<ROWS ; r++) {
            for( int c=0 ; c<COLS ; c++) {
                Label lbl = new Label();
                lbl.setBackground(BACKGROUND);    
                gc.gridx = r;
                gc.gridy = c;
                add(lbl, gc); //add(component, constraintObj);
                label[r][c] = lbl;             
            }
        }

        // now find random fields for the colors defined in BACKGROUND
        for(Color col : colors) {
            int r, c;
            do { // make sure to find unique fields
                r = (int)Math.floor(Math.random() * ROWS);
                c = (int)Math.floor(Math.random() * COLS);
            } while(!label[r][c].getBackground().equals(BACKGROUND));
            label[r][c].setBackground(col);  
        }// end 

        int i=0;
        Component[] components = getComponents();       
        for (Component component : components) {
            i++;
            Color color = component.getBackground();
            Rectangle bounds = component.getBounds();
            System.out.println("box "+i +",coordinate= "+bounds +", Color= "+color);
        }       
    }
}

Output: I couldn't get the coordinate, all coordinates seem the same, java.awt.Rectangle[x=0,y=0,width=0,height=0]

A: 

You can get the location from the component added to the cell

Rectangle bounds = component.getBounds();

Or to go through the entire grid you could use something like this:

Component[] components = panel.getComponents();
for (Component component : components) {
    Color color = component.getBackground();
    Rectangle bounds = component.getBounds();
}
objects
Why I keep getting the same coordinate? java.awt.Rectangle[x=0,y=0,width=0,height=0]
Jessy
Has the panel been displayed ie. is it visible?
objects
Yes, the panel has been successfully displayed. The only problem is that no coordinate just --> java.awt.Rectangle[x=0,y=0,width=0,height=0] for all label...I checked it through the console output (System.out.println(bounds)
Jessy
are you running the same code as in the referenced question? If not can you post your code
objects
yes, I am running the same. I think I better post the complete code here.
Jessy
you are getting the coordinates *before* the gui has been made visible
objects
I have changed it, but it still returning 0
Jessy
works fine here
objects
A: 

How about:

GridBagLayout lay = new GridBagLayout(); 
setLayout(lay);
// Add components
add(comp1, constraints);
add(comp2, constraints);
//
GridBagConstraints c = lay.getConstraints(comp1);
System.out.println(c.gridx + ", " + c.gridy);

In your case, try this in place of System.out.println:

GridBagConstraints gbc = ((GridBagLayout) getLayout()).getConstraints(component);
System.out.println("box " + i + ",coordinate=" + gbc.gridx + " , " + gbc.gridy);

That works for me...

If you need to component position on screen, make sure the frame is visible first. For example, when I use this instead of your main(), it prints the positions properly:

public static void main(String[] args) {
    final JFrame jf = new JFrame();
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final Grid grid = new Grid();
    jf.add(grid);
    jf.pack();
    jf.addWindowListener(new WindowAdapter() {
        public void windowActivated(WindowEvent e) {
            int i = 0;
            Component[] components = grid.getComponents();
            for (Component component : components) {
                i++;
                Color color = component.getBackground();
                Rectangle bounds = component.getBounds();
                System.out.println("box " + i + ",coordinate= " + bounds
                        + ", Color= " + color);
            }
        }
    });
    jf.setVisible(true);
}

It works in all cases, not only in a WindowListener. Just make sure the frame is visible already...

Konrad Garus
Thanks for the code. But the problem is still there :-(
Jessy
See updated answer.
Konrad Garus
Thanks again, but the coordinate that I need is not in a form of row and column but in coordinate of JPanel size. e.g. if the dimension of JPanel is (300,300) how can I get the x,y e.g. (200,100), (100,10) etc..
Jessy
Ahh, in that case I think you first need to make the frame visible, then get coordinates.
Konrad Garus
I think I did --> jf.setVisible(true)...
Jessy
You did, but *after* getting coordinates. Do it in reverse order.
Konrad Garus
I have changed it, but it still returning 0 ...
Jessy
See my last edit.
Konrad Garus
THANK YOU VERY MUCH!! its WORKS!!..you are brilliant!! :-)
Jessy