将另一个类中的对象添加到JPanel

时间:2013-12-07 14:30:15

标签: java swing class jpanel draw

好的,我有一个像这样的JPanel:

public class GUI {
JFrame frame = new JFrame("Net");

JPanel panel = new JPanel();
public GUI()
{
frame.setSize(835,650);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);          
frame.add(panel);
panel.setSize(600,600);
panel.setLocation(215,5);}

桌子上还有其他一些面板等。我的主要是这一个:

public static void main(String[] args) {

   SwingUtilities.invokeLater(new Runnable(){ 
    @Override
    public void run(){
    //new GUI();
    new GUI().buildTable();

     }

   });

还有另外一节课:

public class DrawPlanes extends GUI 
{    

private static int centreX, centreY, radius;
private Color colour;

public DrawPlanes()
{
centreX = 300;
centreY = 300;
radius = 200;
colour = Color.BLACK;
}

public DrawPlanes(int centreX,int centreY, int radius, Color colour)
{
this.centreX = centreX;
this.centreY = centreY;
this.radius = radius;
this.colour = colour;

}

@Override
protected void paintComponent(Graphics g)
{

  super.paintComponent(g);
  System.out.println("ppp");
  Graphics2D g2D = (Graphics2D) g;           
  g2D.setStroke(new BasicStroke(2F));  
  g.setColor(Color.BLACK);
  g.drawOval(centreX - radius , centreY - radius, radius * 2 , radius * 2);
  ......
    }
   }

现在我无法将此类添加到我的面板中,我尝试在main中创建一个对象,然后将该对象添加到我的面板中。我也试过了

panel.add(new DrawPlanes(int x, int y, int radius,Color colour));

但它没有在面板中添加绘图。任何建议?

1 个答案:

答案 0 :(得分:1)

  • DrawPanel不是一个组件,它扩展了GUI,它也不是一个组件。
  • container.add(component)函数需要一个Component,在Swing中基本上是JComponent并且它正在扩展组件:JPanel, JLabel, JButton等。
  • DrawPanel扩展为JComponentJPanel。然而,它们基本上都是JComponent不透明而JPanel不透明的事实。