2016-05-06 4 views
0

Dieser Code generiert drei Schaltflächen. Der Knopf "Eins" erscheint im "Norden" und deckt teilweise den "Zwei" -Button im Osten ab. Knopf drei erscheint im Südwesten. Wie bekomme ich das gleiche Layout mit überlappender Taste 1 und 2, aber ohne Taste drei?Wie funktionieren die GridBagConstraints für überlappende Objekte?

import java.awt.Component; 
import java.awt.Container; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.Insets; 

import javax.swing.JButton; 
import javax.swing.JFrame; 

public class GridBagButtons { 
    private static final Insets insets = new Insets(0, 0, 0, 0); 

    public static void main(final String args[]) { 
    final JFrame frame = new JFrame("GridBagLayout"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLayout(new GridBagLayout()); 
    JButton button; 
    // Row One - Three Buttons 
    button = new JButton("One"); 
    addComponent(frame, button, 0, 0, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH); 
    button = new JButton("Two"); 
    addComponent(frame, button, 1, 0, 1, 2, GridBagConstraints.CENTER, GridBagConstraints.BOTH); 

    button = new JButton("Three"); 
    addComponent(frame, button, 0, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH); //Comment out this 

    frame.setSize(500, 200); 
    frame.setVisible(true); 
    } 
    private static void addComponent(Container container, Component component, int gridx, int gridy, 
     int gridwidth, int gridheight, int anchor, int fill) { 
    GridBagConstraints gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0, 1.0, 
    anchor, fill, insets, 0, 0); 
    container.add(component, gbc); 
    } 
    } 

Auskommentieren Button drei ändert das Layout. Knopf eins deckt Knopf zwei vollständig ab. [modifizierter] Code kommt von hier http://www.java2s.com/Tutorial/Java/0240__Swing/UsingGridBagConstraints.htm

Antwort

1

Versuchen Sie explizit, die Grid-Größe im GridBagLayout-Konstruktor festzulegen.

d.h.

frame.setLayout(new GridBagLayout(2, 2)); 
Verwandte Themen