Reputation: 12205
I'm doing something like this:
JFrame frame = new JFrame();
frame.setSize(216, 272);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
GridLayout gl = new GridLayout(10, 2);
jp.setLayout(gl);
//this an an 18x18 png
Image img = ImageIO.read(new File("C:\\Users\\Josh\\workspace\\src\\red.png"));
for(int ii=0; ii < 20; ii++)
{
JPanel buttonPanel = new JPanel();
JButton jb1 = new JButton(new ImageIcon(img));
jb1.setBorder(BorderFactory.createEmptyBorder());
buttonPanel.add(jb1);
jp.add(buttonPanel);
}
frame.add(jp);
Which produces:
No matter how I resize the image or use a frame.size() I can't get the vertical gaps to go away. There is always space between the top of one block and the bottom of another.
Does anyone know how I can remove the spaces between the bottom of one button and the top of the next button?
Upvotes: 3
Views: 4209
Reputation: 347204
Start by specifying the vertical (and horizontial) spacing for GridLayout
via the constructor.
Next, you need to strip away all the unrequired content of the buttons...
jb1.setMargin(new Insets(0, 0, 0, 0));
jb1.setContentAreaFilled(false);
jb1.setFocusPainted(false);
jb1.setBorder(new EmptyBorder(0, 0, 0, 0));
Then you should be set.
public class TestButtons {
public static void main(String[] args) {
new TestButtons();
}
public TestButtons() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ButtonPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ButtonPane extends JPanel {
public ButtonPane() {
setLayout(new GridLayout(10, 2, 0, 0));
BufferedImage img = new BufferedImage(18, 18, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, 18, 18);
g2d.dispose();
for (int ii = 0; ii < 20; ii++) {
JButton jb1 = new JButton(new ImageIcon(img));
jb1.setMargin(new Insets(0, 0, 0, 0));
// jb1.setBorderPainted(false);
jb1.setContentAreaFilled(false);
jb1.setFocusPainted(false);
jb1.setBorder(new EmptyBorder(0, 0, 0, 0));
add(jb1);
}
}
}
}
Updated with individual panels
The default layout for a panel is FlowLayout
, you need something that isn't going to add more padding, something like BorderLayout
or even GridBagLayout
for (int ii = 0; ii < 20; ii++) {
JButton jb1 = new JButton(new ImageIcon(img));
JPanel panel = new JPanel(new BorderLayout());
jb1.setMargin(new Insets(0, 0, 0, 0));
jb1.setContentAreaFilled(false);
jb1.setFocusPainted(false);
jb1.setBorder(new EmptyBorder(0, 0, 0, 0));
panel.add(jb1);
add(panel);
}
Upvotes: 5