Question

So after a bit of research I'm leaning toward needing to specify the preferred size of my JComponent before hand, since JComponent doses't really have a preferred size inherently.

Would adding a preferred size to my JComponent fix the issue with it displaying on my panel?

And if this is the way to fix the issue whats the best way to go about doing it? Ive read different people saying use setPreferedSize and others saying you shouldn't use this method at all.

import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.ComponentOrientation;

public class ArrayViewer 
{
    static int[] array;
    static int[] sortedArray;

    public static void main(String[] args)
    {
        int size=0;
        Scanner in=new Scanner(System.in);
        //ask for the size of the array until the user enters a size in the right range
        do
        {
            System.out.print("Enter the size of the array (should be between 10 and 100): ");
            size=in.nextInt();
        }
        while (size<10 || size>100);

        JFrame frame = new JFrame();
        frame.setSize(1000,1000);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        array= ArrayUtil.randomIntArray(size,200);//create a random array of given size and entries ranging from 0 to 100
        System.out.println(ArrayUtil.printArray(array));



        //Set up the content pane.
        addComponentsToPane(frame.getContentPane());

        //Display the window.
        frame.pack();
        frame.setVisible(true);


    }

    public static void addComponentsToPane(Container pane) 
    {
        pane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        //For each component to be added to this container:

        ArrayComponent arrayGraph = new ArrayComponent(array, false);
        //...Set instance variables in the GridBagConstraints instance...
        c.ipady = 0;       //reset to default
        c.weighty = 0.0;   //request any extra vertical space
        c.anchor = GridBagConstraints.PAGE_END; //bottom of space
        c.insets = new Insets(0,0,0,0);  //no padding
        c.gridx = 0;       //begins in 1st cell of..
        c.gridwidth = 2;   //2 columns wide
        c.gridy = 1;       //2nd row
        pane.add(arrayGraph, c);


}

ArrayComponent class

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import javax.swing.JComponent;

public class ArrayComponent extends JComponent
{
    // instance variables - replace the example below with your own
    int[] theArray;
    int highlightIndex;
    boolean sorted;

    /**
     * Constructor for objects of class ArrayComponent
     */
    public ArrayComponent(int[] input, boolean sorted)
    {
        // initialise instance variables
        theArray = input;
        this.sorted = sorted;
    }

    public void paintComponent(Graphics g)
    {
        if (sorted == false)
        {
            Graphics2D g2 = (Graphics2D)g;
            int x = 25;
            int size = theArray.length;
            for(int i = 0; i<size; i++)
            {

                g2.drawRect(x,15,5,theArray[i]);
                x = x+10;    
            }

        }

    }
}

ArrayUtil class

public class ArrayUtil
{
    private static Random generator = new Random();

    /**
    Creates an array filled with random values.
    @param length the length of the array
    @param n the number of possible random values
    @return an array filled with length numbers between
    0 and n - 1
     */
    public static int[] randomIntArray(int length, int n)
    {  
        int[] a = new int[length];      
        for (int i = 0; i < a.length; i++)
            a[i] = generator.nextInt(n);

        return a;
    }

    public static String printArray(int[] array)
    {
        String str=("array=[");
        int k=0;
        for (k=0;k<array.length-1;k++)
            str=str+array[k]+", ";              
        str=str+array[k]+"]";
        return str;
    }
Was it helpful?

Solution

Override getPreferredSize rather than using setPreferredSize

You can also affect the size using GridBagLayout by specifying the fill property and changing the weightx/y property

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top