2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
這個(gè)對(duì)我有用:
注意,我用圖片創(chuàng)建了兩張圖片和圖標(biāo),一張是按鈕的,一張是按下狀態(tài)的,表示已經(jīng)按下了。
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class XButtonTest {
private static final String X_IMG_PATH = "https://i.imgur.com/cWGntek.png";
public static void main(String[] args) {
try {
URL xImgUrl = new URL(X_IMG_PATH);
BufferedImage xImage = ImageIO.read(xImgUrl);
int w = xImage.getWidth();
int h = xImage.getHeight();
BufferedImage pressedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = pressedImg.createGraphics();
g2.setColor(Color.LIGHT_GRAY);
g2.fillRect(0, 0, w, h);
g2.drawImage(xImage, 0, 0, null);
g2.dispose();
Icon icon = new ImageIcon(xImage);
Icon pressedIcon = new ImageIcon(pressedImg);
JButton button = new JButton(icon);
button.setPressedIcon(pressedIcon);
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setContentAreaFilled(false);
JPanel panel = new JPanel();
panel.add(button);
JOptionPane.showMessageDialog(null, panel, "Test", JOptionPane.PLAIN_MESSAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
}

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超9個(gè)贊
我發(fā)現(xiàn)“drawImage”渲染的圖像很糟糕,這就是我認(rèn)為的問題:
public class Panel extends JPanel
{
BufferedImage image;
public Panel() {
super();
try {
image = ImageIO.read(new File("images/BMW-TA.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
資料來源:https ://i.imgur.com/ebr17CV.jpg
渲染:https ://i.imgur.com/Z01I7mn.png
找到解決方案
在 paintComponent 中使用抗鋸齒:
@Override
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(rh);
g2.drawImage(cross,0,0,null);
}
添加回答
舉報(bào)