import javax.swing.*;
import java.awt.*;
public class Main {
public Main(){
JPanel panel = new JPanel();
panel.setSize(500,600);
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0,0,500,600);
g.setColor(Color.RED);
g.fillOval(20,30,50,50);
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Practice");
Main ball = new Main();
frame.add(ball);
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,600);
frame.setVisible(true);
}
}
在此过程中,我遇到两个错误,我在youtube上学习了此代码。
我不知道为什么我不能写问题中的错误。这就是为什么我要在评论部分写东西。
答案 0 :(得分:4)
首先,停止。收起视频。拿杯热咖啡,然后阅读Performing Custom Painting和Painting in AWT and Swing,以更好地了解Swing中绘画系统的核心方面。
Swing提供了许多“挂钩”,您可以在其中执行自定义绘制,主要是import asyncio
import requests
def call_rest_api(data):
print('Triggered REST API in background')
response = requests.get(data['url'])
print('Response: %s' % response)
async def main(loop):
print('Some operations here...')
data = {'url': 'http://example.com#some_rest_api'}
await call_rest_api(data)
print('Continue work of main thread...')
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
的{{1}}。
要利用此优势,您首先需要一个从paintComponent
或它的子级(通常为JComponent
)扩展的类
JComponent
现在您有了一个自定义组件,只需将其显示为可以显示的内容
JPanel