我在java中制作一个简单的gui程序。当我点击运行时,它给出了一个如下所示的错误:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Unknown Source)
at java.awt.Container.addImpl(Unknown Source)
at javax.swing.JLayeredPane.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JRootPane.setContentPane(Unknown Source)
at javax.swing.JFrame.setContentPane(Unknown Source)
at main.cool(main.java:31)
at main$1.run(main.java:43)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
这是我的代码:
import javax.swing.*;
import java.awt.Container;
import java.awt.event.*;
public class main extends JFrame implements ActionListener {
protected JButton click, fun;
public main()
{
click = new JButton("Click");
click.setActionCommand("click");
click.addActionListener(this);
add(click);
click.setSize(16, 16);
fun = new JButton("wow");
fun.setActionCommand("wow");
fun.addActionListener(this);
add(fun);
}
public static void cool()
{
JFrame frame = new JFrame("TEST!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main main = new main();
frame.setContentPane(main);
frame.setSize(128, 128);
frame.setVisible(true);
frame.setResizable(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
cool();
}
});
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if("click".equals(e.getActionCommand()))
{
System.out.println("oh right");
} else if ("wow".equals(e.getActionCommand()))
{
System.out.println("hi");
}
}
}
我相信bug可能在cool()方法中;使用setContentPane行。但不确定。任何人都可以帮助我。
答案 0 :(得分:0)
您的班级main
延伸JFrame
而不是JPanel
,因此您在另一个frame.setContentPane()
上拨打JFrame
,并且没有任何意义JFrame
内的JFrame
。将超类更改为JPanel
,错误将消失
答案 1 :(得分:0)
是;错误是在frame.setContentPanel()
课程的cool()
方法的main
中触发的。您的main
课程应extend JPanel
而不是extend JFrame
。
除了:避免声明与类名匹配的局部变量;并且,避免声明与标准方法名称相同的类名...所以,将main
类重命名为Main
(如果必须,但尝试更具描述性......也许{{ 1}}),并使您的本地变量名称不是Application
......可能main
或m
。