首页 > 解决方案 > JComponents 无法正确显示

问题描述

更改 JButton 的颜色后,我的 JFrame 上显示的两个 jbutton 没有正确显示。当我将鼠标悬停在上面时,文本相互重叠。

这是我的程序代码:

import javax.swing.*;
import java.awt.*;

public class ButtonExample extends JFrame
{
   public static void main (String [] args) 
  {
    //Create jframe
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setSize(400, 250);
    frame.setLocation(5, 5);
    frame.setVisible(true);
    frame.setLayout(new FlowLayout());
    
    //Create first button
    JButton button = new JButton("First button");
    button.setBackground(new Color(0, 0, 0, 0));
    button.setForeground(new Color(0, 0, 0, 250));
    frame.add(button);
    
    //Create second button
    JButton button2 = new JButton("button 2");
    button2.setBackground(new Color(0, 0, 0, 0));
    button2.setForeground(new Color(0, 0, 0, 250));
    frame.add(button2);
   }
 }

这是程序的输出

我第一次运行它时的程序:

https://i.stack.imgur.com/VdPpK.png

将鼠标悬停在两个按钮上后进行编程:

https://i.stack.imgur.com/sFOvs.png

标签: javaswing

解决方案


如果您希望按钮透明,则不要设置背景。

相反,您可以使用:

button.setOpaque( false );

现在 Swing 将在绘制按钮之前首先自动绘制父组件,因此将删除绘制伪影。


推荐阅读