我有一些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);
如果我只是设置了,,它工作正常,我看到了图标。如果我执行上述操作并尝试设置翻转图标,则当鼠标悬停在按钮上时,我看不到任何图标。
我做错了什么?
由于
答案 0 :(得分:5)
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);
}
});
}
}