Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Java SE 综合讨论区  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? [Re:stevendu]
guru





发贴: 131
积分: 53
于 2003-07-02 06:23 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
See following codes. the define of Bar and BarRenderer had been changed.



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,20,Color.black),"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", new Color(51, 51, 153),new Bar(20,35,Color.red),"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", new Color(51, 102, 51),new Bar(30,50,Color.green),"Chasing toddlers", new Integer(2), new Boolean(false)},
{"Mark", Color.blue,new Bar(55,75,Color.blue),"Speed reading", new Integer(20), new Boolean(true)},
{"Philip", Color.pink,new Bar(75,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 Bar {
int start, stop;
Color color;
public Bar( int start, int stop, Color color ) {
this.start = start;
this.stop = stop;
this.color = color;
}
}

class BarRenderer extends JPanel implements TableCellRenderer {
Border unselectedBorder = null;
Border selectedBorder = null;
boolean isBordered = true;
int x1=0, y1=0, w1=0, h1=0;
int x2=0, y2=0, w2=0, h2=0;
Color c, bc;
public BarRenderer(boolean isBordered) {
super();
this.isBordered = isBordered;
setOpaque(true);
}
public void paint(Graphics g){
g.setColor(bc);
g.fillRect(x2,y2,w2,h2);
g.setColor ( c );
g.fillRect(x1,y1,w1,h1);
}
public Component getTableCellRendererComponent( JTable table, Object bar, boolean isSelected, boolean hasFocus,int row, int column) {
Bar b = (Bar)bar;

x1 = b.start * table.getCellRect(row,column,false).width / 100;
y1 = 2;
w1 = b.stop * table.getCellRect(row,column,false).width / 100 - x1;
h1 =table.getCellRect(row,column,false).height - 4;;

x2 = 0;
y2 = 0;
w2 = table.getCellRect(row,column,false).width;
h2 =table.getCellRect(row,column,false).height;;

c = b.color;

if (isSelected) {
this.setBackground(table.getSelectionBackground());
bc = table.getSelectionBackground();
} else {
bc = table.getBackground();
this.setBackground(table.getBackground());
}
/*
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);
}
}




guru edited on 2003-07-02 06:31


话题树型展开
人气 标题 作者 字数 发贴时间
7099 请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? stevendu 13616 2003-07-02 00:54
5583 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? guru 13161 2003-07-02 06:23
5397 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? stevendu 22 2003-07-02 10:18
5406 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? stevendu 17 2003-07-02 16:01
5422 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? guru 167 2003-07-02 21:24
5478 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? stevendu 72 2003-07-03 15:23
5442 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? stevendu 147 2003-07-04 11:09
5342 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? stevendu 33 2003-07-04 14:57
5495 Re:请教:如何实现在表格中显示不同位置、不同长度、不同颜色的Label? guru 115 2003-07-04 23:02

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   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