java - 为什么 Repaint() 和 add() 方法不起作用?
问题描述
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 上学习了这段代码。
我不知道为什么我不能写出问题中的错误。这就是我在评论部分写的原因。
解决方案
首先,停下来。把视频放一边。喝杯热咖啡,阅读在 AWT 和 Swing中执行自定义绘画和绘画,以更好地了解绘画系统的核心方面如何在 Swing 中工作。
Swing 提供了许多“钩子”,您可以在其中执行自定义绘画,主要paintComponent
是JComponent
.
为了利用这一点,您首先需要一个从其JComponent
子级或其子级扩展的类(通常JPanel
)
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.BLACK);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// The background is painted for us, so we don't need to
// You shouldn't be relying on "magic" numbers anyway
//g.setColor(Color.BLACK);
//g.fillRect(0,0,500,600);
g.setColor(Color.RED);
g.fillOval(20,30,50,50);
// Never, ever, call repaint in here
// bad things happen, fairies lose wings
// black holes suck small children to oblivion
// Fire Fly gets cancelled
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 600);
}
}
现在你有一个自定义组件,你只需要它可以显示的东西
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Practice");
TestPane ball = new TestPane();
frame.add(ball);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
推荐阅读
- tensorflow - 为什么我的 GraphDef 实现超过了 TensorFlow 中的 2GB 限制?
- r - 调用系列中每次迭代的结果
- c# - 是否有 Visual Studio 编辑器功能可以垂直拆分页面以进行 Linq 评论?
- javascript - 如何在 Reactjs 组件中使用 vanilla javascript?
- jira - JIRA - 用户更改历史
- ios - 在 iPhone 和 iPad 中,标签和 SpanLabel 未正确对齐(略有不同)
- python - RobotFramework 变量部分的 Python 方法
- javascript - 不和谐删除消息过滤器
- sql-server - 如何禁用sqlServer中的所有FK
- excel - VBA 代码无错误停止,提示从目标工作簿中删除模块和表单