java – 为什么不绘制面板?
作者:互联网
码
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中的绘画.
> Lesson: Performing Custom Painting
得到这样的东西
你可以改变你的代码:
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-2d,paintcomponent,java,colors,swing 来源: https://codeday.me/bug/20190726/1541368.html