本文介绍了即使我将Eclipse上的Java添加到JFrame中,也不会显示JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是文件.我已经将JFrame设置为可见,并向其中添加了JPanel,但是代码仍然只显示没有任何内容的窗口.

These are the files. I have set JFrame to be visible, and have added JPanel to it, but still, the code only shows the window without anything in it.

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);
}

------------- DRAWINGPANEL文件-------------------

-------------DRAWINGPANEL FILE-------------------

 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);
     }
 }

推荐答案

尝试将DrawingPanel中的方法从painting更改为paint,该方法在运行时将被调用. paint是从JPanel继承的方法.

Try changing the method in DrawingPanel from painting to paint, which will get called when run. paint is a method inherited from JPanel.

NomadMaker 所述,请在此处使用paintComponent()而不是paint().阅读以获取更多信息.

As mentioned by NomadMaker, use paintComponent() not paint() here. Read this for more information.

这篇关于即使我将Eclipse上的Java添加到JFrame中,也不会显示JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 22:35