kevinlinxp
12/31/2016 - 3:11 AM

Java:Swing

Java:Swing

KeyEvent evt = new KeyEvent(jf, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, 0, '\n');
EventQueue eq = jf.getToolkit().getSystemEventQueue();
eq.postEvent(evt);
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

/**
 * Utility class for creating UI components
 */
public class SwingUIUtils
{

  public static final Dimension Dimension_30_20 = new Dimension(30, 20);
  public static final Dimension Dimension_40_20 = new Dimension(40, 20);
  public static final Dimension Dimension_50_20 = new Dimension(50, 20);
  public static final Dimension Dimension_60_20 = new Dimension(60, 20);
  public static final Dimension Dimension_70_20 = new Dimension(70, 20);
  public static final Dimension Dimension_80_20 = new Dimension(80, 20);
  public static final Dimension Dimension_90_20 = new Dimension(90, 20);
  public static final Dimension Dimension_100_20 = new Dimension(100, 20);
  public static final Dimension Dimension_150_20 = new Dimension(150, 20);
  public static final Dimension Dimension_200_20 = new Dimension(200, 20);
  public static final Dimension Dimension_350_20 = new Dimension(350, 20);
  public static final Dimension Dimension_450_20 = new Dimension(450, 20);
  public static final Dimension Dimension_400_600 = new Dimension(400, 600);
  public static final Dimension Dimension_800_600 = new Dimension(800, 600);

  private UIUtils()
  {
  }

  /**
   * Return a JLabel, width 30, height 20, right alignment
   */
  public static JLabel createLabel_30_20(String text)
  {
    return createLabel_30_20(text, SwingConstants.RIGHT);
  }

  /**
   * Return a JLabel, width 40, height 20, right alignment
   */
  public static JLabel createLabel_40_20(String text)
  {
    return createLabel_40_20(text, SwingConstants.RIGHT);
  }

  /**
   * Return a JLabel, width 50, height 20, right alignment
   */
  public static JLabel createLabel_50_20(String text)
  {
    return createLabel_50_20(text, SwingConstants.RIGHT);
  }

  /**
   * Return a JLabel, width 60, height 20, right alignment
   */
  public static JLabel createLabel_60_20(String text)
  {
    return createLabel_60_20(text, SwingConstants.RIGHT);
  }

  /**
   * Return a JLabel, width 70, height 20, right alignment
   */
  public static JLabel createLabel_70_20(String text)
  {
    return createLabel_70_20(text, SwingConstants.RIGHT);
  }

  /**
   * Return a JLabel, width 80, height 20, right alignment
   */
  public static JLabel createLabel_80_20(String text)
  {
    return createLabel_80_20(text, SwingConstants.RIGHT);
  }

  /**
   * Return a JLabel, width 150, height 20, right alignment
   */
  public static JLabel createLabel_150_20(String text)
  {
    return createLabel_150_20(text, SwingConstants.RIGHT);
  }

  /**
   * Return a JLabel, width 30, height 20
   */
  public static JLabel createLabel_30_20(String text, int alignment)
  {
    return createLabel(text, alignment, Dimension_30_20);
  }

  /**
   * Return a JLabel, width 40, height 20
   */
  public static JLabel createLabel_40_20(String text, int alignment)
  {
    return createLabel(text, alignment, Dimension_40_20);
  }

  /**
   * Return a JLabel, width 50, height 20
   */
  public static JLabel createLabel_50_20(String text, int alignment)
  {
    return createLabel(text, alignment, Dimension_50_20);
  }

  /**
   * Return a JLabel, width 60, height 20
   */
  public static JLabel createLabel_60_20(String text, int alignment)
  {
    return createLabel(text, alignment, Dimension_60_20);
  }

  /**
   * Return a JLabel, width 70, height 20
   */
  public static JLabel createLabel_70_20(String text, int alignment)
  {
    return createLabel(text, alignment, Dimension_70_20);
  }

  /**
   * Return a JLabel, width 80, height 20
   */
  public static JLabel createLabel_80_20(String text, int alignment)
  {
    return createLabel(text, alignment, Dimension_80_20);
  }

  /**
   * Return a JLabel, width 150, height 20
   */
  public static JLabel createLabel_150_20(String text, int alignment)
  {
    return createLabel(text, alignment, Dimension_150_20);
  }

  /**
   * Return a JLabel with specified params
   */
  public static JLabel createLabel(String text, int alignment, Dimension d)
  {
    JLabel label = new JLabel(text, alignment);
    label.setHorizontalAlignment(alignment);
    label.setPreferredSize(d);
    return label;
  }

  public static JTextField createTextField_60_20()
  {
    JTextField tf = createTextField();
    tf.setPreferredSize(Dimension_60_20);
    return tf;
  }

  public static JTextField createTextField_60_20_numeric()
  {
    JTextField tf = createTextField_60_20();
    tf.setDocument(new NumericConstrainedDoc());
    return tf;
  }

  public static JTextField createTextField_150_20()
  {
    JTextField tf = createTextField();
    tf.setPreferredSize(Dimension_150_20);
    return tf;
  }

  public static JTextField createTextField_150_20_numeric()
  {
    JTextField tf = createTextField_150_20();
    tf.setDocument(new NumericConstrainedDoc());
    return tf;
  }

  public static JTextField createTextField_150_20_alphanumeric()
  {
    JTextField tf = createTextField_150_20();
    tf.setDocument(new AlphanumericConstrainedDoc());
    return tf;
  }

  public static JTextField createTextField_350_20()
  {
    JTextField tf = createTextField();
    tf.setPreferredSize(Dimension_350_20);
    return tf;
  }

  public static JTextField createTextField_450_20()
  {
    JTextField tf = createTextField();
    tf.setPreferredSize(Dimension_450_20);
    return tf;
  }

  public static JTextField createTextField()
  {
    JTextField tf = new JTextField();
    return tf;
  }

  private static class NumericConstrainedDoc extends PlainDocument
  {
    private static final long serialVersionUID = 8108496883271314447L;

    private Pattern p = Pattern.compile("[\\d]*\\.{0,1}[\\d]*");

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
    {
      String proposedInsert = getText(0, offs) + str + getText(offs, getLength() - offs);
      if (p.matcher(proposedInsert).matches())
        super.insertString(offs, str, a);
    }
  }

  public static class PatternConstrainedDoc extends PlainDocument
  {
    private List<Pattern> patternList = new ArrayList<Pattern>();

    public void addPattern(Pattern p)
    {
      patternList.add(p);
    }

    public void removePattern(Pattern p)
    {
      patternList.remove(p);
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
    {
      String proposedResult = getText(0, offs) + str + getText(offs, getLength() - offs);
      for (int i = 0; i < patternList.size(); i++)
      {
        if (!patternList.get(i).matcher(proposedResult).matches())
        {
          return;
        }
      }
      super.insertString(offs, str, a);
    }

    @Override
    public void remove(int offs, int len) throws BadLocationException
    {
      String proposedResult = getText(0, offs) + getText(offs + len, getLength() - len - offs);
      for (int i = 0; i < patternList.size(); i++)
      {
        if (!patternList.get(i).matcher(proposedResult).matches())
        {
          return;
        }
      }
      super.remove(offs, len);
    }
  }

  private static class AlphanumericConstrainedDoc extends PlainDocument
  {
    private static final long serialVersionUID = 8108496883271314447L;

    private Pattern p = Pattern.compile("[a-zA-Z0-9]*");

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
    {
      String proposedInsert = getText(0, offs) + str + getText(offs, getLength() - offs);
      if (p.matcher(proposedInsert).matches())
        super.insertString(offs, str, a);
    }
  }

  public static JTextField getNumberFormatWithPercentCharTxtField()
  {
    JTextField tf = createTextField();
    tf.setPreferredSize(Dimension_450_20);
    tf.setDocument(new NumericWithPercentCharDoc());
    return tf;
  }

  private static class NumericWithPercentCharDoc extends PlainDocument
  {
    private static final long serialVersionUID = -2950492565766085667L;

    private Pattern p = Pattern.compile("[\\d]*\\.{0,1}[\\d]*[\\d%]{0,1}");

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
    {
      String proposedInsert = getText(0, offs) + str + getText(offs, getLength() - offs);
      if (p.matcher(proposedInsert).matches())
        super.insertString(offs, str, a);
    }
  }

  private static void changeTxtComponentBackground(Component txtComp, boolean changeTxtFieldBg,
          boolean changeTextAreaBg)
  {
    if (!(txtComp instanceof JTextComponent))
    {
      return;
    }
    if (txtComp instanceof JTextField)
    {
      if (changeTxtFieldBg)
      {
        txtComp.setBackground(UIManager.getColor("TextField.inactiveBackground"));
      }
      else
      {
        txtComp.setBackground(UIManager.getColor("TextField.background"));
      }
    }
    else
    {
      if (changeTextAreaBg)
      {
        txtComp.setBackground(UIManager.getColor("TextField.inactiveBackground"));
      }
      else
      {
        txtComp.setBackground(UIManager.getColor("TextField.background"));
      }
    }
  }

  public static void setToViewOnly(Component comp, boolean changeTxtFieldBg, boolean changeTextAreaBg)
  {
    if (comp != null)
    {
      if (comp instanceof JTextComponent)
      {
        JTextComponent textComp = (JTextComponent) comp;
        textComp.setEditable(false);
        changeTxtComponentBackground(comp, changeTxtFieldBg, changeTextAreaBg);
        textComp.setForeground(UIManager.getColor("TextField.foreground"));
      }
      else if (comp instanceof JComboBox)
      {
        changeTxtComponentBackground(comp, changeTxtFieldBg, changeTextAreaBg);
      }
      else if (comp instanceof JScrollPane)
      {
      }
      else if (comp instanceof JLabel)
      {
      }
      else if (comp instanceof JScrollBar)
      {
      }
      else
      {
        comp.setEnabled(false);
      }
    }
    if (comp instanceof Container)
    {
      Container container = (Container) comp;
      Component[] comps = container.getComponents();
      if (comps != null && comps.length > 0)
      {
        for (int i = 0; i < comps.length; i++)
        {
          setToViewOnly(comps[i], changeTxtFieldBg, changeTextAreaBg);
        }
      }
    }
  }

  public static void recoverFromViewOnly(Component comp)
  {
    if (comp != null)
    {
      if (comp instanceof JTextComponent)
      {
        JTextComponent textComp = (JTextComponent) comp;
        textComp.setEditable(true);
        // textComp.setBackground(UIManager.getColor("TextField.inactiveBackground"));
        // textComp.setBackground(UIManager.getColor("TextField.background"));
        // textComp.setForeground(UIManager.getColor("TextField.foreground"));
      }
      else if (comp instanceof JComboBox)
      {
        JComboBox cmbComp = (JComboBox) comp;
        cmbComp.setEnabled(true);
        // cmbComp.setBackground(UIManager.getColor("TextField.inactiveBackground"));
        // cmbComp.setForeground(UIManager.getColor("TextField.foreground"));
      }
      else if (comp instanceof JScrollPane)
      {
      }
      else if (comp instanceof JLabel)
      {
      }
      else if (comp instanceof JScrollBar)
      {
      }
      else
      {
        comp.setEnabled(true);
      }
    }
    if (comp instanceof Container)
    {
      Container container = (Container) comp;
      Component[] comps = container.getComponents();
      if (comps != null && comps.length > 0)
      {
        for (int i = 0; i < comps.length; i++)
        {
          recoverFromViewOnly(comps[i]);
        }
      }
    }
  }

  public static void recursiveDisable(Component comp)
  {
    if (comp != null)
    {
      if (comp instanceof JLabel)
      {
      }
      else
      {
        comp.setEnabled(false);
      }
    }
    if (comp instanceof Container)
    {
      Container container = (Container) comp;
      Component[] comps = container.getComponents();
      if (comps != null && comps.length > 0)
      {
        for (int i = 0; i < comps.length; i++)
        {
          recursiveDisable(comps[i]);
        }
      }
    }
  }

  public static PlainDocument getPositiveDigitalFilterDocument()
  {
    PlainDocument digitalFilterDocument = new PlainDocument()
    {

      @Override
      public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
      {
        String targetStr = super.getText(0, offs) + str + super.getText(offs, super.getLength() - offs);
        if (targetStr.length() > 0 && targetStr.matches("^\\d+((\\.\\d+%?$)|(\\d*%?$))"))
        {
          super.insertString(offs, str, a);
        }
      }

    };
    return digitalFilterDocument;
  }

  public static PlainDocument getDigitalFilterDocument()
  {
    PlainDocument digitalFilterDocument = new PlainDocument()
    {

      @Override
      public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
      {
        String targetStr = super.getText(0, offs) + str + super.getText(offs, super.getLength() - offs);
        if (targetStr.length() > 0 && targetStr.matches("^\\-?\\d+((\\.\\d+%?$)|(\\d*%?$))"))
        {
          super.insertString(offs, str, a);
        }
      }

    };
    return digitalFilterDocument;
  }
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class UIDialog extends JDialog
{

  private static final long serialVersionUID = 7894473200937799942L;

  private int option = JOptionPane.CANCEL_OPTION;
  private JPanel v_pnlMain;

  public UIDialog()
  {
    this((JComponent) null);
  }

  public UIDialog(JComponent owner)
  {
    this(JOptionPane.getFrameForComponent(owner), true);
  }

  public UIDialog(JComponent owner, boolean modal)
  {
    this(JOptionPane.getFrameForComponent(owner), modal);
  }

  public UIDialog(Dialog owner, boolean modal)
  {
    super(owner, modal);
    initDialog();
  }

  public UIDialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)
  {
    super(owner, title, modal, gc);
    initDialog();
  }

  public UIDialog(Dialog owner, String title, boolean modal)
  {
    super(owner, title, modal);
    initDialog();
  }

  public UIDialog(Dialog owner, String title)
  {
    super(owner, title);
    initDialog();
  }

  public UIDialog(Dialog owner)
  {
    super(owner);
    initDialog();
  }

  public UIDialog(Frame owner, boolean modal)
  {
    super(owner, modal);
    initDialog();
  }

  public UIDialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)
  {
    super(owner, title, modal, gc);
    initDialog();
  }

  public UIDialog(Frame owner, String title, boolean modal)
  {
    super(owner, title, modal);
    initDialog();
  }

  public UIDialog(Frame owner, String title)
  {
    super(owner, title);
    initDialog();
  }

  public UIDialog(Frame owner)
  {
    super(owner);
    initDialog();
  }

  public UIDialog(Window owner, ModalityType modalityType)
  {
    super(owner, modalityType);
    initDialog();
  }

  public UIDialog(Window owner, String title, ModalityType modalityType, GraphicsConfiguration gc)
  {
    super(owner, title, modalityType, gc);
    initDialog();
  }

  public UIDialog(Window owner, String title, ModalityType modalityType)
  {
    super(owner, title, modalityType);
    initDialog();
  }

  public UIDialog(Window owner, String title)
  {
    super(owner, title);
    initDialog();
  }

  public UIDialog(Window owner)
  {
    super(owner);
    initDialog();
  }

  private void initDialog()
  {
    setLayout(new BorderLayout());
    JButton btnOK = new UIButton("OK");
    btnOK.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        option = JOptionPane.OK_OPTION;
        onOK();
        closeAndDispose();
      }
    });
    btnOK.setPreferredSize(new Dimension(80, 22));
    JButton btnCancel = new UIButton("Cancel");
    btnCancel.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        option = JOptionPane.CANCEL_OPTION;
        onCancel();
        closeAndDispose();
      }
    });
    btnCancel.setPreferredSize(new Dimension(80, 22));

    JPanel pnl4Buttons = new JPanel(new FlowLayout(FlowLayout.CENTER, 35, 5));
    pnl4Buttons.setPreferredSize(new Dimension(Integer.MAX_VALUE, 32));
    pnl4Buttons.add(btnOK);
    pnl4Buttons.add(btnCancel);
    pnl4Buttons.setBorder(new LineBorder(Color.blue, 1));
    getContentPane().add(pnl4Buttons, BorderLayout.SOUTH);
    getContentPane().add(getV_pnlMain(), BorderLayout.CENTER);
  }

  protected JPanel getV_pnlMain()
  {
    if (v_pnlMain == null)
    {
      v_pnlMain = new JPanel(new BorderLayout());
    }
    return v_pnlMain;
  }

  /**
   * Hook
   */
  protected void onOK()
  {
  }

  /**
   * Hook
   */
  protected void onCancel()
  {
  }

  public void toCenter()
  {
    Point centerPoint = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
    Rectangle bounds = getBounds();
    setBounds(centerPoint.x - bounds.width / 2, centerPoint.y - bounds.height / 2, bounds.width, bounds.height);
  }

  public void setSize(int width, int height, boolean toCenter)
  {
    Dimension d = new Dimension(width, height);
    setSize(d);
    setPreferredSize(d);
    if (toCenter)
    {
      toCenter();
    }
  }

  protected void closeAndDispose()
  {
    setVisible(false);
    dispose();
  }

  public int getOption()
  {
    return option;
  }

}
import java.awt.Color;
import java.awt.Component;
import java.text.NumberFormat;
import java.util.regex.Pattern;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

public class SwingTableUtils
{

  /**
   * Automatically adjust cell width of the given JTable
   *
   * @param table
   */
  public static void adjustColumnPreferredWidths(JTable table)
  {
    // Set the preferredSize of a column to the widest cell of it
    TableColumnModel columnModel = table.getColumnModel();
    for (int col = 0; col < table.getColumnCount(); col++)
    {
      int maxwidth = 0;
      TableCellRenderer rend = table.getCellRenderer(Integer.MAX_VALUE, col);
      for (int row = 0; row < table.getRowCount(); row++)
      {
        // TableCellRenderer rend = table.getCellRenderer(row, col);
        Object value = table.getValueAt(row, col);
        Component comp = rend.getTableCellRendererComponent(table, value, false, false, row, col);
        maxwidth = Math.max(comp.getPreferredSize().width, maxwidth);
      } // for row

      // -- then we should take column header into consideration --
      TableColumn column = columnModel.getColumn(col);
      // 1.Get the TableCellRenderer instance representing the
      // headerRenderer
      TableCellRenderer headerRenderer = column.getHeaderRenderer();
      if (headerRenderer == null)
        headerRenderer = table.getTableHeader().getDefaultRenderer();

      // 2.Get the rendererComponent by the TableCellRenderer
      // instance(a
      // DefaultTableCellHeaderRenderer in fact)
      Object headerValue = column.getHeaderValue();
      Component headerComp = headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col);

      // 3.Compare its width with current MAX
      maxwidth = Math.max(maxwidth, headerComp.getPreferredSize().width);

      // 4.OK this is the result!
      column.setPreferredWidth(maxwidth);
    } // for col
  }

  /**
   * Render alternate color rows for a JTable
   *
   * @param table
   * @param colorsToRenderer
   */
  public static void renderAlternateColorTable(JTable table, Color[] colorsToRenderer)
  {
    int columnCount = table.getColumnCount();
    AlternateRowColorTableCellRenderer renderer = new AlternateRowColorTableCellRenderer(colorsToRenderer);
    for (int colIndex = 0; colIndex < columnCount; colIndex++)
    {
      TableColumn tc = table.getColumnModel().getColumn(colIndex);
      tc.setCellRenderer(renderer);
    }
    table.revalidate();
    table.repaint();
  }

  /**
   * Clean the table, only apply to DefaultTableModel
   *
   * @param tableModel
   */
  public static void removeAllRows(TableModel tableModel)
  {
    if (tableModel instanceof DefaultTableModel)
    {
      DefaultTableModel dtm = (DefaultTableModel) tableModel;
      dtm.setRowCount(0);
    }
  }

  /**
   * Hide a column
   *
   * @param table
   * @param columnIndex
   */
  public static void hiddenColumn(JTable table, int columnIndex)
  {
    int columnCount = table.getColumnCount();
    if (columnIndex < 0 || columnIndex > columnCount)
      throw new IllegalArgumentException("TableUtils.hiddenColumn()参数越界");
    TableColumn tc = table.getColumnModel().getColumn(columnIndex);
    tc.setMaxWidth(0);
    tc.setMinWidth(0);
    tc.setPreferredWidth(0);
  }

  /**
   * @param table
   * @param cols
   * @see {@link #hiddenColumn(JTable, int)}
   */
  public static void hideColumns(JTable table, int[] cols)
  {
    for (int i = 0; i < cols.length; i++)
    {
      hiddenColumn(table, cols[i]);
    }
  }

  /**
   * Recover a hidden column
   *
   * @param table
   * @param columnIndex
   * @see {@link #hiddenColumn(JTable, int)}
   */
  public static void showColumn(JTable table, int columnIndex)
  {
    int currentResizeMode = table.getAutoResizeMode();
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    int columnCount = table.getColumnCount();
    if (columnIndex < 0 || columnIndex > columnCount)
      throw new IllegalArgumentException("TableUtils.hiddenColumn()参数越界");
    TableColumn tc = table.getColumnModel().getColumn(columnIndex);
    tc.setMaxWidth(300);
    tc.setMinWidth(10);
    tc.setPreferredWidth(100);
    table.setAutoResizeMode(currentResizeMode);
  }

  /**
   * @param table
   * @param cols
   * @see {@link #showColumn(JTable, int)}
   */
  public static void showColumns(JTable table, int[] cols)
  {
    for (int i = 0; i < cols.length; i++)
    {
      showColumn(table, cols[i]);
    }
  }

  /**
   * @param table
   * @param columnIndex
   * @param alignment
   */
  public static void setColumnAlignment(JTable table, int columnIndex, int alignment)
  {
    AlignmentRenderer renderer = new AlignmentRenderer(alignment);
    TableColumn tc = table.getColumnModel().getColumn(columnIndex);
    tc.setCellRenderer(renderer);
  }

  public static void setNumberRendererToTableColumn(JTable tbl, int colIndex)
  {
    TableColumn tc = tbl.getColumnModel().getColumn(colIndex);
    setNumberRendererToTableColumn(tc);
  }

  public static void setNumberRendererToTableColumn(TableColumn tc)
  {
    tc.setCellRenderer(new NumberColumnRenderer());
  }

  private static class NumberColumnRenderer extends DefaultTableCellRenderer
  {
    Pattern p = Pattern.compile("^ *-? *\\d*\\.?\\d*$");
    NumberFormat nf = NumberFormat.getInstance();

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column)
    {
      super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      if (value instanceof Number)
      {
        setText(nf.format(value));
        setHorizontalAlignment(SwingConstants.RIGHT);
      }
      else if (value instanceof String)
      {
        String strVal = (String) value;
        if (null != strVal && strVal.trim() != null)
        {
          if (!strVal.trim().equals(".") && p.matcher(strVal).matches())
          {
            setText(nf.format(Double.valueOf(strVal)));
            setHorizontalAlignment(SwingConstants.RIGHT);
          }
        }
      }
      return this;
    }

    ;
  }

  private static class ColorLooper
  {

    private int length;

    private Color[] colors;

    public ColorLooper(Color[] colors)
    {
      // protective copy
      this.colors = new Color[colors.length];
      System.arraycopy(colors, 0, this.colors, 0, colors.length);
      if (colors.length == 0)
        throw new IllegalArgumentException("颜色参数不合法");
      this.length = colors.length;
    }

    public Color getColor4Row(int rowIndex)
    {
      return colors[rowIndex % length];
    }
  }

  private static class AlignmentRenderer extends DefaultTableCellRenderer
  {

    private static final long serialVersionUID = 1400330361272255584L;
    private int alignment;

    private AlignmentRenderer(int alignment)
    {
      this.alignment = alignment;
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column)
    {
      Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      if (comp instanceof JLabel)
      {
        JLabel lbl = (JLabel) comp;
        lbl.setHorizontalAlignment(alignment);
      }
      return comp;
    }
  }

  private static class AlternateRowColorTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer
  {

    private static final long serialVersionUID = -5577943597037540695L;
    private ColorLooper colorLooper;

    public AlternateRowColorTableCellRenderer(Color[] colors)
    {
      this.colorLooper = new ColorLooper(colors);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column)
    {
      Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      comp.setBackground(colorLooper.getColor4Row(row));
      return comp;
    }

  }
}
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.GraphicsEnvironment;

import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JRadioButton;

class SwingFontMetricsUtils
{
  public String[] listFonts()
  {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = ge.getAvailableFontFamilyNames();
  }

  public static Dimension getDimFit2Text(JComponent comp, String text)
  {
    Dimension dim = new Dimension(comp.getPreferredSize());
    int width = dim.width;
    FontMetrics fm = comp.getFontMetrics(comp.getFont());
    int len = fm.stringWidth(text);
    int extra = 10;
    if (comp instanceof JRadioButton || comp instanceof JCheckBox)
    {
      extra = 25;
    }
    else if (comp instanceof JLabel)
    {
      JLabel label = (JLabel) comp;
      if (label.getIcon() != null)
        extra = label.getIcon().getIconWidth();
    }
    dim.setSize(Math.max(width, len + extra), dim.getHeight());
    return dim;
  }

}
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;

import javax.swing.JApplet;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

import org.apache.log4j.Logger;

@SuppressWarnings("rawtypes")
public class AppUtils
{

  private static final Logger log = Logger.getLogger(SwingUtils.class);

  public static final void initLookAndFeel(String lafClassName, Font font) throws Exception
  {
    if (font != null)
    {
      log.info("set font to: " + font);
      Enumeration keys = UIManager.getLookAndFeelDefaults().keys();
      while (keys.hasMoreElements())
      {
        Object key = keys.nextElement();
        if (UIManager.get(key) instanceof Font)
        {
          UIManager.put(key, font);
        }
      }
    }
    try
    {
      log.info("init L&F using: " + lafClassName);
      UIManager.setLookAndFeel(lafClassName);
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
    }
  }

  public static final void initWindowsLookAndFeel() throws Exception
  {
    initLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel", null);
  }

  /**
   * Initialize Look And Feel with system default
   */
  public static final void initSystemLookAndFeel()
  {
    try
    {
      initLookAndFeel(UIManager.getSystemLookAndFeelClassName(), null);
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      throw new RuntimeException(e);
    }
  }

  // For Test
  public static void run(JFrame frame, int width, int height)
  {
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(width, height);
    frame.setVisible(true);
  }

  public static void run(JApplet applet, int width, int height)
  {
    JFrame frame = new JFrame(title(applet));
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }

  public static void run(JPanel panel, int width, int height)
  {
    JFrame frame = new JFrame(title(panel));
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.setSize(width, height);
    frame.setVisible(true);
  }

  public static void run(Class<? extends JDialog> dlgClass, Class[] paramTypes, Object[] params, int width, int height)
  {
    JDialog dlg;
    try
    {
      if (paramTypes == null && params == null)
      {
        dlg = dlgClass.newInstance();
        dlg.setVisible(true);
      }
      else if (paramTypes != null && paramTypes != null)
      {
        if (paramTypes.length == params.length)
        {
          Constructor<? extends JDialog> constructor = dlgClass.getConstructor(paramTypes);
          dlg = constructor.newInstance(params);
        }
        else
        {
          throw new IllegalArgumentException("paramTypes.length == params.length");
        }
      }
      else
      {
        throw new IllegalArgumentException("paramTypes is " + paramTypes + " while params is " + params);
      }
    }
    catch (IllegalArgumentException e)
    {
      throw new RuntimeException(e);
    }
    catch (InstantiationException e)
    {
      throw new RuntimeException(e);
    }
    catch (IllegalAccessException e)
    {
      throw new RuntimeException(e);
    }
    catch (InvocationTargetException e)
    {
      throw new RuntimeException(e);
    }
    catch (SecurityException e)
    {
      throw new RuntimeException(e);
    }
    catch (NoSuchMethodException e)
    {
      throw new RuntimeException(e);
    }
    dlg.setResizable(true);
    dlg.addWindowListener(new WindowAdapter()
    {
      public void windowClosed(WindowEvent e)
      {
        System.exit(0);
      }
    });
    if (width > 0 && height > 0)
    {
      dlg.setPreferredSize(new Dimension(width, height));
      dlg.setSize(new Dimension(width, height));
    }
    dlg.setVisible(true);
  }

  private static String title(Object o)
  {
    String t = o.getClass().toString();
    // Remove the word "class":
    // if(t.indexOf("class")!=-1)
    // t = t.substring(6);
    return t.replaceAll("^class\\b\\s*", "");
    // 单词边界 空白
    // return t;
  }

}