簡體   English   中英

將JComponent的寬度和高度設置為實例變量

[英]Setting the width and height of a JComponent as instance variables

我將組件的寬度和高度設置為實例變量(在組件的子類中)有問題。 如果我在構造函數中調用getWidth()getHeight() (總是為零),則這些值與在paintComponent(Graphics g)調用相同的方法不同。 有人可以解釋為什么會發生這種情況,我怎樣才能將組件的寬度和高度設置為實例變量。 非常感謝提前。

這是一段代碼:

import java.awt.Graphics;
import javax.swing.JComponent;

public class MyComponent extends JComponent
{
    // Instance variables.
    private int width;
    private int height;

    public MyComponent()
    {
        width = getWidth();
        height = getHeight();
        System.out.println(width+","+height);
    }

    public void paintComponent(Graphics g)
    {
        // Local variables.
        int width = this.getWidth();
        int height = this.getHeight();
        System.out.println(width+","+height);
    }

}

import javax.swing.JFrame;

public class ComponentTester
{
    public static void main(String args[])
    {
        JFrame frame = new JFrame();
        MyComponent component = new MyComponent();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(350, 400);
        frame.setVisible(true);

        frame.add(component);
    }

}

設置組件大小取決於組件。 因此在構造函數中,默認大小為0.如果將組件添加到布局管理器中(就像將組件添加到具有默認布局管理器的框架時所做的那樣),它將根據首選/最小/最大值設置大小這 - 默認為0到max-int。 因此布局管理器會將組件的大小調整為框架的大小。

無需將大小存儲在本地副本中,因為getWidth()/ Height()將從組件類中的本地副本讀取大小。

暫無
暫無

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

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