简体   繁体   English

Swing:无法绘制矩形

[英]Swing: can't paint rectangle

I have this simple code: the JFrame adds custom Jpanel MyPanel which overrides paintComponent method to draw the rectangle.我有这个简单的代码: JFrame添加了自定义Jpanel ,它覆盖了paintComponent方法来绘制矩形。 However nothing shows up on the window:然而,window 上没有任何显示:

import javax.swing.*;

import java.awt.*;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestGui extends JFrame  {
    public TestGui()  {
        setLayout(new FlowLayout());

        JPanel panel = new JPanel();

        panel.add(new JLabel("H E L L O"));
        getContentPane().add(panel);

        getContentPane().add(new MyPanel());

        setSize(100, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        repaint();
        revalidate();
        setVisible(true);
    }

    class MyPanel extends JPanel {
        private int squareX = 50;
        private int squareY = 50;
        private int squareW = 20;
        private int squareH = 20;

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.fillRect(squareX,squareY,squareW,squareH);
        }
    }

    public static void main(String[] args) {
        TestGui gui = new TestGui();
    }
}

By default, an empty JPanel has a size of 0x0 , so when you add it to your UI, the layout manager (in this case) honours it's request and makes it 0x0默认情况下,空的JPanel的大小为0x0 ,因此当您将其添加到 UI 时,布局管理器(在这种情况下)会接受它的请求并将其设为0x0

Start by adding...首先添加...

@Override
public Dimension getPreferredSize() {
    return new Dimension(100, 100);
}

to MyPanel到我的MyPanel

Also, the repaint and revalidate calls aren't going to do anything, as the window isn't yet attached to native peer (rendering surface)此外, repaintrevalidate调用不会做任何事情,因为 window 尚未附加到本机对等点(渲染表面)

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

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