我正在尝试在主类的 JPanel 上显示来自单独类的图形。
主类是 mytest,独立类是 Ball。 Ball有一个paint组件方法,简单地画一个彩色圆圈。在 mytest 中,我实例化一个球并将其添加到 JPanel (dp):dp.add(ball)。非常简单,但我得到的只是白色面板背景,没有绘制球。
这是我的测试代码:
package myStuff;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class mytest {
private JFrame frame=new JFrame();
private JPanel dp = new JPanel();
public static void main(String[] args) {
mytest gui = new mytest();
gui.go();
}
public void go() {
frame.setTitle("Test");
frame.setSize(1000,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel dp=new JPanel();
dp.setBackground(Color.WHITE);
Ball ball = new Ball(dp.getWidth(),dp.getHeight());
dp.add(ball);
frame.add(dp);
frame.setVisible(true);
}
}
<小时/>
这是 Ball 类代码:
package myStuff;
import java.awt.*;
import javax.swing.*;
public class Ball extends JComponent{
private int Width;
private int Height;
public Ball (int width, int height ) {
Width=width;
Height=height;
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.setColor(Color.RED);
g2d.fillOval(Width/2,Height/2,40,40);
System.out.println("Doing graphics....");
}
}
<小时/>
dp 面板上应显示一个红球。我得到的只是面板背景,没有球。我知道它正在尝试,因为“做图形”打印了两次。
最佳答案
这是一个工作示例。
import java.awt.*;
import javax.swing.*;
public class Mytest {
private JFrame frame = new JFrame();
public static void main(String[] args) {
Mytest gui = new Mytest();
SwingUtilities.invokeLater(() -> gui.go());
}
public void go() {
frame.setTitle("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel dp = new JPanel();
dp.setPreferredSize(new Dimension(500, 500));
dp.setBackground(Color.WHITE);
Ball ball = new Ball(150, 150);
dp.add(ball);
frame.add(dp);
frame.pack(); // invokes layout and sizes components
frame.setLocationRelativeTo(null); // centers on screen
frame.setVisible(true);
}
}
class Ball extends JComponent {
private int width;
private int height;
// A ball should probably only have a "diameter"
public Ball(int width, int height) {
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width, height));
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.setColor(Color.RED);
// smooths out the graphics
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(0, 0, width, height);
System.out.println("Doing graphics....");
}
}
两个最大的建议是:
- 确保当您更改 Swing 组件时,您是在事件调度线程上进行的。
- 并使用抗锯齿功能使您的绘图看起来更平滑(请注意,这是可选的,它会增加额外的处理开销。)
没有绘制红球(或仅绘制了 1/4)的原因是您更改了在组件窗口中绘制它的位置。您尝试以宽度/2 和高度/2 绘制它,这是组件的中心。对于正常渲染,它应该位于 0,0。
还可以阅读《Java 教程》中有关绘画的内容 1
关于java - 如何显示另一个类的图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55716679/