Reputation:
I have tried many solutions but I do not know what is wrong with my code. Basicaly I want to display the shapes in the window, FlowLayout does not display anything and BorderLayout displays the last one which is not what I want. Ignore the shape.draw() method, it just prints coordinates of the shape. Shape extends JComponent.
package Shapes;
import javax.swing.*;
import java.awt.*;
/**
* Created by Matej on 10/12/2016.
*/
public class TestShapes extends JFrame
{
//static Shape[] shapes = new Shape[3];
public static void main(String[] args)
{
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(300,100,20);
shapes[1] = new Rectangle(100,100,40,60);
shapes[2] = new RedRectangle(200,200,20,30);
TestShapes window = new TestShapes();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(500,500);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
for(Shape shape:shapes)
{
shape.printName();
shape.draw();
panel.add(shape);
}
window.add(panel);
window.setVisible(true);
}
public void paint (Graphics g)
{
super.paint(g);
}
}
Upvotes: 0
Views: 199
Reputation: 285403
You've not shown us your code for your Shape class and subclass, but regardless you're doing it wrong, and the fix is to not have them extend JComponent. Rather make them logical not component classes, and pass them into a JPanel that holds them in an ArrayList<...>
and that draws them in its paintComponent method override. Then add this JPanel to your JFrame's contentPane, BorderLayout.CENTER, so that it may display its contained shapes.
Note that JComponents default to a preferred size of 0,0 unless they have been given other reason not to -- such as if they hold components that have preferred size or if they have an overridden getPreferredSize()
method.
But again this is moot, because you're not wanting to display each figure in its own component as this will unnecessarily limit what you can do with the images and where you can display them.
Upvotes: 1