Topic: 请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? |
Print this page |
1.请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? | Copy to clipboard |
Posted by: stevendu Posted on: 2003-07-02 00:54 我试过setDefaultRenderer、getTableCellRendererComponent之类的方法,只能颜色不同,我该怎么办?下面是我的代码: import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; import javax.swing.event.*; import javax.swing.border.Border; import javax.swing.SwingUtilities; import javax.swing.text.*; import java.awt.Toolkit; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; public class SimpleTableDemo extends JFrame { class DataModel extends AbstractTableModel { Object[][] tableData = null; String[] columnNames = null; public DataModel(Object[][] data, String[] colNames) { tableData = data; columnNames = colNames; } public int getColumnCount() { return tableData[0].length; } public int getRowCount() { return tableData.length; } public Object getValueAt( int row, int col ) { return tableData[row][col]; } public void setValueAt( Object val, int row, int col ) { tableData[row][col] = val; fireTableDataChanged(); } public boolean isCellEditable( int row, int col ) { return true; } /* * JTable uses this method to determine the default renderer/ * editor for each cell. If we didn't implement this method, * then the last column would contain text ("true"/"false"), * rather than a check box. */ public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } }//DataModel end public SimpleTableDemo() { final String[] colNames = {"First Name", "Favorite Color","Call Flow","Sport","# of Years","Vegetarian"}; final Object[][] data = { {"Mary", new Color(153, 0, 153),new Bar(2,5,2,5,Color.black),"Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", new Color(51, 51, 153),new Bar(2,20,2,35,Color.red),"Rowing", new Integer(3), new Boolean(true)}, {"Kathy", new Color(51, 102, 51),new Bar(2,35,2,50,Color.green),"Chasing toddlers", new Integer(2), new Boolean(false)}, {"Mark", Color.blue,new Bar(2,50,2,75,Color.blue),"Speed reading", new Integer(20), new Boolean(true)}, {"Philip", Color.pink,new Bar(2,75,2,95,Color.pink),"Pool", new Integer(7), new Boolean(false)} }; final JTable table = new JTable( new DataModel( data, colNames ) ); table.setPreferredScrollableViewportSize(new Dimension(600, 200)); setUpBarRenderer(table); setUpColorRenderer(table); // setUpColorEditor(table); setUpIntegerEditor(table); TableColumn column = null; column = table.getColumnModel().getColumn(0); column.setPreferredWidth(50); column = table.getColumnModel().getColumn(1); column.setPreferredWidth(50); column = table.getColumnModel().getColumn(2); column.setPreferredWidth(100); column = table.getColumnModel().getColumn(3); column.setPreferredWidth(80); column = table.getColumnModel().getColumn(4); column.setPreferredWidth(50); column = table.getColumnModel().getColumn(5); column.setPreferredWidth(50); /* TableColumn sportColumn = table.getColumnModel().getColumn(0); JComboBox combo = new JComboBox(); combo.addItem("Yes"); combo.addItem("No"); sportColumn.setCellEditor( new DefaultCellEditor( combo ) ); sportColumn = table.getColumnModel().getColumn(1); JLabel label = new JLabel("Label1"); sportColumn.setCellEditor( new DefaultCellEditor( label ) ); sportColumn = table.getColumnModel().getColumn(2); JCheckBox check = new JCheckBox(); sportColumn.setCellEditor( new DefaultCellEditor( check ) ); sportColumn = table.getColumnModel().getColumn(3); JButton button = new JButton("Button1"); sportColumn.setCellEditor( new DefaultCellEditor( button ) ); */ //Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); //Add the scroll pane to this window. getContentPane().add(scrollPane, BorderLayout.CENTER); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } class Bar extends JLabel { int top, left, bottom, right; Color color; public Bar( int top, int left, int bottom, int right, Color color ) { this.top = top; this.left = left; this.bottom = bottom; this.right = right; this.color = color; } } class BarRenderer extends JLabel implements TableCellRenderer { Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; public BarRenderer(boolean isBordered) { super(); this.isBordered = isBordered; setOpaque(true); } public Component getTableCellRendererComponent( JTable table, Object bar, boolean isSelected, boolean hasFocus,int row, int column) { Bar b = (Bar)bar; setBackground(b.color); if (isBordered) { if (isSelected) { if (selectedBorder == null) { selectedBorder = BorderFactory.createMatteBorder(b.top,b.left,b.bottom,b.right,table.getSelectionBackground()); } setBorder(selectedBorder); } else { if (unselectedBorder == null) { unselectedBorder = BorderFactory.createMatteBorder(b.top,b.left,b.bottom,b.right,table.getBackground()); } setBorder(unselectedBorder); } } return this; } } private void setUpBarRenderer( JTable table ) { table.setDefaultRenderer(Bar.class, new BarRenderer(true)); } class ColorRenderer extends JLabel implements TableCellRenderer { Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; public ColorRenderer(boolean isBordered) { super(); this.isBordered = isBordered; setOpaque(true); //MUST do this for background to show up. } public Component getTableCellRendererComponent( JTable table, Object color, boolean isSelected, boolean hasFocus,int row, int column) { setBackground((Color)color); if (isBordered) { if (isSelected) { if (selectedBorder == null) { selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,table.getSelectionBackground()); } setBorder(selectedBorder); } else { if (unselectedBorder == null) { unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,table.getBackground()); } setBorder(unselectedBorder); } } return this; } } private void setUpColorRenderer(JTable table) { table.setDefaultRenderer(Color.class,new ColorRenderer(true)); } //Set up the editor for the Color cells. private void setUpColorEditor(JTable table) { //First, set up the button that brings up the dialog. final JButton button = new JButton("") { public void setText(String s) { //Button never shows text -- only color. } }; button.setBackground(Color.white); button.setBorderPainted(false); button.setMargin(new Insets(0,0,0,0)); //Now create an editor to encapsulate the button, and //set it up as the editor for all Color cells. final ColorEditor colorEditor = new ColorEditor(button); table.setDefaultEditor(Color.class, colorEditor); //Set up the dialog that the button brings up. final JColorChooser colorChooser = new JColorChooser(); ActionListener okListener = new ActionListener() { public void actionPerformed(ActionEvent e) { colorEditor.currentColor = colorChooser.getColor(); } }; final JDialog dialog = JColorChooser.createDialog(button,"Pick a Color",true,colorChooser,okListener,null); //XXXDoublecheck this is OK //Here's the code that brings up the dialog. button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button.setBackground(colorEditor.currentColor); colorChooser.setColor(colorEditor.currentColor); //Without the following line, the dialog comes up //in the middle of the screen. //dialog.setLocationRelativeTo(button); dialog.show(); } }); } /* * The editor button that brings up the dialog. * We extend DefaultCellEditor for convenience, * even though it mean we have to create a dummy * check box. Another approach would be to copy * the implementation of TableCellEditor methods * from the source code for DefaultCellEditor. */ class ColorEditor extends DefaultCellEditor { Color currentColor = null; public ColorEditor(JButton b) { super(new JCheckBox()); //Unfortunately, the constructor //expects a check box, combo box, //or text field. editorComponent = b; setClickCountToStart(1); //This is usually 1 or 2. //Must do this so that editing stops when appropriate. b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fireEditingStopped(); } }); } protected void fireEditingStopped() { super.fireEditingStopped(); } public Object getCellEditorValue() { return currentColor; } public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelected,int row,int column) { ((JButton)editorComponent).setText(value.toString()); currentColor = (Color)value; return editorComponent; } } private void setUpIntegerEditor(JTable table) { //Set up the editor for the integer cells. final WholeNumberField integerField = new WholeNumberField(0, 5); integerField.setHorizontalAlignment(WholeNumberField.RIGHT); DefaultCellEditor integerEditor = new DefaultCellEditor(integerField) { //Override DefaultCellEditor's getCellEditorValue method //to return an Integer, not a String: public Object getCellEditorValue() { return new Integer(integerField.getValue()); } }; table.setDefaultEditor(Integer.class, integerEditor); } class WholeNumberField extends JTextField { private Toolkit toolkit; private NumberFormat integerFormatter; public WholeNumberField(int value, int columns) { super(columns); toolkit = Toolkit.getDefaultToolkit(); integerFormatter = NumberFormat.getNumberInstance(Locale.US); integerFormatter.setParseIntegerOnly(true); setValue(value); } public int getValue() { int retVal = 0; try { retVal = integerFormatter.parse(getText()).intValue(); } catch (ParseException e) { // This should never happen because insertString allows // only properly formatted data to get in the field. toolkit.beep(); } return retVal; } public void setValue(int value) { setText(integerFormatter.format(value)); } protected Document createDefaultModel() { return new WholeNumberDocument(); } protected class WholeNumberDocument extends PlainDocument { public void insertString(int offs, String str,AttributeSet a) throws BadLocationException { char[] source = str.toCharArray(); char[] result = new char[source.length]; int j = 0; for (int i = 0; i < result.length; i++) { if (Character.isDigit(source[i])) result[j++] = source[i]; else { toolkit.beep(); System.err.println("insertString: " + source[i]); } } super.insertString(offs, new String(result, 0, j), a); } } } public static void main(String[] args) { SimpleTableDemo frame = new SimpleTableDemo(); frame.pack(); frame.setVisible(true); } } |
2.Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re: stevendu] | Copy to clipboard |
Posted by: guru Posted on: 2003-07-02 06:23 See following codes. the define of Bar and BarRenderer had been changed.
|
3.Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re: guru] | Copy to clipboard |
Posted by: stevendu Posted on: 2003-07-02 10:18 Quru: Thank you a lot! |
4.Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re: stevendu] | Copy to clipboard |
Posted by: stevendu Posted on: 2003-07-02 16:01 我想问一下,为什么列名没有显示呢? |
5.Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re: stevendu] | Copy to clipboard |
Posted by: guru Posted on: 2003-07-02 21:24 override you getColumnName in DataModel class
|
6.Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re: stevendu] | Copy to clipboard |
Posted by: stevendu Posted on: 2003-07-03 15:23 谢谢,我重载了getColumnName之后,出现了奇怪的情况,在编辑期能显示列名,可是执行期却不显示,就连列名那一行都没有了,这是怎么回事呢? |
7.Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re: stevendu] | Copy to clipboard |
Posted by: stevendu Posted on: 2003-07-04 11:09 ScrollPane.getViewport().add(table, null); ScrollPane.add( table ); 用这两种方式添加table时,编辑期都可以显示Table和列名 但是运行期用第一种可显示Table,没有列名 第二种连Table都不显示了! 奇怪? |
8.Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re: stevendu] | Copy to clipboard |
Posted by: stevendu Posted on: 2003-07-04 14:57 我找到问题所在了,JB产生了一条语句把TableHeader关了。 |
9.Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re: stevendu] | Copy to clipboard |
Posted by: guru Posted on: 2003-07-04 23:02 Sorry for not reply, I am a little busy to visit my customer. I use IntelliJ, so there is no problem from Jbuilder. |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |