I'm trying to put all the buttons (and their icons) into a single class. However, when I try to draw just one button in a frame, it doesn't show up. I can get it to be displayed if I instantiate the button in the same class as the Frame, but not in a separate class. Not sure what I'm doing wrong here :|

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;

public class ShapeDisplayer
{
   public static void main(String[] args)
   {
      ShapeFrame frame = new ShapeFrame();


  //    frame.addShape(new SnowMan(0,0,20));
      frame.addShape(new Car(0,0, 50));

      // frame.addShape(create your composite shape here);

      frame.setSize(300, 400);
      frame.setTitle("Shape Displayer");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);

   }
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ShapeFrame extends JFrame
{
	public ShapeFrame()
	{
		box = new Box();
	}
	public void addShape(CompositeShape aShape)
	{
		box.add(aShape);
		add(box);
	}
	private Box box;
	private ShapePanel panel;
}
import java.awt.*;
import javax.swing.*;
import java.util.*;

public class Box extends JComponent
{
	public Box()
	{
		
	}
	public void add(CompositeShape aShape)
	{
		Rectangle temp = aShape.getBounds();
		int width = (int)temp.getWidth();
		int height = (int)temp.getHeight();

		JButton aButton = new JButton(new ShapeIcon(aShape, width, height));
	}
	private ShapeIcon shape;
}
public void add(CompositeShape aShape)
	{
		Rectangle temp = aShape.getBounds();
		int width = (int)temp.getWidth();
		int height = (int)temp.getHeight();

		JButton aButton = new JButton(new ShapeIcon(aShape, width, height));
	}

The button only exists in the add method. You declare it then that's it, you are not doing anything with it. No one outside the method can see it. It is not even part of the Box class. You should declare as a private attribute in the Box class and use get method. Then you should add it in the frame that you are displaying.

Suggestion: have Box extend JButton

Hi,

I changed my add method so that it returns a JButton and it works fine. One thing I forgot to mention though was that the Box class was supposed to be a container of Buttons (each button has an icon on it). From what I understand about containers, I'm supposed to design each component separately and then place each individual part into the container. Then I can simply take that container (in addition to another container called ShapePanel) and add it to the Frame container (am I right about this?). This will give me a GUI that I can use. From an OO perspective, is it correct to use what you suggested?

This article has been dead for over six months. Start a new discussion instead.