覆盖JButton paintComponent()不';t工作java
我想绘制我自己版本的JButton,因此我重写了覆盖JButton paintComponent()不';t工作java,java,swing,graphics,paint,jbutton,Java,Swing,Graphics,Paint,Jbutton,我想绘制我自己版本的JButton,因此我重写了paintComponent()方法,并绘制了一个渐变roundRect。这是可行的,但在那之后,我想在它上面画按钮的字符串,在编译时,我没有收到任何错误消息。但在运行时,我只看到roundRect,gradient,正如我所希望的那样(我也可以单击它),但是字符串是不可见的 这是我的密码: import javax.swing.*; import javax.swing.border.*; import java.awt.*; import ja
paintComponent()
方法,并绘制了一个渐变roundRect。这是可行的,但在那之后,我想在它上面画按钮的字符串,在编译时,我没有收到任何错误消息。但在运行时,我只看到roundRect,gradient,正如我所希望的那样(我也可以单击它),但是字符串是不可见的
这是我的密码:
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);
}
}
1) 最简单的方法是JButton的方法示例
2) 您可以根据我的评论覆盖或更改,“它对我有用……”例如:
@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();
}
只需为JButton调用
setContentAreaFilled(false)
,重写paint()
方法,最后调用paint()
方法super.paint()
如果在绘制渐变后绘制字符串会怎么样?虽然更好的方法可能是简单地用按钮的图像创建一个BuffereImage,但用它制作一个ImageIcon并设置按钮的图标。虽然我认为你需要去掉边距和边框才能成功完成这项工作。我想要一个用于制作鼠蛋白、鼠印等动画的鼠标听写器,但它成功了,现在我只想画那根线。@hovercraftfullofels我先试过了,但没有成功……它对我有效。请看下面的例子。请注意,您不能使用0,0作为文本的位置。为什么不能@HoverCraftfullOfelsbell优于带MouseListener:-)+1为什么评论super.paintComponent?