Vector columnNames=new Vector()
columnNames.add("name")
columnNames.add("sex")
DefaultTableModel dataModel=new DefaultTableModel(data,columnNames)
JTable table = new JTable(dataModel)
JScrollPane scrollpane = new JScrollPane(table)
/********************************我也是新开始学的,例子比较简陋。大概思想就是:单元格里面渲染JScrollPane,其上有个JTextArea,可以实现换行。
具体例子如下:
****************************/
import java.awt.Component
import java.util.ArrayList
import java.util.EventObject
import javax.swing.JFrame
import javax.swing.JScrollPane
import javax.swing.JTable
import javax.swing.JTextArea
import javax.swing.event.CellEditorListener
import javax.swing.table.DefaultTableModel
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
public class ListToJTable {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<String>()
list.add("1\r\n23\n4\n5")
list.add("abc")
JFrame f=new JFrame("ListToJTable Test")
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
f.setSize(400, 300)
JTable t=new JTable(0,1)
DefaultTableModel dataModel=(DefaultTableModel) t.getModel()
int count=dataModel.getRowCount()
while(count>0){
dataModel.removeRow(0)
count--
}
for (int i = 0 i < list.size() i++) {
Object[] ob=new Object[]{list.get(i)}
dataModel.addRow(ob)
}
t.setModel(dataModel)
f.add(t)
f.setVisible(true)
t.setDefaultRenderer(Object.class, new TableCellRenderer(){
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JScrollPane sc=new JScrollPane()
JTextArea area=new JTextArea(value.toString())
sc.setViewportView(area)
return sc
}
})
t.setDefaultEditor(Object.class, new TableCellEditor(){
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
JScrollPane sc=new JScrollPane()
JTextArea area=new JTextArea(value.toString())
sc.setViewportView(area)
return sc
}
@Override
public void addCellEditorListener(CellEditorListener l) {
}
@Override
public void cancelCellEditing() {
}
@Override
public Object getCellEditorValue() {
return null
}
@Override
public boolean isCellEditable(EventObject anEvent) {
return true
}
@Override
public void removeCellEditorListener(CellEditorListener l) {
}
@Override
public boolean shouldSelectCell(EventObject anEvent) {
return false
}
@Override
public boolean stopCellEditing() {
return false
}
})
t.setRowHeight(40)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)