如何在jList中显示多columns?columns的个数在运行时可否进行调整?
解决方案 »
- JAVA打印TXT
- 写了一个注册小程序,用Struts+DAO,在具体实现方法中出了点问题
- 在linux下用java命令运行一个JFrame程序 ,但是却抛出不能与X Windows联接的异常,请问该怎么办?重分酬谢
- 太急了,就差一点
- 大家都用哪些IDE开发?
- Applet怎样实现屏幕拷贝?
- 怎么生成对一个文件的MD5码?
- 不能安装J3D!!急!!
- 拜托!老兄们,有谁知道使用JBUILDR下的CORBA?(毕业设计啊,很惨啊:)!)
- 大家怎样处理application的密码修改问题(密码保存成文件,要加密)
- could not creat java virtual machine!!!!!!!!!!!!!!急(在线等)
- 解决个小问题,先来先得分!
每个JList都有一个相应的ListModel控制其内容,它只能存放以array或vector组织起来的对象集合.ListModel, represents the contents of the list. It's easy to display an array or vector of objects, using a JList constructor that builds a ListModel instance for you: // Create a JList that displays the strings in data[] String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
比如,用以下的方法可以在JList的每一行中同时显示图标和文字说明:// Display an icon and a string for each object in the list.
class MyCellRenderer extends JLabel implements ListCellRenderer {
final static ImageIcon longIcon = new ImageIcon("long.gif");
final static ImageIcon shortIcon = new ImageIcon("short.gif"); // This is the only method defined by ListCellRenderer.
// We just reconfigure the JLabel each time we're called. public Component getListCellRendererComponent(
JList list,
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // the list and the cell have the focus
{
String s = value.toString();
setText(s);
setIcon((s.length() > 10) ? longIcon : shortIcon);
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
return this;
}
} String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
dataList.setCellRenderer(new MyCellRenderer());以次类推,楼主可根据这种思路加以改进,我想是可以得到显示多个column效果的.
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;public class T {
public static void main(String[] args) {
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < 50; i++) {
model.addElement("Item-" + i);
}
JList list = new JList(model);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
JScrollPane sp = new JScrollPane(list);
JFrame frame = new JFrame("List Test");
frame.getContentPane().add(sp, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
所以,尽管可以得到各种显示效果,但其实质都没有变。
每一个column应该在最上面有一个label...
如前所述,JList的内容排列方式只能是一维的。所以,即使可以显示成行列结构(二维表),也只能对其进行一维操作(如:每次只能选择一整行的元素,而不能选择一行中某一列上的元素)。不知我是否说清楚了。
总之,如果需要进行"列"选择、"单元格"选择等涉及二维表格的操作,
则用JList就无法实现,而只能用JTable;否则,如果只需要进行“行”选择,就可以用JList实现。
(用我前面所说的方法:重新定义每行元素的显示效果,让每行元素都“看起来”具有多个column)。