覆盖JButton paintComponent()不起作用

我想绘制自己的JButton版本,所以我重写了paintComponent()方法,并画了一个渐变roundRect。 这可行,但在那之后,我想在它上面绘制Button的String,并且在编译时,我没有收到任何错误消息。 但是在运行时,我只看到了roundRect,gradient,就像我想要的那样(我也可以点击它),但是String是不可见的……

这是我的代码:

 import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; public class JIconButton extends JButton implements MouseListener { private boolean mouseInside; public JIconButton(String file, String text) { super(text, new ImageIcon(file)); setBorder(new LineBorder(Color.LIGHT_GRAY, 0, true)); setContentAreaFilled(false); setFocusPainted(false); addMouseListener(this); setVisible(true); } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g.create(); g2.setPaint(Color.BLACK); g2.drawString(getText(), 0, 0); g2.setPaint(new GradientPaint( new Point(0, 0), Color.WHITE, new Point(0, getHeight()), Color.PINK.darker())); g2.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30); g2.dispose(); //super.paintComponent(g); } } 

根据我的评论,“它对我有用……”
例如:

  @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(new GradientPaint(new Point(0, 0), Color.WHITE, new Point(0, getHeight()), Color.PINK.darker())); g2.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30); g2.setPaint(Color.BLACK); g2.drawString(getText(), 30, 12); g2.dispose(); // super.paintComponent(g); } 

你必须做:

 g2.drawString(getText(), 0, 10); 

字符串坐标的y必须大于0 ,因为它是基线的起点而不是框左上角的点。 最终代码:

 @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(new GradientPaint( new Point(0, 0), Color.WHITE, new Point(0, getHeight()), color.PINK.darker())); g2.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30); // The drawString(string) must be put after the setPaint(gradient) g2.setPaint(Color.BLACK); g2.drawString(getText(), 0, 10); g2.dispose(); } 

1)最简单的方法是JButton的方法JButton(String text,Icon icon) 这里的例子

2)您可以覆盖XxxButtonUI ,或更改GradientButton