Java Swing Drawing Rectangles

258 views Asked by At

I'm trying to visualize values in an Integer Array. They are supposed to be like a bar graph, but just the bars no axis etc Im using Java Swing for the GUI. This is supposed to draw just one rectangle for now, but no matter how high I increase the height in g.fillRect(0,0,width,height) it is drawn as a square.

Here is my code:

public class MyClass extends JPanel
{
...

public void paint(Graphics g)
{
    g.fillRect(0,0,10,100);
}

public void draw()
{
    JFrame myframe = new JFrame("FrameTest");
    myframe.setSize(new Dimension (groesse,groesse));
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    JPanel mypanel = new JPanel();
    mypanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    mypanel.setSize(new Dimension(256,256));

    mypanel.add(new MyClass(),BorderLayout.SOUTH);

    myframe.add(mypanel,BorderLayout.SOUTH);

    myframe.setVisible(true);
}

I would love to post a picture of the output but SO doesn't want me to...

2

There are 2 answers

0
camickr On
mypanel.setSize(new Dimension(256,256));

Don't use setSize().

Custom painting is done by overriding the paintComponent() method of your class and don't forget to invoke super.paintComponent(...). You would also override the getPreferredSize() method to return the Dimension of your custom painting.

Now your component will have a preferred size and the layout manager can do its job.

Read the section from the Swing tutorial on Custom Painting for more information and working examples.

mypanel.add(new MyClass(),BorderLayout.SOUTH);

A JPanel uses a FlowLayout by default. Specifying a BorderLayout constraint does nothing. You don't even need this panel, so get rid of it and just add the rectangle panel to the frame.

3
Jean-Baptiste Yunès On

Use BorderLayout not FlowLayout. Don't add two components in the same BorderLayout area. Put your MyClass instance in BorderLayout.CENTER.

Also override the getPreferredSize method of MyClass to an appropriate value (the size of your drawing area), and forget setSize; use pack to pack your frame before making it visible.

And finally, don't override paint when using swing but paintComponent.