0

I'm writing a simple paint program in Java Swing and i'm hold by a problem of creating a grid of color buttons. I did it by creating a JPanel at the top of the window. this is what it looks like right now

I'm adding the buttons this way:

        for (String name : colors.keySet()) {
        ColorAction action = new ColorAction(name, colors.get(name));
        // above is my class that handles action of clicking button
        BufferedImage image = loadButtonImage(name);
        JButton button = new JButton (new ImageIcon(image));
        button.addActionListener(action);
        button.setContentAreaFilled(false);
        add(button);
    }

Instead of that I want it to look like a grid of these squares fitting close to each other and each square would be a color button. Right now, when I click somewhere near the color square I'm actually clicking a button and it looks awful. I'm using the GridLayout and I know that it extends all the buttons to cover the whole panel by default and it causes the problem.

Would there be a simple way to achieve my goal other than complicated code using GridBagLayout?

IFeel3
  • 167
  • 1
  • 13
  • 1
    You may prefer `JLabel`, and set the colors with `setBackground` instead of using images . – Arnaud Sep 02 '16 at 12:44

1 Answers1

0

Like @Berger mentioned, use a JLabel with setBackground. To get the squares tightly packed, on the JLabel's call setPreferredSize(new Dimension(x,x)) (x= your desired size in pixels) and call pack() on the container after all the labels are added.

Pramod CS
  • 45
  • 6
  • 1
    See [Should I avoid the use of setPreferred|maximum|minimumSize methods in java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) (Yes) instead you should override the `getPreferredSize()` methods – Frakcool Sep 02 '16 at 14:14