Domanda

I am working on a test example at work and I need to use absolute layout. That is what the boss wants. I found a simple example on line that works and I can put my custom component on it and the frame displays just fine.

But when I try to do it on an already existing form then i get errors. What am I doing wrong?

Code:

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

    }
}

Error:

    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)
È stato utile?

Soluzione

Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI.

For more info have a look Using Top-Level Containers

JFrame is a top-level container and you can't set content pane to be null.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top