线程" main"中的例外情况java.lang.IllegalArgumentException:将容器的父级添加到自身

时间:2015-07-29 08:56:56

标签: java swing

import java.awt.FlowLayout;  
import java.awt.event.*;  
import javax.swing.*;  
public class Cylinder extends JFrame implements ActionListener{  

    JLabel lblRadius = new JLabel("Enter the Radius");  
    JLabel lblHeight = new JLabel("Enter the Height");  
    JTextField txtRadius  = new JTextField(10);  
    JTextField txtHeight = new JTextField(10);  
    JButton btnCalculate = new JButton("Calculate");  
    JButton btnClear = new JButton("Clear");  
    JTextField txtOutput = new JTextField(20);  
    JPanel p = new JPanel();  
    FlowLayout layout;  
    public Cylinder(){  
        super("Calculator");  
        setSize(300,300);  
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        layout = new FlowLayout();  
        p.setLayout(layout);  
        p.add(lblRadius);  
        p.add(txtRadius);  
        p.add(lblHeight);  
        p.add(txtHeight);  
        p.add(btnCalculate);  
        p.add(btnClear);  
        p.add(txtOutput);  
        p.add(p);  

        setVisible(true);  

        btnCalculate.addActionListener(this);  
        btnClear.addActionListener(this);  
    }  

    @Override  
    public void actionPerformed(ActionEvent e) {  
        Object source = e.getSource();  
        int radius = Integer.parseInt(txtRadius.getText());  
        int height = Integer.parseInt(txtHeight.getText());  
        if (source.equals(btnCalculate)){  
            double volume = (Math.PI * radius * radius)*height;  
            txtOutput.setText("The Volume is: "+ Math.round(volume));  
        }  

        if (source.equals(btnClear)){  
            txtRadius.setText("");  
            txtHeight.setText("");  
            txtOutput.setText("");  
        }  
    }  
    public static void main(String[] args) {  
         new Cylinder();  
    }  
}  

我正在尝试向我的netbeans项目添加GUI但是收到错误消息:

  

线程中的异常" main" java.lang.IllegalArgumentException:添加   容器的父母自己   java.awt.Container.checkAddToSelf(Container.java:472)at   java.awt.Container.addImpl(Container.java:1083)at   java.awt.Container.add(Container.java:410)at   cylinder.Cylinder。(Cylinder.java:38)at   cylinder.Cylinder.main(Cylinder.java:68)Java结果:1

1 个答案:

答案 0 :(得分:2)

因为这行代码

p.add(p); 

解决方案:将此行更改为add(p);,因为您无法将面板放入自身。我相信你的目标是将面板放在你继承的JFrame上。