我想制作一个透明的按钮,直到用户用鼠标悬停在它上面,所以我创建了自己的类,它扩展了JButton。我测试了它,它确实使按钮透明,并确实检测到用户在它上面悬停时,但它后来不会使它变得不透明。我需要使用此代码更改什么?
import javax.swing.*;
import java.awt.event.*;
public class TransparentButton extends JButton {
boolean opaque = false, areaFilled = false, borderPainted = false;
public TransparentButton(Icon icon) {
super(icon);
initialise();
}
public TransparentButton(String text) {
super(text);
initialise();
}
private void initialise() {
super.setOpaque(opaque);
super.setContentAreaFilled(areaFilled);
super.setBorderPainted(borderPainted);
super.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
opaque = true;
areaFilled = true;
borderPainted = true;
}
public void mouseExited(MouseEvent e) {
opaque = false;
areaFilled = false;
borderPainted = false;
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
}
}
答案 0 :(得分:1)
import javax.swing.*;
import java.awt.event.*;
public class TransparentButton extends JButton {
boolean opaque = false, areaFilled = false, borderPainted = false;
public TransparentButton(Icon icon) {
super(icon);
initialise();
}
public TransparentButton(String text) {
super(text);
initialise();
}
private void initialise() {
super.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
opaque = true;
areaFilled = true;
borderPainted = true;
reset();
}
public void mouseExited(MouseEvent e) {
opaque = false;
areaFilled = false;
borderPainted = false;
reset();
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
}
private void reset() {
super.setOpaque(opaque);
super.setContentAreaFilled(areaFilled);
super.setBorderPainted(borderPainted);
}
}
答案 1 :(得分:1)
boolean opaque = false,areaFilled = false,borderPainted = false; 字段opaque,areaFilled和borderPainted是calss的局部变量。 改变它不会影响晚餐班!
setOpaque,setContentAreaFilled和setBorderPainted方法背后有很多逻辑 你应该用它
答案 2 :(得分:1)
您需要添加MouseMotionListener代码,但最好是ChangeListener
您必须更改AlphaComposite的值
答案 3 :(得分:0)
设置变量是不够的。您还必须在按钮上调用适当的方法:
public void mouseEntered(MouseEvent e) {
super.setOpaque(true);
super.setContentAreaFilled(true);
super.setBorderPainted(true);
}
public void mouseExited(MouseEvent e) {
super.setOpaque(false);
super.setContentAreaFilled(false);
super.setBorderPainted(false);
}
P.S:我没有测试过。但这似乎在逻辑上很明显enoguh