我有一些JButton的代码:
solutionButton = new JButton("Solution");
solutionButton.setBorderPainted( false);
solutionButton.setContentAreaFilled( false );
solutionButton.setFocusPainted( false);
solutionButton.setFont( new Font("Arial",Font.BOLD,16));
solutionButton.setForeground( new Color(80,21,25));
solutionButton.setRolloverIcon(
new ImageIcon(getClass().getResource( "images/game.png")));
solutionButton.setRolloverEnabled( true );
add(solutionButton);
如果我只是setIcon,它可以正常工作,我会看到该图标。如果执行上述操作并尝试设置鼠标悬停图标,则将鼠标悬停在该按钮上时看不到任何图标。
我究竟做错了什么?
谢谢
最佳答案
指向月亮!
import java.awt.Image;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
class TestRolloverIcon {
public static void main(String[] args) throws Exception {
URL url1 = new URL("http://pscode.org/media/citymorn1.jpg");
URL url2 = new URL("http://pscode.org/media/citymorn2.jpg");
final Image image1 = ImageIO.read(url1);
final Image image2 = ImageIO.read(url2);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JButton button = new JButton("Point at the Moon!");
button.setIcon(new ImageIcon(image1));
button.setRolloverIcon(new ImageIcon(image2));
JOptionPane.showMessageDialog(null, button);
}
});
}
}
有没有一种方法,而无需先设置图标,我只希望鼠标悬停图标而不是图标。
指向太空(很多)!
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
class TestRolloverIcon {
public static void main(String[] args) throws Exception {
URL url2 = new URL("http://pscode.org/media/citymorn2.jpg");
final BufferedImage image2 = ImageIO.read(url2);
final BufferedImage image1 = new BufferedImage(
image2.getWidth(),image2.getHeight(),BufferedImage.TYPE_INT_ARGB);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JButton button = new JButton("Point at space (there's a lot of it)!");
button.setIcon(new ImageIcon(image1));
button.setRolloverIcon(new ImageIcon(image2));
JOptionPane.showMessageDialog(null, button);
}
});
}
}