[英]How to set a button background to transparent?
我在JLabel中有一個按鈕列表。 按鈕是圖像,該圖像的背景是透明的,但是按鈕iself比圖像大,並且覆蓋背景圖像,這就是我的意思:
這是我的代碼:
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);
SomePanel代碼:
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);
}
}
請注意,我在第一個地圖上測試了這些命令,但它仍然沒有在右側顯示標簽的背景。 我想念什么?
該按鈕具有默認邊框。 如果您不希望使用邊框,則可以使用:
button.setBorderPainted( false );
您可能還想使用:
button.setFocusPainted( false );
button.setContentAreaPainted( false );
編輯:
糟糕,我剛剛注意到您確實在第一個按鈕上使用了上面的代碼(對於其他按鈕,您當然需要重復執行)。
我猜問題出在按鈕面板上。 您還需要使面板透明:
JPanel buttons = new JPanel(new GridLayout(0, 1));
buttons.setOpaque( false );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.