Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove space between ImageIcons in GridLayout (Java)

I am making a java game reliant on having tiles in a grid. I have used ImageIcon, along with JLabel in a GridLayout. I have set both the vertical and horizontal to zero when I created the GridLayout, and all images used have no extra space in them.

What is the best way to fix this?

//Sets up the game canvas
private void setUpCanvasPanel(){
    //Adjusts the panel settings
    canvasPanel.setLayout(new GridLayout(Main.diameter, Main.diameter, 0 ,0));

    //Adds panel to masterpanel
    resetc();
    c.gridx = 0;
    c.gridy = 1;
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;

    masterPanel.add(canvasPanel, c);
}

//Renders the game canvas
public void renderCanvas(){
    ImageIcon[] iconArray = new ImageIcon[Main.diameter * Main.diameter];
    JLabel[] labelArray = new JLabel[Main.diameter * Main.diameter];
    int count = 0;

    for(int i = 0; i < Main.diameter; i ++){
        for(int j = 0; j < Main.diameter; j ++){
            iconArray[count] = new ImageIcon("textures/" + Main.renderer.renderedWorld[i][j] + ".jpeg"); 
            labelArray[count] = new JLabel(iconArray[count]);
            canvasPanel.add(labelArray[count]);

            count ++;
        }
    }

    count = 0;

    canvasPanel.setVisible(true);
}

enter image description here

EDIT: For note, in this instance Main.diameter is set to 100.

like image 994
Primus Avatar asked Feb 10 '23 15:02

Primus


1 Answers

The problem is GridLayout will provide equal amount of space to all the components, dividing the available space by the number of rows/columns, so as the available space increases, so will each individual cell, but the components are maintained at their preferred size.

You could...

Use something like WrapLayout which will automatically components down by lines as the horizontal space is reduced

WrapLayout

You could...

Use a GridBagLayout, which would allow you to maintain the rows/columns, but have more control over the available space which the individual components occupy

GridBagLayout

...Using GridBagConstraints#insets to add spacing between the components

Insets

...add GridBagConstraints#weightx, GridBagConstraints#weightx and GridBagConstraints#fill to fill the available space

Fill

Take a look at Laying Out Components Within a Container, How to Use GridLayout and How to Use GridBagLayout for more details

...And some test code...

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TexturePane extends JPanel {

        public TexturePane(Color background) {
            setBackground(background);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(20, 20);
        }

    }

    public class TestPane extends JPanel {

        public TestPane() {
            int total = 10 * 10;
            Color[] rowColors = new Color[]{
                Color.RED,
                Color.GREEN,
                Color.BLUE,
                Color.CYAN,
                Color.MAGENTA,
                Color.ORANGE,
                Color.PINK,
                Color.YELLOW,
                Color.DARK_GRAY,
                Color.GRAY,
            };
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(1, 1, 1, 1);
            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.fill = GridBagConstraints.BOTH;
            for (int row = 0; row < 10; row++) {
                gbc.gridy = row;
                for (int col = 0; col < 10; col++) {
                    gbc.gridx = col;
                    double progress = (row * 10) + col;
                    Color color = blend(Color.BLACK, rowColors[row], col / 10d);
                    add(new TexturePane(color), gbc);
                }
            }
        }

    }
    public static Color blend(Color color1, Color color2, double ratio) {
        float r = (float) ratio;
        float ir = (float) 1.0 - r;

        float rgb1[] = new float[3];
        float rgb2[] = new float[3];

        color1.getColorComponents(rgb1);
        color2.getColorComponents(rgb2);

        float red = rgb1[0] * r + rgb2[0] * ir;
        float green = rgb1[1] * r + rgb2[1] * ir;
        float blue = rgb1[2] * r + rgb2[2] * ir;

        if (red < 0) red = 0;
        else if (red > 255) red = 255;
        if (green < 0) green = 0;
        else if (green > 255) green = 255;
        if (blue < 0) blue = 0;
        else if (blue > 255) blue = 255;

        Color color = null;
        try {

            color = new Color(red, green, blue);

        } catch (IllegalArgumentException exp) {

            NumberFormat nf = NumberFormat.getNumberInstance();
            System.out.println(nf.format(red) + "; " + nf.format(green) + "; " + nf.format(blue));

        }
        return color;
    }

}

You'll have to include WrapLayout yourself and remove the references to GridBagLayout from the above code, but that's all I used

like image 129
MadProgrammer Avatar answered Feb 12 '23 07:02

MadProgrammer