Override JButton paintComponent() doesn't work java

 ̄綄美尐妖づ 提交于 2019-12-06 02:55:43

As per my comment, "it worked for me...."
For example:

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

You have to do:

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

the y of the string coordinate must be greater than 0, because is the starting point of the baseline and not the point of the upper left corner of a box. The final code:

@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();
}
mKorbel

1) easiest way would be JButton's methods JButton(String text, Icon icon) example here

2) you can override XxxButtonUI, or change GradientButton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!