Search code examples
layoutswingx

Use of setPreferredSize is disregarded by program


How do I successfully call setPreferredSize in a method? I'm calling setPreferredSize twice. If I remove the call inside the constructor, the panel doesn't appear at all, whereas it had earlier appeared with the undesired size (500,300). This demonstrates that setPreferredSize is being executed in the constructor, but not in the method of the same class. Note that this is the only issue (as far as I have tested) with my code; there's no unexpected interference outside the code below.

...
public abstract class XYGrapher extends JPanel{
    ...
    JFrame frame;
    JPanel contentPane;
    ...
    public XYGrapher() {
        frame = new JFrame("Grapher");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane = new JPanel();
        contentPane.setPreferredSize(new Dimension(500, 300));
        contentPane.setLayout(new SpringLayout());
        this.setPreferredSize(new Dimension(500, 300));
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setVisible(true);
        contentPane.add(this);
    }
    //
    public void drawGraph(int xPixelStart, int yPixelStart, int pixelsWide, int pixelsHigh) {
        ...
        contentPane.setPreferredSize(new Dimension(pixelsWide, pixelsHigh));
        this.setPreferredSize(new Dimension(pixelsWide, pixelsHigh));
        ...
    }
    //*/
}

For reference, this is how XYGrapher eventually gets used:

public class GrapherTester extends XYGrapher{
    ...
    public static void main(String[] args) {
            GrapherTester g = new GrapherTester();
            g.drawGraph(0,0,100,100);
    }
}

Solution

  • I have managed to fix the issue in the meantime. Simply add

    frame.pack();
    

    to the method.