【问题标题】:JComponents not displaying properlyJComponents 无法正确显示
【发布时间】:2020-08-06 16:51:46
【问题描述】:

更改 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);
   }
 }

这是程序的输出

第一次运行时的程序:

将鼠标悬停在两个按钮上后的程序:

【问题讨论】:

  • 按钮的透明背景似乎是问题所在。如果您希望按钮融入其中,请将其背景颜色设置为与 JPanel 相同的值
  • @R VISHAL 无论我将 Jbutton 设置为什么背景颜色,都会出现同样的问题

标签: java swing


【解决方案1】:

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

您可以使用:

button.setOpaque( false );

现在 Swing 会在绘制按钮之前自动绘制父组件,因此绘制的伪影将被移除。

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 2014-04-23
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多