0

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;
    }
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Post an [MCVE (link)](http://stackoverflow.com/help/mcve). – user1803551 Apr 23 '14 at 22:12
  • Possibly, but there are any number of reasons that a component may not be "visible" on a container. Also, take a look at [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – MadProgrammer Apr 23 '14 at 22:12
  • I was looking over that earlier, a good bit of whats being said is above me, but ill try again. I also excluded code because my other components are working fine, i just looked up why a JComponent wouldnt show up, and preferred size issues was what I found – Kevin Knapp Apr 23 '14 at 22:15
  • 1
    [Don't use `setPreferredSize()` when you really mean to override `getPreferredSize()`](http://stackoverflow.com/q/7229226/230513). – trashgod Apr 23 '14 at 22:17
  • Ah, ha! Thank you for the comments i overrid the getPreferredSize method and just returned the dimensions i want (ill go back later and provide max possible dimension of my component). To clarify my understanding a bit. When adding a component to the layout, the getPreferredSize method is called on each component inherently so that the layout manager will know what dimensions to use when adding it to the panel. In the case of JComponents, since they dont have a natural preferred size, overriding the method call and adding in your own fixes the issue. – Kevin Knapp Apr 23 '14 at 22:36

1 Answers1

2

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • why Override getPreferredSize rather than using setPreferredSize? – Spik330 Apr 03 '17 at 00:22
  • It is generally recommend that you override `getPreferredSize`, as it maintains the single responsibility principle, it's the component's responsibility to calculate this, not someone elses. You can also have a look at [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) for more discussions on the subject. – MadProgrammer Apr 03 '17 at 00:26