有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

摇摆的颜色。使用drawString()java时跳过白色

当我试图在黑色背景上画白色字母时,我注意到了一些奇怪的东西

public WhiteOnBlackPanel() {
    setBackground(Color.BLACK);
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(new Color(255,255,255));
    g.drawString("Hello World",100,100);
    g.drawLine(0,0,100,100);
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new WhiteOnBlackPanel());
    frame.setTitle("Hello World");
    frame.setSize(600,400);
    frame.setLocation(100,100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setVisible(true); // The frame is visible from now on
}

!不要看图像中的代码,只看框架

给我这个: "White" letters on a black background

然而,界线画得很好

"White" letters and a white line on a black background

当我用一种不同但非常接近的颜色(2542555)时,我得到了这个

White letters on a black background

为什么java.awt.Graphics阻止绘制纯白(255255)字母(即使是在黑色背景上)

蒂娅,查理


共 (2) 个答案

  1. # 1 楼答案

    在添加所有组件并进行设置后,最后调用setVisible(true)。不要覆盖“绘制”,而要覆盖“绘制组件”。例如,这很好:

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class ShowColor extends JPanel {
       private static final int PREF_W = 600;
       private static final int PREF_H = 400;
    
       public ShowColor() {
          setBackground(Color.black);
       }
    
       public Dimension getPreferredSize() {
          if (isPreferredSizeSet()) {
             return super.getPreferredSize();
          }
          return new Dimension(PREF_W, PREF_H);
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.setColor(new Color(255,255,255));
          g.drawString("Hello World",100,100);
       }
    
       private static void createAndShowGUI() {
          ShowColor paintEg = new ShowColor();
    
          JFrame frame = new JFrame("ShowColor");
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.getContentPane().add(paintEg);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGUI();
             }
          });
       }
    }
    
  2. # 2 楼答案

    jdk1中的一个bug。8.0_20,至少在Linux(Ubuntu)中:0xFFFFFFFF显示为黑色。更改alpha或其中一个RGB值会导致“几乎为白色”

    jdk1。7.0_67在同一系统上运行良好

    检查了所有形式的setColor

    之后发现报告了错误:JDK-8054638 : White color is not painted

    受影响的版本:8u11,8u25

    这个bug只影响Linux;在Windows上,一切正常