Search code examples
javaswinglayoutuser-interfacejscrollpane

JScrollPane isn't working in GUI


OK, I am trying to create a GUI that has a JScrollPane that, through the JTextArea, will print out an array of ints, one line at a time. I am using some methods I created for an assignment to deal with the data, and have one of them working on the data in the following example, (I can't show the methods because it's homework that isn't due yet). The methods have been tested and work fine, so no need for them in this question. So far, either the text area will show up in the GUI, but not have the scroll pane attached to it, or only the jlabel will show up with the results of the work done via the method. Can someone have a look at my code and tell me what I am doing wrong, because I have gone over this like 50 times, and cannot get the GUI to behave.

public class MyClassName extends JFrame{

private JScrollPane myScroll;
private JTextArea myTextArea;
private JLabel myMean;
private JLabel myMedian;
private JLabel myMax;
private JLabel myMin;
private JLabel mySum;
private Container content;
private Font myFont;
private SpringLayout layout;


private MyClassName() {
    this(500,300,"TEST TITLE");
}

private MyClassName(int width, int height, String title)
{
    this.setVisible(true);
    this.setTitle(title);
    this.setSize(width, height);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiComponent();
}

public void guiComponent()
{
    layout = new SpringLayout();
    content = this.getContentPane();

    int [] test = {50,37,43,12,8,16,32,44,78,92,1,3,66,34};

    myTextArea = new JTextArea();

    myScroll = new JScrollPane(myTextArea);
    content.add(myScroll);

    myMean = new JLabel("MEAN : " + MyClassName.mean(test));
    for(int count : test)
    {
        String z = Integer.toString(count);
        myTextArea.append('\n' + z);
    }

    myFont = new Font("Serrif", Font.BOLD, 30);
    myMean.setFont(myFont);

    content.add(myScroll);
    layout.putConstraint(SpringLayout.WEST, myScroll, 20, SpringLayout.WEST, content);
    layout.putConstraint(SpringLayout.NORTH, myScroll, 25, SpringLayout.NORTH, content);

    content.add(myMean);
    layout.putConstraint(SpringLayout.WEST, myMean, 20, SpringLayout.EAST, myScroll);
    layout.putConstraint(SpringLayout.NORTH, myMean, 25, SpringLayout.NORTH, content);
}

public static double mean(int[] ar) {
    double x = 0;
    for (int i = 0; i < ar.length; i++) {
        x += ar[i];
    }
    return x / ar.length;
}

public static void main(String[] args) {

    MyClassName test2 = new MyClassName();
}

Solution

  • Your problem when you need to display the components in layout, to solve your problem add those three line after initialize 'myTextArea' component:

    myTextArea.setColumns(20);
    myTextArea.setRows(5);
    getContentPane().setLayout(layout);
    

    you maybe need to read this link about Layout.