SWING复杂表格例子

Swing里的提供的表格过于简单。要做复杂的表格得花一番功夫。现把以前做过的整理如下:

  1. 表格里有checkbox的表格

Java代码

   1. package test; 
   2. /**
   3.  * Another JTable example, showing how column attributes can be refined
   4.  * even when columns have been created automatically. Here we create some
   5.  * specialised renderers and editors as well as changing widths and colors
   6.  * for some of the columns in the SwingSet demo table.
   7.  *
   8.  * @version 1.19 11/17/05
   9.  * @author Philip Milne
  10.  */ 
  11.  
  12. import javax.swing.*; 
  13. import javax.swing.table.*; 
  14. import javax.swing.border.*; 
  15.  
  16. import java.awt.Dimension; 
  17. import java.awt.event.WindowAdapter; 
  18. import java.awt.event.WindowEvent; 
  19. import java.awt.Color; 
  20.  
  21. public class TableExample4 { 
  22.  
  23.     public TableExample4() { 
  24.         JFrame frame = new JFrame("Table"); 
  25.         frame.addWindowListener(new WindowAdapter() { 
  26.             public void windowClosing(WindowEvent e) {System.exit(0);}}); 
  27.  
  28.         // Take the dummy data from SwingSet. 
  29.         final String[] names = {"First Name", "Last Name", "Favorite Color", 
  30.                                 "Favorite Number", "Vegetarian"}; 
  31.         final Object[][] data = { 
  32.         {"Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE}, 
  33.         {"Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE}, 
  34.         {"Alan", "Chung", "Green", new Integer(838), Boolean.FALSE}, 
  35.         {"Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE}, 
  36.         {"Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE}, 
  37.         {"Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE}, 
  38.         {"James", "Gosling", "Pink", new Integer(21), Boolean.FALSE}, 
  39.         {"David", "Karlton", "Red", new Integer(1), Boolean.FALSE}, 
  40.         {"Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE}, 
  41.         {"Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE}, 
  42.         {"Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE}, 
  43.         {"Dave", "Moore", "Green", new Integer(88), Boolean.FALSE}, 
  44.         {"Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE}, 
  45.         {"Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE}, 
  46.         {"Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE}, 
  47.         {"Chester", "Rose", "Black", new Integer(0), Boolean.FALSE}, 
  48.         {"Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE}, 
  49.         {"Georges", "Saab", "Red", new Integer(4), Boolean.FALSE}, 
  50.         {"Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE}, 
  51.         {"Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE}, 
  52.         {"Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE} 
  53.         }; 
  54.  
  55.         // Create a model of the data. 
  56.         TableModel dataModel = new AbstractTableModel() { 
  57.             // These methods always need to be implemented. 
  58.             public int getColumnCount() { return names.length; } 
  59.             public int getRowCount() { return data.length;} 
  60.             public Object getValueAt(int row, int col) {return data[row][col];} 
  61.  
  62.             // The default implementations of these methods in 
  63.             // AbstractTableModel would work, but we can refine them. 
  64.             public String getColumnName(int column) {return names[column];} 
  65.             public Class getColumnClass(int c) {return getValueAt(0, c).getClass();} 
  66.             public boolean isCellEditable(int row, int col) {return true;} 
  67.             public void setValueAt(Object aValue, int row, int column) { 
  68.                 System.out.println("Setting value to: " + aValue); 
  69.                 data[row][column] = aValue; 
  70.             } 
  71.          }; 
  72.  
  73.         // Create the table 
  74.         JTable tableView = new JTable(dataModel); 
  75.         // Turn off auto-resizing so that we can set column sizes programmatically.  
  76.     // In this mode, all columns will get their preferred widths, as set blow.  
  77.         tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
  78.  
  79.     // Create a combo box to show that you can use one in a table. 
  80.     JComboBox comboBox = new JComboBox(); 
  81.     comboBox.addItem("Red"); 
  82.     comboBox.addItem("Orange"); 
  83.     comboBox.addItem("Yellow"); 
  84.     comboBox.addItem("Green"); 
  85.     comboBox.addItem("Blue"); 
  86.     comboBox.addItem("Indigo"); 
  87.     comboBox.addItem("Violet"); 
  88.  
  89.         TableColumn colorColumn = tableView.getColumn("Favorite Color"); 
  90.         // Use the combo box as the editor in the "Favorite Color" column. 
  91.         colorColumn.setCellEditor(new DefaultCellEditor(comboBox)); 
  92.  
  93.         // Set a pink background and tooltip for the Color column renderer. 
  94.         DefaultTableCellRenderer colorColumnRenderer = new DefaultTableCellRenderer(); 
  95.         colorColumnRenderer.setBackground(Color.pink); 
  96.         colorColumnRenderer.setToolTipText("Click for combo box"); 
  97.         colorColumn.setCellRenderer(colorColumnRenderer); 
  98.  
  99.         // Set a tooltip for the header of the colors column. 
100.     TableCellRenderer headerRenderer = colorColumn.getHeaderRenderer(); 
101.     if (headerRenderer instanceof DefaultTableCellRenderer) 
102.         ((DefaultTableCellRenderer)headerRenderer).setToolTipText("Hi Mom!"); 
103.  
104.     // Set the width of the "Vegetarian" column. 
105.         TableColumn vegetarianColumn = tableView.getColumn("Vegetarian"); 
106.         vegetarianColumn.setPreferredWidth(100); 
107.  
108.     // Show the values in the "Favorite Number" column in different colors. 
109.         TableColumn numbersColumn = tableView.getColumn("Favorite Number"); 
110.         DefaultTableCellRenderer numberColumnRenderer = new DefaultTableCellRenderer() { 
111.         public void setValue(Object value) { 
112.             int cellValue = (value instanceof Number) ? ((Number)value).intValue() : 0; 
113.             setForeground((cellValue > 30) ? Color.black : Color.red); 
114.             setText((value == null) ? "" : value.toString()); 
115.         } 
116.         }; 
117.         numberColumnRenderer.setHorizontalAlignment(JLabel.RIGHT); 
118.         numbersColumn.setCellRenderer(numberColumnRenderer); 
119.         numbersColumn.setPreferredWidth(110); 
120.  
121.         // Finish setting up the table. 
122.         JScrollPane scrollpane = new JScrollPane(tableView); 
123.     scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED)); 
124.         scrollpane.setPreferredSize(new Dimension(430, 200)); 
125.         frame.getContentPane().add(scrollpane); 
126.         frame.pack(); 
127.         frame.setVisible(true); 
128.     } 
129.  
130.     public static void main(String[] args) { 
131.         new TableExample4(); 
132.     } 
133. } 

package test;
/**
* Another JTable example, showing how column attributes can be refined
* even when columns have been created automatically. Here we create some
* specialised renderers and editors as well as changing widths and colors
* for some of the columns in the SwingSet demo table.
*
* @version 1.19 11/17/05
* @author Philip Milne
*/

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;

import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Color;

public class TableExample4 {

    public TableExample4() {
        JFrame frame = new JFrame("Table");
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}});

        // Take the dummy data from SwingSet.
        final String[] names = {"First Name", "Last Name", "Favorite Color",
                                "Favorite Number", "Vegetarian"};
        final Object[][] data = {
    {"Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE},
    {"Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE},
    {"Alan", "Chung", "Green", new Integer(838), Boolean.FALSE},
    {"Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE},
    {"Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE},
    {"Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE},
    {"James", "Gosling", "Pink", new Integer(21), Boolean.FALSE},
    {"David", "Karlton", "Red", new Integer(1), Boolean.FALSE},
    {"Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE},
    {"Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE},
    {"Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE},
    {"Dave", "Moore", "Green", new Integer(88), Boolean.FALSE},
    {"Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE},
    {"Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE},
    {"Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE},
    {"Chester", "Rose", "Black", new Integer(0), Boolean.FALSE},
    {"Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE},
    {"Georges", "Saab", "Red", new Integer(4), Boolean.FALSE},
    {"Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE},
    {"Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE},
    {"Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE}
        };

        // Create a model of the data.
        TableModel dataModel = new AbstractTableModel() {
            // These methods always need to be implemented.
            public int getColumnCount() { return names.length; }
            public int getRowCount() { return data.length;}
            public Object getValueAt(int row, int col) {return data[row][col];}

            // The default implementations of these methods in
            // AbstractTableModel would work, but we can refine them.
            public String getColumnName(int column) {return names[column];}
            public Class getColumnClass(int c) {return getValueAt(0, c).getClass();}
            public boolean isCellEditable(int row, int col) {return true;}
            public void setValueAt(Object aValue, int row, int column) {
                System.out.println("Setting value to: " + aValue);
                data[row][column] = aValue;
            }
         };

        // Create the table
        JTable tableView = new JTable(dataModel);
        // Turn off auto-resizing so that we can set column sizes programmatically.
// In this mode, all columns will get their preferred widths, as set blow.
        tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

// Create a combo box to show that you can use one in a table.
JComboBox comboBox = new JComboBox();
comboBox.addItem("Red");
comboBox.addItem("Orange");
comboBox.addItem("Yellow");
comboBox.addItem("Green");
comboBox.addItem("Blue");
comboBox.addItem("Indigo");
comboBox.addItem("Violet");

        TableColumn colorColumn = tableView.getColumn("Favorite Color");
        // Use the combo box as the editor in the "Favorite Color" column.
        colorColumn.setCellEditor(new DefaultCellEditor(comboBox));

        // Set a pink background and tooltip for the Color column renderer.
        DefaultTableCellRenderer colorColumnRenderer = new DefaultTableCellRenderer();
        colorColumnRenderer.setBackground(Color.pink);
        colorColumnRenderer.setToolTipText("Click for combo box");
        colorColumn.setCellRenderer(colorColumnRenderer);

        // Set a tooltip for the header of the colors column.
TableCellRenderer headerRenderer = colorColumn.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText("Hi Mom!");

// Set the width of the "Vegetarian" column.
        TableColumn vegetarianColumn = tableView.getColumn("Vegetarian");
        vegetarianColumn.setPreferredWidth(100);

// Show the values in the "Favorite Number" column in different colors.
        TableColumn numbersColumn = tableView.getColumn("Favorite Number");
        DefaultTableCellRenderer numberColumnRenderer = new DefaultTableCellRenderer() {
    public void setValue(Object value) {
        int cellValue = (value instanceof Number) ? ((Number)value).intValue() : 0;
        setForeground((cellValue > 30) ? Color.black : Color.red);
        setText((value == null) ? "" : value.toString());
    }
        };
        numberColumnRenderer.setHorizontalAlignment(JLabel.RIGHT);
        numbersColumn.setCellRenderer(numberColumnRenderer);
        numbersColumn.setPreferredWidth(110);

        // Finish setting up the table.
        JScrollPane scrollpane = new JScrollPane(tableView);
scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED));
        scrollpane.setPreferredSize(new Dimension(430, 200));
        frame.getContentPane().add(scrollpane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new TableExample4();
    }
}

2. 固定列的表格
Java代码

   1. package aaa; 
   2.  
   3.  
   4. import java.awt.BorderLayout; 
   5. import java.awt.event.WindowAdapter; 
   6. import java.awt.event.WindowEvent; 
   7.  
   8. import javax.swing.JFrame; 
   9. import javax.swing.JScrollPane; 
  10. import javax.swing.JTable; 
  11. import javax.swing.JViewport; 
  12. import javax.swing.ListSelectionModel; 
  13. import javax.swing.event.ListSelectionEvent; 
  14. import javax.swing.event.ListSelectionListener; 
  15. import javax.swing.table.AbstractTableModel; 
  16.  
  17.  
  18. /**
  19. * @version 1.0 12/05/98
  20. */ 
  21.  
  22. public class FixedColumnExample extends JFrame { 
  23.     Object[][] data; 
  24.     Object[] column; 
  25.     JTable fixedTable, table; 
  26.  
  27.     public FixedColumnExample() { 
  28.         super("Fixed Column Example"); 
  29.         setSize(400, 150); 
  30.      
  31.     data =  new Object[][]{ 
  32.         {"1","11","A","","","","",""}, 
  33.         {"2","22","","B","","","",""}, 
  34.         {"3","33","","","C","","",""}, 
  35.         {"4","44","","","","D","",""}, 
  36.         {"5","55","","","","","E",""}, 
  37.         {"6","66","","","","","","F"}}; 
  38.     column = new Object[]{"fixed 1","o","a","b","c","d","e","f"}; 
  39.          
  40.     AbstractTableModel fixedModel = new AbstractTableModel() { 
  41.             public int getColumnCount() { 
  42.                 return 1; 
  43.             } 
  44.  
  45.             public int getRowCount() { 
  46.                 return data.length; 
  47.             } 
  48.  
  49.             public String getColumnName(int col) { 
  50.                 return (String) column[col]; 
  51.             } 
  52.  
  53.             public Object getValueAt(int row, int col) { 
  54.                 return data[row][col]; 
  55.             } 
  56.         }; 
  57.         AbstractTableModel model = new AbstractTableModel() { 
  58.             public int getColumnCount() { 
  59.                 return column.length - 2; 
  60.             } 
  61.  
  62.             public int getRowCount() { 
  63.                 return data.length; 
  64.             } 
  65.  
  66.             public String getColumnName(int col) { 
  67.                 return (String) column[col + 1]; 
  68.             } 
  69.  
  70.             public Object getValueAt(int row, int col) { 
  71.                 return data[row][col + 1]; 
  72.             } 
  73.  
  74.             public void setValueAt(Object obj, int row, int col) { 
  75.                 data[row][col + 1] = obj; 
  76.             } 
  77.  
  78.         }; 
  79.      
  80.         fixedTable = new JTable(fixedModel); 
  81.         fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
  82.         fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
  83.         fixedTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { 
  84.             public void valueChanged(ListSelectionEvent arg0) { 
  85.                 checkSelection(true); 
  86.  
  87.             } 
  88.         }); 
  89.  
  90.         table = new JTable(model); 
  91.         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
  92.         table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
  93.         table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { 
  94.             public void valueChanged(ListSelectionEvent arg0) { 
  95.                 checkSelection(false); 
  96.             } 
  97.         }); 
  98.  
  99.         
100.         JViewport viewport = new JViewport(); 
101.         viewport.setView(fixedTable); 
102.         viewport.setPreferredSize(fixedTable.getPreferredSize()); 
103.          
104.         JScrollPane scroll = new JScrollPane(table); 
105.         scroll.setRowHeaderView(viewport); 
106.         scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTable.getTableHeader()); 
107.  
108.         getContentPane().add(scroll, BorderLayout.CENTER); 
109.     } 
110.    
111.   private void checkSelection(boolean isFixedTable) { 
112.         int fixedSelectedIndex = fixedTable.getSelectedRow(); 
113.         int selectedIndex = table.getSelectedRow(); 
114.         if (fixedSelectedIndex != selectedIndex) { 
115.             if (isFixedTable) { 
116.                 table.setRowSelectionInterval(fixedSelectedIndex, fixedSelectedIndex); 
117.             } else { 
118.                 fixedTable.setRowSelectionInterval(selectedIndex, selectedIndex); 
119.             } 
120.         } 
121.     
122.   } 
123.    
124.  
125.   public static void main(String[] args) { 
126.         FixedColumnExample frame = new FixedColumnExample(); 
127.         frame.addWindowListener(new WindowAdapter() { 
128.             public void windowClosing(WindowEvent e) { 
129.                 System.exit(0); 
130.             } 
131.         }); 
132.         frame.setVisible(true); 
133.     } 
134. }  

package aaa;


import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;


/**
* @version 1.0 12/05/98
*/

public class FixedColumnExample extends JFrame {
    Object[][] data;
    Object[] column;
    JTable fixedTable, table;

    public FixedColumnExample() {
        super("Fixed Column Example");
        setSize(400, 150);
   
    data =  new Object[][]{
        {"1","11","A","","","","",""},
        {"2","22","","B","","","",""},
        {"3","33","","","C","","",""},
        {"4","44","","","","D","",""},
        {"5","55","","","","","E",""},
        {"6","66","","","","","","F"}};
    column = new Object[]{"fixed 1","o","a","b","c","d","e","f"};
       
    AbstractTableModel fixedModel = new AbstractTableModel() {
            public int getColumnCount() {
                return 1;
            }

            public int getRowCount() {
                return data.length;
            }

            public String getColumnName(int col) {
                return (String) column[col];
            }

            public Object getValueAt(int row, int col) {
                return data[row][col];
            }
        };
        AbstractTableModel model = new AbstractTableModel() {
            public int getColumnCount() {
                return column.length - 2;
            }

            public int getRowCount() {
                return data.length;
            }

            public String getColumnName(int col) {
                return (String) column[col + 1];
            }

            public Object getValueAt(int row, int col) {
                return data[row][col + 1];
            }

            public void setValueAt(Object obj, int row, int col) {
                data[row][col + 1] = obj;
            }

        };
   
        fixedTable = new JTable(fixedModel);
        fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent arg0) {
                checkSelection(true);

            }
        });

        table = new JTable(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent arg0) {
                checkSelection(false);
            }
        });

      
        JViewport viewport = new JViewport();
        viewport.setView(fixedTable);
        viewport.setPreferredSize(fixedTable.getPreferredSize());
       
        JScrollPane scroll = new JScrollPane(table);
        scroll.setRowHeaderView(viewport);
        scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTable.getTableHeader());

        getContentPane().add(scroll, BorderLayout.CENTER);
    }
 
  private void checkSelection(boolean isFixedTable) {
        int fixedSelectedIndex = fixedTable.getSelectedRow();
        int selectedIndex = table.getSelectedRow();
        if (fixedSelectedIndex != selectedIndex) {
            if (isFixedTable) {
                table.setRowSelectionInterval(fixedSelectedIndex, fixedSelectedIndex);
            } else {
                fixedTable.setRowSelectionInterval(selectedIndex, selectedIndex);
            }
        }
  
  }
 

  public static void main(String[] args) {
        FixedColumnExample frame = new FixedColumnExample();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.setVisible(true);
    }
}

3.表格列里有radiobutton的表格
Java代码

   1. /* (swing1.1beta3) */ 
   2. //package jp.gr.java_conf.tame.swing.examples; 
   3. /**
   4.  * @version 1.0 12/03/98
   5.  */ 
   6.  
   7. import java.awt.*; 
   8. import java.awt.event.*; 
   9. import javax.swing.*; 
  10. import javax.swing.table.*; 
  11. import javax.swing.event.*; 
  12.  
  13. class RadioButtonRenderer implements TableCellRenderer { 
  14.     public Component getTableCellRendererComponent(JTable table, Object value, 
  15.             boolean isSelected, boolean hasFocus, int row, int column) { 
  16.         if (value == null) 
  17.             return null; 
  18.         return (Component) value; 
  19.     } 
  20. } 
  21.  
  22. class RadioButtonEditor extends DefaultCellEditor implements ItemListener { 
  23.     private JRadioButton button; 
  24.  
  25.     public RadioButtonEditor(JCheckBox checkBox) { 
  26.         super(checkBox); 
  27.     } 
  28.  
  29.     public Component getTableCellEditorComponent(JTable table, Object value, 
  30.             boolean isSelected, int row, int column) { 
  31.         if (value == null) 
  32.             return null; 
  33.         button = (JRadioButton) value; 
  34.         button.addItemListener(this); 
  35.         return (Component) value; 
  36.     } 
  37.  
  38.     public Object getCellEditorValue() { 
  39.         button.removeItemListener(this); 
  40.         return button; 
  41.     } 
  42.  
  43.     public void itemStateChanged(ItemEvent e) { 
  44.         super.fireEditingStopped(); 
  45.     } 
  46. } 
  47.  
  48. public class JRadioButtonTableExample extends JFrame { 
  49.  
  50.     public JRadioButtonTableExample() { 
  51.         super("JRadioButtonTable Example"); 
  52.         UIDefaults ui = UIManager.getLookAndFeel().getDefaults(); 
  53.         UIManager.put("RadioButton.focus", ui.getColor("control")); 
  54.  
  55.         DefaultTableModel dm = new DefaultTableModel(); 
  56.         dm.setDataVector(new Object[][] { { "Group 1", new JRadioButton("A") }, 
  57.                 { "Group 1", new JRadioButton("B") }, 
  58.                 { "Group 1", new JRadioButton("C") }, 
  59.                 { "Group 2", new JRadioButton("a") }, 
  60.                 { "Group 2", new JRadioButton("b") } }, new Object[] { 
  61.                 "String", "JRadioButton" }); 
  62.  
  63.         JTable table = new JTable(dm) { 
  64.             public void tableChanged(TableModelEvent e) { 
  65.                 super.tableChanged(e); 
  66.                 repaint(); 
  67.             } 
  68.         }; 
  69.         ButtonGroup group1 = new ButtonGroup(); 
  70.         group1.add((JRadioButton) dm.getValueAt(0, 1)); 
  71.         group1.add((JRadioButton) dm.getValueAt(1, 1)); 
  72.         group1.add((JRadioButton) dm.getValueAt(2, 1)); 
  73.         ButtonGroup group2 = new ButtonGroup(); 
  74.         group2.add((JRadioButton) dm.getValueAt(3, 1)); 
  75.         group2.add((JRadioButton) dm.getValueAt(4, 1)); 
  76.         table.getColumn("JRadioButton").setCellRenderer( 
  77.                 new RadioButtonRenderer()); 
  78.         table.getColumn("JRadioButton").setCellEditor( 
  79.                 new RadioButtonEditor(new JCheckBox())); 
  80.         JScrollPane scroll = new JScrollPane(table); 
  81.         getContentPane().add(scroll); 
  82.         setSize(200, 140); 
  83.         setVisible(true); 
  84.     } 
  85.  
  86.     public static void main(String[] args) { 
  87.         JRadioButtonTableExample frame = new JRadioButtonTableExample(); 
  88.         frame.addWindowListener(new WindowAdapter() { 
  89.             public void windowClosing(WindowEvent e) { 
  90.                 System.exit(0); 
  91.             } 
  92.         }); 
  93.     } 
  94. } 

/* (swing1.1beta3) */
//package jp.gr.java_conf.tame.swing.examples;
/**
* @version 1.0 12/03/98
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;

class RadioButtonRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value == null)
return null;
return (Component) value;
}
}

class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
private JRadioButton button;

public RadioButtonEditor(JCheckBox checkBox) {
super(checkBox);
}

public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (value == null)
return null;
button = (JRadioButton) value;
button.addItemListener(this);
return (Component) value;
}

public Object getCellEditorValue() {
button.removeItemListener(this);
return button;
}

public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
}
}

public class JRadioButtonTableExample extends JFrame {

public JRadioButtonTableExample() {
super("JRadioButtonTable Example");
UIDefaults ui = UIManager.getLookAndFeel().getDefaults();
UIManager.put("RadioButton.focus", ui.getColor("control"));

DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][] { { "Group 1", new JRadioButton("A") },
{ "Group 1", new JRadioButton("B") },
{ "Group 1", new JRadioButton("C") },
{ "Group 2", new JRadioButton("a") },
{ "Group 2", new JRadioButton("b") } }, new Object[] {
"String", "JRadioButton" });

JTable table = new JTable(dm) {
public void tableChanged(TableModelEvent e) {
super.tableChanged(e);
repaint();
}
};
ButtonGroup group1 = new ButtonGroup();
group1.add((JRadioButton) dm.getValueAt(0, 1));
group1.add((JRadioButton) dm.getValueAt(1, 1));
group1.add((JRadioButton) dm.getValueAt(2, 1));
ButtonGroup group2 = new ButtonGroup();
group2.add((JRadioButton) dm.getValueAt(3, 1));
group2.add((JRadioButton) dm.getValueAt(4, 1));
table.getColumn("JRadioButton").setCellRenderer(
new RadioButtonRenderer());
table.getColumn("JRadioButton").setCellEditor(
new RadioButtonEditor(new JCheckBox()));
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
setSize(200, 140);
setVisible(true);
}

public static void main(String[] args) {
JRadioButtonTableExample frame = new JRadioButtonTableExample();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}


4.列header表格
Java代码

   1. /* (swing1.1beta3) */ 
   2. //package jp.gr.java_conf.tame.swing.examples; 
   3.  
   4. import java.awt.*; 
   5. import java.awt.event.*; 
   6. import javax.swing.*; 
   7. import javax.swing.table.*; 
   8.  
   9.  
  10. /**
  11.  * @version 1.0 11/09/98
  12.  */ 
  13.   
  14. class RowHeaderRenderer extends JLabel implements ListCellRenderer { 
  15.    
  16.   RowHeaderRenderer(JTable table) { 
  17.     JTableHeader header = table.getTableHeader(); 
  18.     setOpaque(true); 
  19.     setBorder(UIManager.getBorder("TableHeader.cellBorder")); 
  20.     setHorizontalAlignment(CENTER); 
  21.     setForeground(header.getForeground()); 
  22.     setBackground(header.getBackground()); 
  23.     setFont(header.getFont()); 
  24.   } 
  25.    
  26.   public Component getListCellRendererComponent( JList list,  
  27.          Object value, int index, boolean isSelected, boolean cellHasFocus) { 
  28.     setText((value == null) ? "" : value.toString()); 
  29.     return this; 
  30.   } 
  31. } 
  32.  
  33. public class RowHeaderExample extends JFrame { 
  34.  
  35.   public RowHeaderExample() { 
  36.     super( "Row Header Example" ); 
  37.     setSize( 300, 150 ); 
  38.          
  39.     ListModel lm = new AbstractListModel() { 
  40.       String headers[] = {"a", "b", "c", "d", "e", "f", "g", "h", "mmm"}; 
  41.       public int getSize() { return headers.length; } 
  42.       public Object getElementAt(int index) { 
  43.         return headers[index]; 
  44.       } 
  45.     }; 
  46.  
  47.     DefaultTableModel dm = new DefaultTableModel(lm.getSize(),10); 
  48.     JTable table = new JTable( dm ); 
  49.     table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
  50.      
  51.     JList rowHeader = new JList(lm);     
  52.     rowHeader.setFixedCellWidth(50); 
  53.      
  54. //    rowHeader.setFixedCellHeight(table.getRowHeight() 
  55. //                               ); 
  56. //                             + table.getIntercellSpacing().height); 
  57.     rowHeader.setCellRenderer(new RowHeaderRenderer(table)); 
  58.  
  59.     JScrollPane scroll = new JScrollPane( table ); 
  60.     scroll.setRowHeaderView(rowHeader); 
  61.     getContentPane().add(scroll, BorderLayout.CENTER); 
  62.   } 
  63.  
  64.   public static void main(String[] args) { 
  65.     RowHeaderExample frame = new RowHeaderExample(); 
  66.     frame.addWindowListener( new WindowAdapter() { 
  67.       public void windowClosing( WindowEvent e ) { 
  68.     System.exit(0); 
  69.       } 
  70.     }); 
  71.     frame.setVisible(true); 
  72.   } 
  73. } 

你可能感兴趣的:(C++,c,UI,swing,C#)