我已经多次看到Java Swing GUIs按钮看起来像图像,直到鼠标滚过它们。他们似乎没有填充他们的内容区域。当鼠标滚过它们时,内容区域会填充,但按钮看起来好像鼠标没有悬停在它上面。这方面的一个例子是用于激活SwingSet2中每个演示的按钮工具栏。
这种效果怎么可能?
编辑:以下图片说明了我的问题:
默认状态
悬停状态
点击(有效)状态
这些都是在Vista上使用Window Look& Feel。这些图像是从SwingSet2演示工具栏中捕获的。
谢谢!
答案 0 :(得分:1)
这是一种简单的方法。此代码将向JButton添加一个已调整大小的图像,并删除按钮的边框和填充区域,除非鼠标位于按钮上。
public JPanel hooverImages(){
JPanel panel;
ImageIcon icon;
Image img;
JButton button;
String name = "image"
icon = new ImageIcon(getClass().getResource("/gui/resources/"
+ name+".png"));
img = icon.getImage();
button = new JButton(new ImageIcon(img.getScaledInstance(30, 30
, Image.SCALE_SMOOTH))); //adds resized image to button.
button.setBounds(20, 0, 40, 40);
button.setContentAreaFilled(false); //this is the piece of code you needed
button.addMouseListener(new MouseAdapter(){
@Override
public void mouseEntered(MouseEvent event){
JButton buton = (JButton)event.getSource();
buton.setContentAreaFilled(true); //when hoovered it will show borders and fill area.
}
@Override
public void mouseExited(MouseEvent event){
JButton buton = (JButton)event.getSource();
buton.setContentAreaFilled(false); //when mouse is not on button then it will look the same.
}
});
panel.add(button);
return panel;
}
答案 1 :(得分:0)
我玩过任何一段时间已经有一段时间了,但我相信它来自于继承自AbstractButton的JButton的setRolloverIcon。我相信你也必须启用翻转。
答案 2 :(得分:0)
<强>更新强> 这就是你想要的。 Flat Button
我知道它是Windows L&amp; F,你可以在SwingSet2中设置,但这并不意味着SwingSet2没有取代一些底层UI处理程序以获得他们所需的效果以及使用Windows L&amp; F。
原始回复
没有图片的粗糙版本。更改边框和颜色以满足您的需求。
public static void main(String[] args) {
JFrame frame = new JFrame("Example");
frame.setLayout(null);
frame.setSize(800, 600);
JButton button = new JButton("Hover Me");
button.setBackground(Color.LIGHT_GRAY);
button.setBounds(10, 10, 60, 40);
button.setBorder(BorderFactory.createEmptyBorder());
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
JButton button = (JButton) e.getComponent();
button.setBackground(Color.LIGHT_GRAY.brighter());
button.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
}
@Override
public void mouseExited(MouseEvent e) {
JButton button = (JButton) e.getComponent();
button.setBackground(Color.LIGHT_GRAY);
button.setBorder(BorderFactory.createEmptyBorder());
}
});
frame.add(button);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
答案 3 :(得分:0)
如果将任何带有图标的JToggleButton添加到JToolBar,它的行为将如下所示。如果您不希望它位于工具栏中,请尝试setBorderPainted(false)
。我知道它适用于GTK LaF,尝试使用windows。
答案 4 :(得分:0)
右键单击jButton,单击属性并将Opacity设置为false。 要么 将此添加到您的代码中。 JButton.setvisible(假);