首先,我是一名网页开发者和初学Java程序员。
我的老板要求我在一个应用程序中制作这个按钮:
我的自定义按钮类必须扩展JButton或BasicButtonUI以便可以被重用。
我在Stack Overflow上进行了一些研究,但由于老板时间的限制,我并没有理解答案。
![enter image description here](https://istack.dev59.com/WZKeL.webp)
我在Stack Overflow上进行了一些研究,但由于老板时间的限制,我并没有理解答案。
RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(x, y, w, h, 10, 10);
g.fill(roundedRectangle);
RoundRectangle2D roundedRectangle2 = new RoundRectangle2D.Float(x + 5, y + 5, w - 10, h - 10, 10, 10);
g.fill(roundedRectangle2);
g.drawString("Click Me", x, y);
最后,您需要在面板上添加鼠标移动监听器。监听器需要找到鼠标是否悬停在按钮上,然后重新绘制组件。
您的矩形可以转换为shape对象,并可以计算出鼠标是否在该形状内。例如:
shape.contains(x,y)
注意:你的颜色对象应该作为类级别字段保存在类中,这样可以通过鼠标悬停进行更改。
希望这有所帮助!
class ButtonRollover {
private String normalImagePath;
private String rolloverImagePath;
public ButtonRollover(String normalImagePath, String rolloverImagePath) {
this.normalImagePath = normalImagePath;
this.rolloverImagePath = rolloverImagePath;
}
public void apply(AbstractButton abstractButton) {
abstractButton.setBorderPainted(false);
abstractButton.setBackground(new Color(0, 0, 0, 0));
abstractButton.setRolloverIcon(createImageIcon(rolloverImagePath));
abstractButton.setIcon(createImageIcon(normalImagePath));
}
private ImageIcon createImageIcon(String path) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
然后使用它。例如。
public class Main extends JFrame {
public static void main(String[] args) {
Main main = new Main();
main.setBackground(Color.WHITE);
main.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
main.setSize(640, 480);
Container contentPane = main.getContentPane();
ButtonRollover buttonRollover = new ButtonRollover("/bt_normal.png",
"/bt_hover.png");
JButton btn = new JButton();
buttonRollover.apply(btn);
contentPane.add(btn);
main.setVisible(true);
}
}
只需将图像文件放在类路径中即可。
有几种方法可以实现。
1)JButton具有内置的API setIcon。您可以在此处设置ImageIcon。
2)您可以添加鼠标监听器(Mouse entered,Mouse exited),将图标更改为所需的图标。
3)制作圆形按钮 - 参考创建曲线按钮。
public class Main extends JFrame {
public static void main(String[] args) {
Main main = new Main();
main.setBackground(Color.WHITE);
main.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
main.setSize(640, 480);
Container contentPane = main.getContentPane();
ButtonRollover buttonRollover = new ButtonRollover("/bt_normal.png",
"/bt_hover.png");
JButton btn = new JButton();
buttonRollover.apply(btn);
contentPane.add(btn);
main.setVisible(true);
}
}