Warum wird das JLabel falsch verschoben?

yachty66

Mitglied
Der folgende Code gibt ein JPanel als GUI aus, im mitgesendeten Foto seht ihr einen Fehler bei dem Label "N/A", das Label ist linkseingerückt - ich verstehe allerdings nicht warum --> eigentlich müsste es in der selben Zeilenposition in der jeweiligen Spalte sein. Weiß jemand, wo da der Fehler liegt?

Java:
public Component GridBagLayoutM() {
        //1. Initialisieren des Panels und Übergabe, des zu verwendenden LayoutManagers
        JPanel p = new JPanel(new GridBagLayout());
        //2. Initialisieren der GridBagConstraints
        GridBagConstraints gbc = new GridBagConstraints();
        GridBagConstraints c = new GridBagConstraints();
        //3. Initialisieren der Komponenten
        JLabel intensityRatioLabel = new JLabel("Intensity ratio:");
        JLabel ratioCutoffLabel = new JLabel("Ratio cutoff:");
        JLabel resultLabel = new JLabel("Result:");
        JLabel backgroundCorrectionLabel = new JLabel("Background correction?");
        JLabel emptyLabel = new JLabel("N/A");
        JLabel emptyLabel2 = new JLabel("N/A");
        JLabel emptyLabel3 = new JLabel("N/A");


        //4. benötigte GridBagConstraints-Attribute konfigurieren
        gbc.gridx = 0; //Spalte 1 (Zählung beginnt bei 0)
        gbc.gridy = 0; //Zeile 0
        gbc.anchor = GridBagConstraints.LINE_START;
        c.gridx = 1;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_END;

        //5. Komponente ins Layout setzen
        p.add(emptyLabel, c);
        p.add(intensityRatioLabel, gbc);

        //wie 4. -> Attribute können wieder verwendet werden
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.LINE_START;
        c.gridx = 2;
        c.gridy = 1;
        c.anchor = GridBagConstraints.LINE_END;


        //wie 5.
        p.add(emptyLabel2, c);
        p.add(ratioCutoffLabel, gbc);

        //wie 4. -> Attribute können wieder verwendet werden
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.anchor = GridBagConstraints.LINE_START;
        c.gridx = 2;
        c.gridy = 2;
        c.anchor = GridBagConstraints.LINE_END;


        //wie 5.
        p.add(emptyLabel3, c);
        p.add(resultLabel, gbc);

        //wie 4. -> Attribute können wieder verwendet werden
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.anchor = GridBagConstraints.LINE_START;


        //wie 5.
        p.add(backgroundCorrectionLabel, gbc);

        return p;
    }

    public MainFrame() {
        super("Test");
        setSize(700, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(GridBagLayoutM(), BorderLayout.WEST);
        init();
        pack();
        setVisible(true);
    }
 

Anhänge

  • Bildschirmfoto 2021-07-21 um 12.00.51.png
    Bildschirmfoto 2021-07-21 um 12.00.51.png
    47 KB · Aufrufe: 3

Zurück
Oben