簡體   English   中英

如何在JPanel中自動調整圖紙大小?

[英]how to do auto-resizing drawings in JPanel?

在JPanel中具有可在用戶每次調整JFrame大小時進行調整大小的圖形的最簡單方法是什么?

我知道我可以使用BorderLayout自動調整面板的大小,但是在這種情況下不會調整圖紙的大小。 我是Java和GUI編程的新手,可能有很多解決方案。

請給我一個正確的方向提示,例如在

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

public class DrawRect extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        g.drawRect(20, 20, 100, 100);
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        DrawRect panel = new DrawRect();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(200, 200));
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

調整框架大小時自動調整大小。

根據面板寬度和高度的比例提供位置和大小。 每次調整面板大小時,渲染引擎都會安排對paintComponent()方法的調用,並且矩形將按比例繪制。 例如

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

public class DrawRect extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        int w = getWidth();
        int h = getHeight();
        g.drawRect(w/10, h/10, w/2, h/2);
    }

    /* A custom component should give the layout manager hints as to
    its preferred size. */
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200,200);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        DrawRect panel = new DrawRect();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}
frame.getContentPane().setLayout(new BorderLayout());

在將組件添加到GUI之前,請插入該行。

您應該學習布局管理器,因為它是Java中的獨特概念。

暫無
暫無

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

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