我尝试使用.setOpaque
,但这不起作用。我无法想到任何其他方法来摆脱白色部分。我一直在寻找堆栈溢出,但没有一种方法似乎有所帮助。有想法的人吗?
谢谢!
package menu;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class MenuPanel extends JPanel implements ActionListener
{
private Button playKnop, highScoreKnop, quitKnop, HTPKnop;
private JTextField naam;
private Image achtergrond;
private Tanks mainVenster;
public static String naam_input;
int x = 95, width = 200, height = 50;
public MenuPanel(Tanks mainVenster)
{
this.mainVenster = mainVenster;
this.setLayout(null);
playKnop = new Button("/buttons/PLAY.png", 350, this);
highScoreKnop = new Button("/buttons/HS.png", 460, this);
HTPKnop = new Button("/buttons/HTP.png", 515, this);
quitKnop = new Button("/buttons/QUIT.png", 570, this);
this.add(playKnop);
this.add(quitKnop);
this.add(HTPKnop);
this.add(highScoreKnop);
validate();
}
public class Button extends JButton
{
JButton button;
ImageIcon buttonImage;
String backgroundPath;
int y;
public Button(String backgroundPath, int y, MenuPanel menuPanel)
{
super();
this.backgroundPath = backgroundPath;
this.y = y;
buttonImage = new
ImageIcon(PlayPanel.class.getResource(backgroundPath));
this.setIcon(buttonImage);
this.setBounds(x, y, width, height);;
this.addActionListener(menuPanel);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(achtergrond, 0, 0, this.getWidth(), this.getHeight(),
this);
}
}
答案 0 :(得分:6)
删除JButton
的一些默认呈现属性,包括
contentAreaFilled
borderPainted
focusPainted
哪个会减少按钮,没什么。 JButton
已经支持绘制图标(并且可以针对各种状态执行此操作),因此不需要覆盖它的paintComponent
方法......
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
try {
BufferedImage img = ImageIO.read(getClass().getResource("/1xaN3.png"));
JButton btn = new JButton(new ImageIcon(img));
btn.setOpaque(false);
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
btn.setFocusPainted(false);
add(btn);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
就个人而言,我更喜欢使用ImageIO
而不是ImageIcon
(或其他方法)来加载我的图像,主要是因为如果出现问题它会抛出IOException
(而不是静默地失败) )并且在图像加载之前不会返回(如果你正确地执行它,则支持进度反馈)
有关详细信息,请查看Reading/Loading an Image