arrowman
arrowman

Reputation: 426

JPanel with null layout in JScrollPane - don't see elements

I want to set every element location with .setLocation(x, y)

I need a JPanel in a JScrollPane. But when I add components to JPanel, only buttons are showing. But not JLabel.

Method below is calling in JFrame constructor:

private void initGUI_test() {
    this.setSize(950, 700);
    this.setResizable(false);
    this.getContentPane().setLayout(null);

    JScrollPane mainScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    JPanel container = new JPanel();

    mainScroll.setSize(900,500);
    mainScroll.setLocation(0,100);
    mainScroll.setBorder(BorderFactory.createLineBorder(Color.blue));
    mainScroll.add(container);

    container.setLayout(null);
    container.setLocation(0, 0);
    container.setSize(900, 500);

    JLabel rowA = new JLabel();
    rowA.setSize(180, 26);
    rowA.setLocation(10, 100);
    rowA.setText("Row A");

    JButton loadButton = new JButton();
    loadButton.setSize(180, 34);
    loadButton.setLocation(290, 110);
    loadButton.setText("Load file");

    container.add(rowA);
    container.add(loadButton);

    this.getContentPane().add(mainScroll);
}

Upvotes: 0

Views: 2103

Answers (1)

ahoxha
ahoxha

Reputation: 1938

Although I agree completely with @Frakcool about null layout, the problem you are facing has a different source. You should not add components directly into JScrollPane, but into JScrollPane's ViewPort.

The line mainScroll.add(container); should be mainScroll.getViewport().add(container);

Upvotes: 3

Related Questions