簡體   English   中英

Java - 重繪(x,y,w,h)不調用paintComponent? (與SSCCE)

[英]Java - repaint(x, y, w, h) doesn't call paintComponent? (with SSCCE)

之前我問過這個問題,但理論上只是在沒有SSCCE的情況下問過。 現在,我創建了一個,問題仍然存在。 我想知道為什么不在repaint(x, y, w, h)上調用paintComponent ,而是在repaint()上調用。

兩個班:

SANDBOX

import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JFrame;

public class Sandbox {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setMinimumSize(new Dimension(800, 600));
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new FlowLayout());

        // Add label
        f.getContentPane().add(new TLabel());

        f.setVisible(true);
    }
}

TLabel (有一點造型):

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;

@SuppressWarnings("serial")
public class TLabel extends JLabel {
    public TLabel() {
    super("TEST LABEL, NON-STATIC");
    this.setHorizontalAlignment(SwingConstants.CENTER);
    TLabel.this.setPreferredSize(new Dimension(200, 50));
    TLabel.this.setMaximumSize(new Dimension(200, 50));
    TLabel.this.setMinimumSize(new Dimension(200, 50));

    TLabel.this.setOpaque(true);
    TLabel.this.setBackground(Color.cyan.darker().darker());
    TLabel.this.setForeground(Color.white);
    TLabel.this.setBorder(new LineBorder(Color.orange, 2));

    this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                // EXPECTED BEHAVIOR HERE: This line will call paint and paintComponent.
                //repaint();

                // PROBLEM HERE: This line will not call paint or paintComponent.
                repaint(TLabel.this.getBounds());
        }
    });
    }

    @Override
    public void paint(Graphics g) {
    // Note: This is called once when the label is realised.
    // Note: This is called when the mouse enters the frame.
    System.out.println("PAINT.");
    super.paint(g);
    }

    @Override
    public void paintComponent(Graphics g) {
    // Note: This is called once when the label is realised.
    // Note: This is called when the mouse enters the frame.
    System.out.println("REPAINT.");
    super.paintComponent(g);
    }
}

你在說這個

repaint(TLabel.this.getBounds());

在TLabel對象里面。 因此重繪將嘗試在Bounds位置繪制相對於其自身的矩形,但getBounds()返回相對於包含對象位置的此組件定位的矩形,而重繪期望相對於組件本身的邊界。 所以你試圖繪制一個矩形,它具有JLabel的寬度和高度,但相對於JLabel位於x = 292和y = 5,而你想要x和y都為0.實質上你我試圖在這個組件之外畫畫。

而是試試這個:

        //!! repaint(TLabel.this.getBounds());
        Dimension d = TLabel.this.getSize();
        repaint(new Rectangle(0, 0, d.width, d.height));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM