問題描述
半透明 JButton:對像出現在背景中 (Semi‑Transparent JButton: Objects appear in Background)
我遇到了一個問題:我開始製作一個更好看的 Swing‑JButton 擴展。剩下的問題之一:每當我將它設置為“半透明”(如 this.setBackground(new Color(100,100,100,90));
)時,光學變得奇怪:每次我將鼠標懸停在我懸停的最後一個帶有字符串的 Swing‑Element 按鈕(如 JRadioButton 或 JCheckBox)將出現在背景中。
我當前的按鈕:
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;
}
還有一件事:我也試過這個,沒有覆蓋paintComponent(...)‑方法。沒有效果。
參考解法
方法 1:
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.
(by blackwodka86、blackwodka86)