我遇到了一个问题:我开始制作一个看起来更漂亮的 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(...)-方法。没有效果。
最佳答案
好吧,只是“偶然”解决了这个问题:我发现按钮周围的面板之一仍然是 java awt Pane 。从来没有认为这是一个问题。
关于java - 半透明JButton : Objects appear in Background,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36543985/