[英]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)此外,
repaint
和revalidate
调用不会做任何事情,因为 window 尚未附加到本机对等点(渲染表面)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.