如何填充JButton?设置背景色无法修改按钮填充区域的问题
我想要填充JButton,但网上找到的方法都是修改背景色和前景色,这并非我需要的效果。我发现setBackground仅能修改按钮后方的颜色,setForeground仅能修改按钮文本颜色(若存在文本),而按钮的主体填充区域始终为白色。我不想修改背景色,而是想修改按钮的白色填充区域,请问是否有实现方法?
我的GameOfLife类代码:
public GameOfLife () { frame = new JFrame("2 player Game of Life"); frame.setSize(505, 533); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(false); buttons = new JButton[10][10]; for (int i = 0; i < buttons.length; i++) { for (int j = 0; j < buttons[i].length; j++) { buttons[i][j] = new JButton(); buttons[i][j].setBounds(i*50+2, j*50+2, 50, 50); frame.add(buttons[i][j]); buttons[i][j].addActionListener(this); //buttons[i][j].setBackground(Color.black); buttons[i][j].setForeground(Color.BLUE); buttons[i][j].setOpaque(true); } } frame.setLayout(null); frame.setVisible(true); }
解决方案
方法1:重写ButtonUI自定义绘制
Swing按钮的外观由UI组件控制,默认UI会绘制白色主体。你可以通过重写BasicButtonUI的paint方法,直接绘制想要的填充颜色:
buttons[i][j].setUI(new BasicButtonUI() { @Override public void paint(Graphics g, JComponent c) { JButton btn = (JButton) c; // 设置填充颜色,比如黑色 g.setColor(Color.BLACK); // 绘制主体区域,留出1px边框空间避免覆盖边框 g.fillRect(1, 1, btn.getWidth() - 2, btn.getHeight() - 2); // 调用父类方法绘制边框、文本等其他元素 super.paint(g, c); } });
方法2:关闭边框+设置背景色
其实默认UI下,按钮的白色主体是边框内部的区域,关闭边框后,设置的背景色就会覆盖整个按钮区域:
buttons[i][j].setBorderPainted(false); buttons[i][j].setOpaque(true); buttons[i][j].setBackground(Color.BLACK);
这样按钮就会完全变成你设置的背景色,替代原来的白色主体。
方法3:用纯色Icon填充按钮
创建一个自定义的纯色Icon,设置为按钮的图标,让它填充整个按钮区域:
buttons[i][j].setIcon(new Icon() { @Override public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(Color.BLACK); g.fillRect(x, y, getIconWidth(), getIconHeight()); } @Override public int getIconWidth() { return buttons[i][j].getWidth(); } @Override public int getIconHeight() { return buttons[i][j].getHeight(); } }); // 可选:关闭边框让样式更统一 buttons[i][j].setBorderPainted(false);
内容的提问来源于stack exchange,提问作者mocoloco
相关产品推荐
相关产品推荐

