我试图了解一个Paint Graphics,但是我的椭圆不能画出来。有人能告诉我,我做错了什么,椭圆形不是画画? 我在哪里弄错了?
主要课程:
import java.awt.EventQueue;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Frame frame = new Frame();
}
});
}
框架类:
public class Frame extends JFrame {
private static final long serialVersionUID = 1L;
public static Grafika grafika;
public Frame() {
JFrame frame = new JFrame("Title");
grafika = new Grafika();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(null);
// frame.addKeyListener(this);
frame.add(grafika);
}
}
最后一个Grafic课程:
public class Grafika extends JComponent {
int x = 200;
int y = 200;
public void paint(Graphics g) {
Graphics2D oval = (Graphics2D) g;
oval.setColor(Color.BLACK);
oval.fillOval(x, y, 100, 100);
oval.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
}
答案 0 :(得分:3)
有几个问题,但最大的问题是你在JFrame上使用空布局,然后添加一个JComponent,其首选大小和大小都是0,0。因此,当您将Grafika添加到JFrame时,它无法显示。
建议:
null
布局。getPreferredSize()
,但在此阶段,我认为可以在其上调用setPreferredSize(...)
。pack()
JFrame,然后,只有在将所有组件添加到JFrame后,才能将其显示为可见。另外
@Override
注释。你可能错了,希望编译器告诉你。Frame
。这可能会混淆他人和你未来的自我。如,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.*;
public class MyGrafika extends JComponent {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
private static final Color OVAL_COLOR = Color.RED;
private int ovalX = 200;
private int ovalY = 200;
private int ovalWidth = 100;
private int ovalHeight = 100;
public MyGrafika() {
setPreferredSize(new Dimension(PREF_W, PREF_H));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(OVAL_COLOR);
g2.fillOval(ovalX, ovalY, ovalWidth, ovalHeight);
}
private static void createAndShowGui() {
MyGrafika mainPanel = new MyGrafika();
JFrame frame = new JFrame("MyGrafika");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
答案 1 :(得分:2)
由于您使用的是paintComponent
,因此您应该覆盖paint
而不是Grafika
,您还应该使用null布局。但关键是您应该在使框架可见之前添加frame.add(grafika);
frame.setVisible(true);
// frame.setLayout(null); REMOVE THIS!
组件:
frame.setVisible(true);
// frame.setLayout(null); REMOVE THIS!
frame.add(grafika);
frame.validate();
frame.repaint();
如果确实需要在框架可见后添加组件,则应在框架或包含添加组件的面板上调用revalidate + repaint:
{{1}}