I created a program from a book I am reading on java. The program is using swing to make a frame that shows buttons. It compiled without any error, but I ran into an error while trying to run the program.

here is the code:

import javax.swing.*;
public class ButtonFrame extends JFrame
	JButton load = new JButton("Load");
	JButton save = new JButton("Save");
	JButton unsubscribe = new JButton("Unsubscribe");
	public ButtonFrame()
		setSize(80, 170);
		JPanel pane = new JPanel();
	public static void main(String[] arguments)
		ButtonFrame bf = new ButtonFrame();

Here is the error when I try to run it:

java.lang.Error: Do not use ButtonFrame.add() use ButtonFrame.getContentPane().add() instead
		at javax.swing.JFrame.createRootPaneException(JFrame.java:465)
		at javax.swing.JFrame.addImpl(JFrame.java:491)
		at java.awt.Container.add(Container.java:307)
		at ButtonFrame.<init>(ButtonFrame.java:19)
		at ButtonFrame.main(ButtonFrame.java:25)
Exception in thread "main" 
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

Thanks in advance

Recommended Answers

All 4 Replies

Just as I thought. Some older versions of java are funny about how things are added. You actually have to include a call to get the content pane even thought you shouldn't.

Change this Line:


to this


I would suggest getting into the habit of creating a Container. If your use swing you should always use a Container:

Container content = getContentPane();

You could also escape that error that way(Which I reccomed);

Thanks for the help, that solved it.

Hi everyone,

Remember that in awt only you can add directly to the Frame but with swing you will have to get the container first and add the require jcomponents to the container

Richard West

Thanks for the advice. I think the book I am reading is getting up to containers but I haven't reached that point just yet. But thanks for the advice.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.