Java, Swing


      
Java, Swing
15.06.2022

JTable, mit Zeilenbeschriftung


Manchmal möchte man auch für die Zeilen einer Tabelle eine Beschriftung, so wie es bei Tabellenkalkulationen üblich ist. Dies kann man durch eine zusätzliche Liste links neben der Tabelle erreichen.

package com.sowas.javawiki.rowheadertable;
 
import java.awt.BorderLayout;
import java.awt.Component;
 
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
 
public class RowHeaderTable extends JFrame {
   public RowHeaderTable(){
      super("Row Header Table");
 
      ListModel lm = new RowHeaderListModel();
 
      DefaultTableModel dtm = new DefaultTableModel(lm.getSize(), 4);
      JTable table = new JTable(dtm);
      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
 
      JList rowHeader = new JList(lm);
      rowHeader.setFixedCellWidth(30);
      rowHeader.setFixedCellHeight(table.getRowHeight());
      rowHeader.setCellRenderer(new RowHeaderRenderer(table));
 
      JScrollPane scroll = new JScrollPane(table);
      scroll.setRowHeaderView(rowHeader);
      getContentPane().add(scroll, BorderLayout.CENTER);
   }
 
   public static void main(String[] args){
      RowHeaderTable frame = new RowHeaderTable();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}
 
class RowHeaderListModel extends AbstractListModel{
   String strRowHeaders[] = {"1", "2", "3", "4", "5", "6", "7"};
 
   public int getSize(){
      return strRowHeaders.length;
   }
 
   public Object getElementAt(int index){
      return strRowHeaders[index];
   }
}
 
class RowHeaderRenderer extends JLabel implements ListCellRenderer{
   RowHeaderRenderer(JTable table){
      JTableHeader tableHeader = table.getTableHeader();
      setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      setHorizontalAlignment(CENTER);
      setForeground(tableHeader.getForeground());
      setOpaque(true);  // Damit der Hintergrund nicht verändert wird
      setFont(tableHeader.getFont());
   }
 
   public Component getListCellRendererComponent(JList list, Object value, int index, 
                                                 boolean fSelected, boolean fCellHasFocus){
      setText((value == null) ? "" : value.toString());
      return this;
   }
}

JTable, ein einfaches Beispiel



      
Java, Swing
15.06.2022

JTable, Spalten fixieren


Normalerweise können Spalten einfach mit der Maus verschoben werden. Möchte man dies unterbinden, so hilft Folgendes:

JTable table = new JTable(10, 20);
table.getTableHeader().setReorderingAllowed(false);

JTable, ein einfaches Beispiel



      
Java, Swing
14.06.2022

JTable, Zelle zentrieren



public class MyCellRenderer extends JLabel implements TableCellRenderer {
   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, 
                                                  boolean hasFocus, int row, int column) {
      setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
      return this;
   }
}

… und dieser muss dann noch der Tabelle zugewiesen werden:

JTable table = new JTable(..
table.setDefaultRenderer(Object.class, new MyCellRenderer());

JTable, ein einfaches Beispiel



      
Java, Swing
14.06.2022

JTable, Spaltenbreite setzen



JTable table = new JTable(10, 20);
// Erste Spalte auf 100 Pixel Breite setzen:
final int INDEX_COLUMN1 = 0;
TableColumn col = table.getColumnModel().getColumn(INDEX_COLUMN1);
col.setPreferredWidth(100);


JTable, ein einfaches Beispiel



      
Java, Swing
14.06.2022

JTable


Ein einfaches Beispiel:


setLayout(new BorderLayout());

DefaultTableModel model = new DefaultTableModel();
model.addColumn("Spalte 1", new String[] {"value row 1", "value row 2", "value row 2"});
model.addColumn("Spalte 2", new String[] {"value row 1", "value row 2", "value row 2"});
JTable table = new JTable(model);
JScrollPane pane = new JScrollPane(table);  // Für Scrollbars bei Bedarf

add(pane, BorderLayout.CENTER);

Weitere Links zu JTable:
Spaltenbreite setzen, Spalten fixieren, Zeilenbeschriftung, Zelle zentrieren



      
Java, Swing
04.01.2022

DiagramPanel



package com.sowas.diagrampanel;

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;

import javax.swing.JPanel;

/**
 * Class to make diagrams
 * 
 * License: free to use, free to modify, even for commercial use; Only this comment must be present"
 * Copyright 2019-2022 sowas.com GmbH 
 */
public abstract class DiagramPanel extends JPanel {
   private static final long serialVersionUID = -608890606773755658L;
   private int leftLabelingSpace = 20;
   private int bottomLabelingSpace = 20;
   private int widthPanel;
   private int heightPanel;
   private int xUnitIndex = 0;
   private int yUnitIndex = 0;
   private int[] xMins;
   private int[] yMins;
   private int[] xMaxs;
   private int[] yMaxs;
   private Graphics g;

   /**
    * Constructor
    * 
    * @param xMin
    * @param yMin
    * @param xMax
    * @param yMax
    */
   public DiagramPanel(int xMin, int yMin, int xMax, int yMax) {
      this(new int[] {xMin}, new int[] {yMin}, new int[] {xMax}, new int[] {yMax});
   }

   /**
    * Constructor
    * 
    * @param xMins
    * @param yMins
    * @param xMaxs
    * @param yMaxs
    */
   public DiagramPanel(int[] xMins, int[] yMins, int[] xMaxs, int[] yMaxs) {
     this.xMins = xMins;
     this.yMins = yMins;
     this.xMaxs = xMaxs;
     this.yMaxs = yMaxs;
   }
	
   @Override
   public void paintComponent(Graphics g) {
      this.g = g;
      heightPanel = getHeight();
      widthPanel = getWidth();
      FontMetrics fm = g.getFontMetrics(g.getFont());
      int maxValue = 0;
      for (int y = 0; y < yMaxs.length; y++) {
         if (yMaxs[y] > maxValue)
            maxValue = yMaxs[y];	 
      }
      leftLabelingSpace = fm.stringWidth(Integer.toString(maxValue)) + 10;

      doPaint(g);
   }

   public abstract void doPaint(Graphics g);
   
   public void drawAxis() {
      // x-Axis:
      g.drawLine(getX(xMins[xUnitIndex]), getY(yMins[yUnitIndex]), getX(xMaxs[xUnitIndex]), getY(yMins[yUnitIndex]));
      // y-Axis:
      g.drawLine(getX(xMins[xUnitIndex]), getY(yMins[yUnitIndex]), getX(xMins[xUnitIndex]), getY(yMaxs[yUnitIndex]));
   }
   
   /**
    * Draws grid lines for the diagram
    * 
    * @param color The color of the grid lines
    * @param xSpace The space between the xLines
    * @param ySpace The space between the yLines
    * @param scaleSize 
    * @param stroke A Stroke, can be null for a normal line
    */
   public void drawGridLines(Color color, int xSpace, int ySpace, int scaleSize, Stroke stroke) {
      Stroke oldStroke = null;
      Color oldColor = g.getColor();
      FontMetrics fm = g.getFontMetrics(g.getFont());
      int hStr = fm.getHeight();
      g.setColor(color);
      if (stroke != null) {
	 oldStroke = ((Graphics2D) g).getStroke();
	 ((Graphics2D) g).setStroke(stroke);
      }
      int wMaxStr = fm.stringWidth(Integer.toString(xMaxs[xUnitIndex] - 1));
      int xLastDrawed = 0;
      for (int x = 0; x < xMaxs[xUnitIndex]; x += xSpace) {
	 int x1 = getX(x);
	 if (x > 0) {
	    if (getX(xLastDrawed - xSpace) + wMaxStr > x1 - 30) 
	       continue;
	 }
	 xLastDrawed = x;
	 int y1 = getY(0);
	 g.drawLine(x1, y1 + scaleSize, x1, getY(yMaxs[yUnitIndex]));
	 String str = Integer.toString(x);
	 int wStr = fm.stringWidth(str);
   	 g.setColor(oldColor);
	 g.drawString(str, x1 - wStr/2, y1 + hStr + scaleSize - 1);
	 g.setColor(color);
      }
      for (int y = 0; y < yMaxs[yUnitIndex]; y += ySpace) {
	 int x1 = getX(0);
	 int y1 = getY(y);
	 g.drawLine(x1 - scaleSize, y1, getX(xMaxs[xUnitIndex]), y1);
	 String str = Integer.toString(y);
	 int wStr = fm.stringWidth(str);
         g.setColor(oldColor);
	 g.drawString(str, x1 - wStr - scaleSize - 2, y1 + hStr/2 - 3);
	 g.setColor(color);
      }
	  
      if (oldStroke != null)
	 ((Graphics2D) g).setStroke(oldStroke);
      g.setColor(oldColor);
	  
      if (scaleSize > 0) {
	 for (int x = 0; x < xMaxs[xUnitIndex]; x += xSpace) {
	    g.drawLine(getX(x), getY(0) + scaleSize, getX(x), getY(0));
	 }
	 for (int y = 0; y < yMaxs[yUnitIndex]; y += ySpace) {
	    g.drawLine(getX(0) - scaleSize, getY(y), getX(0), getY(y));
	 }
      }
   }

   /**
    * Draws a line in user coordinates
    * 
    * @param x1
    * @param y1
    * @param x2
    * @param y2
    */
   public void drawLine(int x1, int y1, int x2, int y2) {
      g.drawLine(getX(x1), getY(y1), getX(x2), getY(y2));
   }

   /**
    * Draws a line in user coordinates and repaints immediately
    * 
    * @param x1
    * @param y1
    * @param x2
    * @param y2
    */
   public void drawLineAndRepaint(int x1, int y1, int x2, int y2) {
      int x1Native = getX(x1);
      int y1Native = getY(y1);
      int x2Native = getX(x2);
      int y2Native = getY(y2);
      g.drawLine(x1Native, y1Native, x2Native, y2Native);
      //System.out.println("##### (" + x1Native + ", " + y1Native + "), (" + x2Native + ", " + y2Native + ")");
      int y0 = y1Native < y2Native ? y1Native : y2Native; 
      repaint(x1Native, y0, x2Native - x1Native + 1, Math.abs(y2Native - y1Native) + 1);
   }

   /**
    * Delivers the native value of x
    * 0,0 is bottom/left
    */
   public int getX(int x) {
      return leftLabelingSpace 
         + Math.round((x - xMins[xUnitIndex]) * (widthPanel - leftLabelingSpace) / (xMaxs[xUnitIndex] - xMins[xUnitIndex]));
   }

   /**
    * Delivers the native value of y
    * 0,0 is bottom/left
    */
   public int getY(int y) {
      return Math.round((yMaxs[yUnitIndex] - y) * (heightPanel - bottomLabelingSpace) / (yMaxs[yUnitIndex] - yMins[yUnitIndex]));
   }
   
   /**
    * Sets the index of xUnit
    * 
    * @param index
    */
   public void setXUnitIndex(int index) {
      xUnitIndex = index;
   }
   
   /**
    * Sets the index of yUnit
    * 
    * @param index
    */
   public void setYUnitIndex(int index) {
      yUnitIndex = index;
   }
   
   /**
    * Sets the x-Max value
    * 
    * @param xMax
    * @param index
    */
   public void setXMax(int xMax, int index) {
      xMaxs[index] = xMax;
   }

   /**
    * Delivers the x-Max value
    * 
    * @param xMax
    * @param index
    */
   public int getXMax(int index) {
      return xMaxs[index];
   }
}