简体   繁体   English

更新setText()时,JLabel的背景颜色会更改

[英]JLabel's background color changes when updated setText()

Edit (it's not the opaque attribute that's causing the problem, it's updating the JLabel's background attribute): I am using a MouseMotionListener to setText() for a JLabel to whatever the mouse's current position is. 编辑(不是造成问题的不透明属性,它是在更新JLabel的background属性):我正在使用MouseMotionListener将JLabel的setText()设置为鼠标的当前位置。 The JLabel starts out with the correct background color/transparency at first running of the program. JLabel在程序第一次运行时以正确的背景色/透明度开始。 Whenever the text/mouseMotion is updated the JLabel is no longer transparent. 每当text / mouseMotion更新时,JLabel就不再透明。

Updated runnable code: 更新了可运行代码:

For example: 例如:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class MouseTester extends JFrame {
public static void main(String[] args) {
try {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            MouseTester.createMouseTester();
        }
    });
} catch (Throwable t) {
    System.exit(1);
}
}
private static MouseTester mt = null;
private JLabel mouseLocation = null;
private static Color labelBackgroundColor = new Color(0, 0, 0, 127);
private static Color labelForegroundColor = Color.WHITE;

public static void createMouseTester() {
      if (mt != null)
          return;
      mt = new MouseTester();
      mt.setVisible(true);
}

private MouseTester() {
      super();
      mt = this;
      setResizable(true);
      Dimension dScreen = Toolkit.getDefaultToolkit().getScreenSize();
      setMinimumSize(new Dimension(Math.min(800, dScreen.width), Math.min(590,
      dScreen.height)));
      setSize(getMinimumSize());
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      mouseLocation = new JLabel(" Lat/Long ");
      mouseLocation.setOpaque(true);
      mouseLocation.setBackground(labelBackgroundColor);
      mouseLocation.setForeground(labelForegroundColor);
      mouseLocation.setToolTipText("The MGRS coordinates.");

      Component textArea = new TextArea("Move mouse here to see mouse motion info...");

      // Add a mouse motion listener to capture mouse motion events
      textArea.addMouseMotionListener(new MouseMotionAdapter() {

public void mouseMoved(MouseEvent evt) {
      TextArea source = (TextArea) evt.getSource();
          // Process current position of cursor while all mouse buttons are up.
            mouseLocation.setText(source.getText() + "\nMouse moved [" + 
          evt.getPoint().x + "," + evt.getPoint().y + "]");
            mouseLocation.setBackground(labelBackgroundColor);
            mouseLocation.setForeground(labelForegroundColor);
            mouseLocation.setOpaque(true);
            mouseLocation.repaint();

      }
      public void mouseDragged(MouseEvent evt) {

      }
  });

  // Add the components to the frame; by default, the frame has a border layout
        mt.add(textArea, BorderLayout.NORTH);
        mouseLocation.setOpaque(true);
        mouseLocation.setBackground(labelBackgroundColor);
        mouseLocation.setForeground(labelForegroundColor);
        mt.add(mouseLocation, BorderLayout.SOUTH);

        int width = 300;
        int height = 300;
        mt.setSize(width, height);
  }
}

The JLabel starts out transparent/slightly grey then changes with the mouse motion to not transparent and entirely black. JLabel开始为透明/浅灰色,然后随着鼠标移动而变为不透明和全黑。 The transparency is determined in the background color. 透明度由背景色决定。

I've pretty much tried changing the background color everywhere I could think of, but it's not working.. 我已经尝试过在所有我能想到的地方更改背景颜色,但是它没有用。

I would like it to remain the color the entire time (the color that it has at startup). 我希望它始终保持颜色(启动时的颜色)。

You have declared that your JLabel is opaque, which means that it is fully responsible for drawing its own background. 您已经声明您的JLabel不透明,这意味着它完全负责绘制自己的背景。 Yet you have set it's background color to a semi-transparent color. 但是,您已将其背景色设置为半透明色。 That is a contradiction and is the cause of your problem. 这是一个矛盾,是造成您问题的原因。

You can fix the appearance of your JLabel by using mt.repaint(); 您可以使用mt.repaint();来修复JLabel的外观mt.repaint(); instead of mouseLocation.repaint(); 而不是mouseLocation.repaint(); thus forcing a re-draw of the area of the entire panel behind the JLabel (in gray) followed by a re-draw of the JLabel in your semi-transparent color. 因此,必须重新绘制JLabel后面的整个面板区域(灰色),然后重新绘制半透明颜色的JLabel。

If you want to avoid the cost of re-painting your entire mt object, then you need to nest your JLabel inside some smaller component which you can redraw quickly. 如果要避免重绘整个mt对象的开销,则需要将JLabel嵌套在一些较小的组件中,以便快速重绘。

对于从(Xxx)MouseListeners触发的每个MouseEvents ,您都必须调用JLabel#repaint()Opaque(true)切换到Opaque(false) ,反之亦然,因为此方法在API中丢失,其余内容与描述有关通过@kleapatra

I'm not sure why you're changing the label's transparency . 我不确定为什么要更改标签的透明度 Making the label opaque and adjusting it's background saturation may be sufficient, as shown below. 如下所示,使标签不透明并调整其背景饱和度可能就足够了。

A few notes on your implmentation: 有关实现的一些注意事项:

  • Kudos for using the event dispatch thread . 使用事件调度线程的荣誉。
  • Let the layout do the work; 让布局完成工作; use setSize() sparingly . 谨慎使用setSize()
  • Don't mix AWT and Swing components needlessly. 不要不必要地混合使用AWT和Swing组件。
  • Don't swallow exceptions. 不要吞下例外。

在此处输入图片说明

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class MouseTester extends JFrame {
    private static MouseTester mt;
    private static Color labelBackgroundColor = Color.gray;
    private static Color labelForegroundColor = Color.white;
    private JLabel mouseLocation;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                MouseTester.createMouseTester();
            }
        });
    }

    public static void createMouseTester() {
        mt = new MouseTester();
        mt.setVisible(true);
    }

    private MouseTester() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mouseLocation = new JLabel("Lat/Long", JLabel.CENTER);
        mouseLocation.setOpaque(true);
        mouseLocation.setBackground(labelBackgroundColor);
        mouseLocation.setForeground(labelForegroundColor);
        mouseLocation.setToolTipText("The MGRS coordinates.");
        JTextArea textArea = new JTextArea(
            "Move mouse here to see mouse motion info...");
        textArea.addMouseMotionListener(new MouseMotionAdapter() {

            @Override
            public void mouseMoved(MouseEvent me) {
                mouseLocation.setText("Mouse moved ["
                    + me.getX() + ", " + me.getY() + "]");
            }
        });
        this.add(textArea, BorderLayout.CENTER);
        this.add(mouseLocation, BorderLayout.SOUTH);
        this.pack();
        this.setSize(320, 240); // content placeholder
        this.setLocationRelativeTo(null);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM