Verwenden Sie eine absolute layout innerhalb eines JScrollPane

Ich eine JScrollPane mit absoluter layoute. Ich weiß, dass die Verwendung von setLayout(null) ist nicht zu empfehlen an alle. Ich habe gelesen, dass, wenn Sie verwenden möchten, das absolute layout mit einem JScrollPane ist es notwendig, die bevorzugte Größe, Eigenschaft der Elemente im inneren, um die JScrollPane berechnen Sie seine Größe.

Ich versuche schon die nächste code-ändern der Reihenfolge und Größen von elemnts aber ich kann nicht herausfinden, wo ich war falsch.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;


public class frame extends JFrame {

private JPanel contentPane;
private JScrollPane scrollPane;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                frame frame = new frame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public frame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setLayout(null);
    setContentPane(contentPane);

    JPanel panel = new JPanel();
    panel.setBackground(Color.red);
    panel.setBounds(0,0,600,600);
    panel.setPreferredSize(new Dimension(420,280));

    scrollPane = new JScrollPane(panel);
    scrollPane.setBounds(0, 0, 600, 600);
    scrollPane.setLayout(null);
    scrollPane.setBackground(Color.green);

    scrollPane.add(panel);
    scrollPane.setPreferredSize(new Dimension(450,300));
    contentPane.add(scrollPane);
}
}

Warum setPreferredSize ist dabei nicht die richtige Arbeit?
Vielen Dank im Voraus.

Siehe auch ScrollPanePaint.
a) niemals-jemals eine null-Layout (aka: kein LayoutManager) b) niemals-jemals setXXSize

InformationsquelleAutor Jonás | 2012-08-16

Schreibe einen Kommentar