gpt4 book ai didi

java - 面板为什么不绘制(paint)?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:40 24 4
gpt4 key购买 nike

代码

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

class tester {
public static void main(String args[]) {
JFrame fr = new JFrame();
JPanel p = new JPanel();
p.setBackground(Color.RED);
p.paintImmediately(20,20,500,500);
fr.add(p);
fr.setVisible(true);
fr.setSize(2000,2000);
}
}

我得到一个完全涂成红色的面板。为什么我不接电话?我怎样才能得到它?

最佳答案

I get a panel painted completely of red color.

那是因为你设置了背景,没有做任何进一步的绘画......

Why dont i get the line ? How can i get it?

这不是做这件事的方法。为什么调用 paintImmediately?以下是文档中的内容:

Paints the specified region in this component and all of its descendants that overlap the region, immediately.

It's rarely necessary to call this method. In most cases it's more efficient to call repaint, which defers the actual painting and can collapse redundant requests into a single paint call. This method is useful if one needs to update the display while the current event is being dispatched.

我建议您继续阅读 AWT/Swing 中的绘画。


得到这样的东西

enter image description here

您可以这样更改您的代码:

JFrame fr = new JFrame();
JPanel p = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(20, 20, 500, 500);
}
};
p.setBackground(Color.RED);
fr.add(p);
fr.setVisible(true);
fr.setSize(200, 200);

关于java - 面板为什么不绘制(paint)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7846485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com