“线程中的异常”;“主要”;java.lang.IllegalArgumentException:添加容器';他是自己的父母
我试图将GUI添加到我的netbeans项目中,但收到一条错误消息: 线程“main”java.lang.IllegalArgumentException中的异常:添加 容器的父容器在 checkAddToSelf(Container.java:472)位于 addImpl(Container.java:1083)位于 add(Container.java:410)位于 cylinder.cylinder.(cylinder.java:38)位于 cylinder.cylinder.main(cylinder.java:68)java结果:1“线程中的异常”;“主要”;java.lang.IllegalArgumentException:添加容器';他是自己的父母,java,swing,Java,Swing,我试图将GUI添加到我的netbeans项目中,但收到一条错误消息: 线程“main”java.lang.IllegalArgumentException中的异常:添加 容器的父容器在 checkAddToSelf(Container.java:472)位于 addImpl(Container.java:1083)位于 add(Container.java:410)位于 cylinder.cylinder.(cylinder.java:38)位于 cylinder.cylinder.main(c
这是因为这行代码
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();
}
}
解决方案:将此行更改为添加(p)代码>因为您无法将面板放入自身。我相信你的目标是把面板放在你继承的
JFrame
上。p.add(p)代码>。这就是为什么。消息是非常明确的。除了将p
添加到p
之外,您还需要将p
添加到中。此(JFrame)代码编写非常重要。但是试试Netbean的JFrame表单
p.add(p);