【问题标题】:Why can i not set the frame frame.setcontentPane(null) for an absolute layout?为什么我不能为绝对布局设置框架 frame.setcontentPane(null)?
【发布时间】:2014-05-13 19:30:58
【问题描述】:

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

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

代码:

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)

【问题讨论】:

  • 你为什么要这么做?为什么将内容窗格设置为null?你想达到什么目标?

标签: java swing jframe


【解决方案1】:

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

更多信息请查看Using Top-Level Containers

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

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 2021-01-17
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多