我试图在我的主类的JPanel上显示一个单独的类的图形。
主要类是mytest,单独的类是Ball。 Ball有一种涂料成分方法,只需绘制一个彩色圆圈即可。在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);
}
}
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....");
}
}
两个最大的建议是:
没有绘制红球的原因(或者只有1/4的原因)是因为您在“组件”窗口中更改了绘制它的位置。您试图以width / 2和height / 2(它是Component的中心)绘制它。对于正常渲染,它应该是0,0。
另请阅读The Java Tutorials 1中的绘画
您正在设置框架的大小,但面板的大小为零。您应该设置面板的首选大小,而不是框架的大小。然后获取面板的首选大小以传递给Ball构造函数,并在使框架可见之前打包框架。
在线前设置面板尺寸,
Ball ball = new Ball(dp.getWidth(),dp.getHeight());
然后添加此代码
setPreferredSize(new Dimension(Width, Height));
在“Ball”构造函数的末尾。
有关详细信息,请参阅此stack question。