我正在工作一个测试示例,我需要使用绝对布局。那就是老板想要的。我在网上找到了一个简单的示例,该示例可以正常工作,并且可以在其中放置自定义组件,并且框架显示得很好。

但是,当我尝试在已经存在的表单上执行操作时,我会收到错误消息。我究竟做错了什么?

码:

package testpak;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;

import java.awt.*;
import java.awt.event.ActionEvent;

public class FrameDemo {
    JFrame frame = new JFrame("Test Custom Component");
    JPanel panel = new JPanel();
    ImageIcon imageForOne = new ImageIcon(getClass().getResource("stop.jpg"));
    JButton MyTestButton = new JButton("",imageForOne);

    MyComponent cc = new MyComponent();
    //MyComponent cc = new MyComponent(20,50);

    FrameDemo() {
         setLookFeel();

         MyTestButton.setPreferredSize(new Dimension(75, 75));

         JButton one = new JButton(new OneAction());
         one.setPreferredSize( new Dimension(55, 55));

         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setContentPane(null);
         frame.pack();
        // panel.add(cc);

         MyTestButton.setBounds(10, 10, 30, 30);
         panel.add(MyTestButton);
         one.setBounds(100, 50, 40, 40);
         panel.add(one);
         frame.add(panel);
         frame.setSize(new Dimension(200, 200));
         frame.setVisible(true);
    }

    private void setLookFeel() {
         try {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         } catch (Exception ex) {

         }
    }

    public static void main(String[] args) {
       FrameDemo fd = new FrameDemo();
    }
}

class OneAction extends AbstractAction {
    private static final long serialVersionUID = 1L;

    public OneAction() {
        ImageIcon imageForOne = new ImageIcon(getClass().getResource("help.jpg"));
        putValue(LARGE_ICON_KEY, imageForOne);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
}


错误:

    Exception in thread "main" java.awt.IllegalComponentStateException: contentPane    cannot be set to null.
at javax.swing.JRootPane.setContentPane(JRootPane.java:620)
at javax.swing.JFrame.setContentPane(JFrame.java:693)
at testpak.FrameDemo.<init>(FrameDemo.java:31)
at testpak.FrameDemo.main(FrameDemo.java:53)

最佳答案

每个顶层容器都有一个内容窗格,通常来说,该窗格包含(直接或间接)该顶层容器的GUI中的可见组件。


有关更多信息,请参见Using Top-Level Containers

JFrame是顶级容器,您不能将内容窗格设置为null

07-26 06:07