blackwodka86
blackwodka86

Reputation: 31

Semi-Transparent JButton: Objects appear in Background

I got a Problem: I started to make a nicer looking extension of Swing- JButton. One of the remaining problems: Whenever I set it "Semi-Transparent" (like this.setBackground(new Color(100,100,100,90));) the optic becomes weird: every time I hover my mouse over the Button the last Swing-Element with a String (like a JRadioButton or a JCheckBox) I hovered over will appear in the background.

My current Button:

private boolean transparent;
private boolean drawImage;
private final int width;
private final int height;
int marginWidth=15;
int marginHeight=15;

public MyButton(String text, String command){
    super(text);
    this.setDoubleBuffered(true);
    this.setOpaque();
    this.setActionCommand(command);

    this.setBackground(ParameterPool.COLOR_BACKGROUND_SECOND);
    this.setBorder(null);

    this.width = (int) this.getPreferredSize().getWidth()+marginWidth;
    this.height = (int) this.getPreferredSize().getHeight()+marginHeight;

    this.setPreferredSize(new Dimension(this.width, this.height));

}


public void setTransparent() {
    this.transparent = true;
    this.setOpaque(false);
}

public void setOpaque() {
   this.transparent = false;
   this.setOpaque(true);
}
@Override
protected void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D)g; 


    g2d.fillRoundRect(0,0,width,height,18,18); 

    g2d.setColor(Color.darkGray); 
    g2d.drawRoundRect(0,0,width, height,18,18); 

    FontRenderContext frc = new FontRenderContext(null, false, false); 
    Rectangle2D r = getFont().getStringBounds(getText(), frc);
    float xMargin = (float)(width-r.getWidth())/2; 
    float yMargin = (float)(height-getFont().getSize())/2; 
    g2d.drawString(getText(), xMargin, (float)getFont().getSize() + yMargin); 
    this.setSize(width, height);
}

public JPanel inTransparentPanel(){
    JPanel ret = new JPanel();
    ret.setOpaque(false);
    ret.setDoubleBuffered(true);
    ret.add(this);
    return ret;
}

One more thing: I also tried this without overriding the paintComponent(...)-Method. No effect.

Upvotes: 0

Views: 592

Answers (1)

blackwodka86
blackwodka86

Reputation: 31

Ok, just fixed this problem "by accident": I figured out that one of the Panels arround that buttons still was a java awt Pane. Never thought of that as a problem.

Upvotes: 1

Related Questions