这些是文件。我已将 JFrame 设置为可见,并向其中添加了 JPanel,但代码仍然只显示窗口,其中没有任何内容。
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.Collections;
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(350, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("My Empty Window");
frame.setVisible(true);
DrawingPanel panel = new DrawingPanel();
frame.add(panel);
frame.setVisible(true);
}
-------------绘图面板文件--------------------
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawingPanel extends JPanel {
public void painting(Graphics pen) {
pen.drawRect(50, 50, 20, 20);
pen.drawRect(100, 50, 40, 20);
pen.drawOval(200,50,20,20);
pen.drawOval(250, 50, 40, 20);
pen.drawString("Square", 50, 90);
pen.drawString("Rectangle", 100, 90);
pen.drawString("Cirlce", 200, 90);
pen.drawString("Oval", 250, 90);
pen.fillRect(50, 100, 20, 20);
pen.fillRect(100, 100, 40, 20);
pen.fillOval(250, 100, 20, 20);
pen.fillOval(250, 100, 40, 20);
pen.drawLine(50, 150, 300, 150);
pen.drawArc(50, 150, 200, 100, 0, 180);
pen.fillArc(100, 175, 200, 75, 90, 45);
}
}
最佳答案
这是使您的代码可运行、修复您的 JFrame
方法调用并修复您的绘图 JPanel
后得到的结果。
Swing 应用程序应始终以调用 SwingUtilities
invokeLater
方法开始。此方法确保在 Event Dispatch Thread 上创建并执行 Swing 组件。 .
您打包一个JFrame
。您可以设置绘图 JPanel
的首选尺寸。这样,您就可以知道您的绘图 JPanel
有多大,而不必担心 JFrame
装饰。
这是完整的可运行代码。
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawingPanelExample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new DrawingPanelExample());
}
@Override
public void run() {
JFrame frame = new JFrame("My Empty Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawingPanel panel = new DrawingPanel();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
public DrawingPanel() {
this.setPreferredSize(new Dimension(350, 300));
}
@Override
protected void paintComponent(Graphics pen) {
super.paintComponent(pen);
pen.drawRect(50, 50, 20, 20);
pen.drawRect(100, 50, 40, 20);
pen.drawOval(200, 50, 20, 20);
pen.drawOval(250, 50, 40, 20);
pen.drawString("Square", 50, 90);
pen.drawString("Rectangle", 100, 90);
pen.drawString("Cirlce", 200, 90);
pen.drawString("Oval", 250, 90);
pen.fillRect(50, 100, 20, 20);
pen.fillRect(100, 100, 40, 20);
pen.fillOval(250, 100, 20, 20);
pen.fillOval(250, 100, 40, 20);
pen.drawLine(50, 150, 300, 150);
pen.drawArc(50, 150, 200, 100, 0, 180);
pen.fillArc(100, 175, 200, 75, 90, 45);
}
}
}
关于即使我将 JPanel 添加到 JFrame,Eclipse 上的 Java 也不会显示 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65484190/