为什么我不能为绝对布局设置框架frame.setcontentPane(null)?

时间:2014-05-13 19:30:58

标签: java swing jframe

我正在研究工作中的测试示例,我需要使用绝对布局。这就是老板想要的。我找到了一个简单的线上示例,我可以将自定义组件放在上面,框架显示得很好。

但是当我尝试在已有的表单上执行此操作时,我会收到错误。我做错了什么?

代码:

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)

1 个答案:

答案 0 :(得分:2)

  

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

有关详情,请查看Using Top-Level Containers

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