Java TableLayout Beispiel / Example

Posted: Dezember 13th, 2011 | Filed under: Java, Programmieren | Tags: , , , , , | 1 Comment »

Oft benutzte ich in meinen Anwendungen das praktische TableLayout. Es ist standardmäßig kein Bestandteil von Java, ihr könnt euch jedoch die Bibliothek hier herunterladen: http://java.sun.com/products/jfc/tsc/articles/tablelayout/apps/TableLayout.jar

Mit dem TableLayout könnt ihr folgende Größen definieren:

  • Prozentuale (in Prozent 0.5 = 50%)
  • Absolute (Pixel 200 = 200 Pixel)
  • Relative (TableLayout.FILL = den restlichen Platz verwenden)

Also Beispiel hier mehrere Buttons:

  • Spalten: 40%, 30%, TableLayout.FILL
  • Reihen: 200 Pixel, TableLayout.FILL

image

Hier der Quellcode:

import info.clearthought.layout.TableLayout;

import java.awt.EventQueue;

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

public class TableLayoutTutorial extends JFrame {

  private JPanel contentPane;

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

  /**
   * Create the frame.
   */
  public TableLayoutTutorial() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100100450300);
    contentPane = new JPanel();
    
    double[][] layout = new double[][]{
        // X-Achse
        {0.40.3, TableLayout.FILL},
        
        // Y-Achse
        {200, TableLayout.FILL}
    };

    TableLayout contentPaneLayout = new TableLayout(layout);
    contentPane.setLayout(contentPaneLayout);
    setContentPane(contentPane);
    
    // "0,0" X-Position, Y-Position
    contentPane.add(new JButton("40% / 200")"0,0");
    contentPane.add(new JButton("30% / 200")"1,0");
    contentPane.add(new JButton("REST / 200")"2,0");
    
    contentPane.add(new JButton("40% / REST")"0,1");
    contentPane.add(new JButton("30% / REST")"1,1");
    contentPane.add(new JButton("REST / REST")"2,1");
  }

}