2017-09-26 2 views
0

ImageIconとテキストがあるJButtonがあります。 ボーダーのない透明な背景を持ちたいと思っていますが、パディングもしたいです。Jbuttonパディング付きの非表示の境界

Jbutton button = new JButton(); 

//Add image to the button 
ImageIcon img= new ImageIcon(imgUrl); 
button.setIcon(img); 

//make button transparent 
button.setBackground(new Color(255,255,255,0)); 

//Remove border 
button.setBorderPainted(false); 
button.setContentAreaFilled(false); 
button.setFocusPainted(false); 

//add padding 
button.setBorder(BorderFactory.createEmptyBorder(5,10,5,50)); 

を私はまだ枠で灰色の境界線の周り参照してください。ここでは

は、私がしようとしているものです。 私はbutton.setBorder(null)を行うと灰色の境界線が消えるが、パディングを追加することはできない。

私が間違っていることについて誰かが私を導くことができれば。私は非常にスイングして、新しい答えを試したが、誰も働いていない。

ありがとうございます。

+0

'button.setBackground(新色(255,255,255,0));'コンポーネントを透明にする方法ではなく、 'setOpaque'を設定してfalseを渡す必要があります – MadProgrammer

+1

[' JButton#setMargin'](https://docs.oracle.com/javase) /8/docs/api/javax/swing/AbstractButton.html#setMargin-java.awt.Insets-)埋め込みを追加する場合 – MadProgrammer

+0

@MadPro grammerはbutton.setMargin(新しいInsets(10,10,10,10))を試みましたが、nullとして設定された境界線では機能しませんでした。私が試すことができる他のものはありますか? – LearningToCode

答えて

0

どのようにマージンを設定するかは、layoutmanager上のどのスイングコンポーネントの気持ちにも影響します。

GridBagLayoutを使用している場合は、GridBagConstraintオブジェクトのインセットを目的の値に設定する必要があります。

1
  • アルファベースの色を使用することは望ましくない副作用
  • がパディング
を生成する setMarginsを使用することを検討して生成することができ、唯一の opaqueプロパティを介して制御する、完全に不透明または完全に透明コンポーネントをサポートスイング、 setBackground(new Color(255,255,255,0))を使用しないでください。

例...

Screen Shot

オリジナル画像...

Original Image

import java.awt.GridBagLayout; 
import java.awt.Insets; 
import java.io.IOException; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.imageio.ImageIO; 
import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 

public class Launcher { 

    public static void main(String[] args) { 
     new Launcher(); 
    } 

    public Launcher() { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        JButton button = new JButton(); 

        ImageIcon img = new ImageIcon(ImageIO.read(getClass().getResource("Cup.png"))); 
        button.setIcon(img); 
        button.setBorderPainted(false); 
        button.setContentAreaFilled(false); 
        button.setFocusPainted(false); 
        button.setOpaque(true); 
        button.setMargin(new Insets(10, 10, 10, 10)); 
        JFrame frame = new JFrame(); 
        // Just testing to see there are glitches 
        frame.setLayout(new GridBagLayout()); 
        frame.add(button); 
        frame.pack(); 
        frame.setLocationRelativeTo(null); 
        frame.setVisible(true); 
       } catch (IOException ex) { 
        Logger.getLogger(Launcher.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } 
     }); 
    } 
} 

私はあなたがsetBorder使用した場合、それはmargin値をオーバーライドすることを見つけた

関連する問題