gpt4 book ai didi

java - 如何让 Jbutton 填充 JPanel 以便按钮之间没有空格?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:20:16 35 4
gpt4 key购买 nike

我正在做这样的事情:

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);

产生:

enter image description here

无论我如何调整图像大小或使用 frame.size(),我都无法消除垂直间隙。一个 block 的顶部和另一个 block 的底部之间总是有空间。

enter image description here

有谁知道如何删除一个按钮底部和下一个按钮顶部之间的空格?

最佳答案

首先通过 constructorGridLayout 指定垂直(和水平)间距.

接下来,您需要去除按钮中所有不需要的内容...

jb1.setMargin(new Insets(0, 0, 0, 0));
jb1.setContentAreaFilled(false);
jb1.setFocusPainted(false);
jb1.setBorder(new EmptyBorder(0, 0, 0, 0));

那么你应该设置好了。

enter image description here

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);
}
}
}
}

更新了个别面板

面板的默认布局是 FlowLayout,您需要一些不会添加更多填充的东西,例如 BorderLayout 甚至 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);
}

关于java - 如何让 Jbutton 填充 JPanel 以便按钮之间没有空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355337/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com