2014-05-04 66 views
0

我有一個JLabel中的按鈕列表。這些按鈕的圖像和圖像的背景是透明的,但是按鈕iself比圖像更大,它涵蓋了背景圖片,這裏就是我的意思:如何將按鈕背景設置爲透明?

http://i.imgur.com/uSBouqO.png

這是我的代碼:

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代碼:我測試這些命令與第一張地圖,但它仍然沒有SH

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); 
    } 
} 

注在右邊標籤的背景。我錯過了什麼?

+1

的[透明的JButton(http://stackoverflow.com/questions/4585867/transparent-jbutton) – Braj

+0

我怎樣才能檢測到這種可能重複? –

+0

只需搜索'StakOverflow'。對你有幫助嗎? – Braj

回答

3

該按鈕有一個默認的邊框。如果你不希望邊框,您可以使用:

button.setBorderPainted(false); 

你也可以使用:

button.setFocusPainted(false); 
button.setContentAreaPainted(false); 

編輯:

哎呀,我剛纔注意到你使用上面的代碼爲你的第一個按鈕(你當然需要重複,如果你的其他按鈕)。

我想這個問題是與按鈕面板。您還需要使面板透明:

JPanel buttons = new JPanel(new GridLayout(0, 1)); 
buttons.setOpaque(false); 
+0

我嘗試過這些,但沒有任何更改:/ –

+1

@ p.bosch,請參閱編輯。 – camickr

+0

哦,我的上帝,你剛剛做到了!我已經超過3個小時尋找這樣的事情,我所要做的就是使面板透明......謝謝你這麼多! –