簡體   English   中英

有什么辦法可以在paintComponent中獲取參數?

[英]Is there any way that I can get a parameter in paintComponent?

我在paintComponent方法中如何設置其他參數時遇到問題。

我還沒有找到其他方法。

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

public class Interface extends JPanel
{    
    protected void paintComponent(Graphics g *here(not part of code btw)*) {
        super.paintComponent(g);
        g.setColor(Color.orange);
        g.fillRect(0, 0, 100, 100);
    }

    public void CreateWindow(String name, int Xsize, int Ysize) {

        //laver et JFrame og klader det "frame" !

        JFrame frame= new JFrame(); 

        frame.setTitle(name);

        frame.setSize(Xsize, Ysize);
        frame.setLocation(200, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        Interface JPanel = new Interface();
        frame.add(JPanel);
        Graphics Grafik = getGraphics();

        paintComponent(Grafik);
    }
}

當我使用參數運行代碼時,它不會繪制矩形。

但是,如果只有Graphics參數,它將運行良好。

如您在Javadoc中所見,JComponent中只有一個為paintComponent定義的方法。 這意味着,有沒有一種方式,你可以做到這一點,而無需創建JComponent中的自己的JComponent和擴展(子類)(這是不必要的復雜和困難)。 相反,請考慮您可以在類中使用字段來存儲進入方法paintComponent時所需的持久狀態。 另一方面,最好將臨時變量定義為該方法的局部變量。

此外,這不是很好的做法來命名你的類Interface ,由於interface是一個保留關鍵字在Java中。

tl; dr-本質上沒有。 使用字段/局部變量存儲其他數據。

暫無
暫無

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

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