0

I'm using GridBagLayout and GridBagConstraints to create a map (grid of texture)

enter image description here

but now I want to insert an edge between different texture: I want something like this

|-----|-----|-----|
|-----|-----|-----|
|----|-|----|-----|
|-----|-----|-----|

i have tried:

c.gridx = i*5;
c.gridy = j*5;
c.gridwidth = 5;
c.gridheight = 5;

if(right != null && right != currentTexture)
    c.gridwidth--;
if(left != null && left != currentTexture){
    c.gridx = i*5+1;
    c.gridwidth--;
}

but I'm getting this:

enter image description here

I'm using the same texture, but I want them to be cut off 1 position at the edge

@ Code-Guru Thanks for your interest. I found a different way to solve my problem: that is, cutting the image with the BufferedImage. I'll post the change to my code:

ImageIcon tile = //get texture ...
Image img = tile.getImage();
BufferedImage buff = new BufferedImage(tile.getIconWidth(),tile.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = buff.createGraphics();
g.drawImage(img,0,0,null);

int w = tile.getIconWidth(), h = tile.getIconHeight();
int x = 0, y = 0;
c = new GridBagConstraints();
c.gridx = i*10;
c.gridy = j*10;
c.gridwidth = 10;
c.gridheight = 10;
c.fill = GridBagConstraints.NONE;

if(right != null && right != texture){
    //c.gridwidth--;
    c.anchor = GridBagConstraints.WEST;
    w -= (int)(res.ordinal()*2.5+2.5);
}
if(left != null && left != texture){
    //c.gridx = (i*10)+1;
    //c.gridwidth--;
    x = (int)(res.ordinal()*2.5+2.5);
    w -= (int)(res.ordinal()*2.5+2.5);
    if(c.anchor == GridBagConstraints.WEST)
        c.anchor = GridBagConstraints.CENTER;
    else
        c.anchor = GridBagConstraints.EAST;
}
BufferedImage buff2 = buff.getSubimage(x, y, w, h);
JLabel l = new JLabel(new ImageIcon(buff2));
globalMap.add(l, c);
4

1 回答 1

0

I think, you will need to start with a grid that has 5 columns per row. Then for each row, you will need to specify how many columns each cell will span.

For the first, second and fourth row in your example, the first cell spans two columns, the second cell spans two columns and the last cell only spans one column. For the third row, the first, third, and fourth cells span a single column and the second cell spans two columns.

p.s. You implement what I call "spanning" here by using the gridwidth member of your GridBagConstraints objects. You can set this with the constructor or directly.

于 2013-02-17T01:21:15.610 回答