我在 JLabel 中有一个按钮列表。按钮是图像,该图像的背景是透明的,但是按钮本身比图像大并且它覆盖了背景图像,这就是我的意思:
这是我的代码:
JPanel buttons = new JPanel(new GridLayout(0, 1));
JButton butoMapa = null;
try {
butoMapa = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Mapa.png"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
butoMapa.setOpaque(false);
butoMapa.setContentAreaFilled(false);
butoMapa.setBorderPainted(false);
butoMapa.addActionListener(this);
JButton butoEtnies = null;
try {
butoEtnies = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Etnies.png"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
butoEtnies.addActionListener(this);
JButton butoComandes = null;
try {
butoComandes = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Comandes.png"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
butoComandes.addActionListener(this);
JButton butoSurtir = null;
try {
butoSurtir = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Surtir.png"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
butoSurtir.addActionListener(this);
SomePanel label2 = new SomePanel();
label2.add(buttons);
frame.add(label2, BorderLayout.EAST);
buttons.add(butoMapa);
buttons.add(butoEtnies);
buttons.add(butoComandes);
buttons.add(butoSurtir);
//JPanel right = new JPanel(new BorderLayout());
// right
//right.add(buttons, BorderLayout.NORTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
一些面板代码:
class SomePanel extends JPanel {
private BufferedImage image;
public SomePanel() {
try {
image = ImageIO.read(getClass().getResource("imatges/costat.png"));
} catch (IOException ex) {}
//add(new JButton("Hello"));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
}
请注意,我使用第一张 map 测试了这些命令,但它仍然没有显示右侧标签的背景。我错过了什么?
最佳答案
该按钮有一个默认边框。如果您不想要边框,可以使用:
button.setBorderPainted( false );
您可能还想使用:
button.setFocusPainted( false );
button.setContentAreaPainted( false );
编辑:
哎呀,我刚刚注意到您确实在第一个按钮中使用了上述代码(当然,您需要为其他按钮重复该代码)。
我猜问题出在按钮面板上。您还需要使面板透明:
JPanel buttons = new JPanel(new GridLayout(0, 1));
buttons.setOpaque( false );
关于java - 如何将按钮背景设置为透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23458186/