站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题Java JList中能放对象吗(比如:按钮);我刚学

Java JList中能放对象吗(比如:按钮);我刚学

摘要: Java JList中能放对象吗(比如:按钮);我刚学


Java JList中能放对象吗(比如:按钮);


晕,没人知道吗?


可以加进去的..


对象肯定是可以加的。ListModel的这个addElement就是加对象的。
但是至于你说加button,能不能出现JList里面的按钮效果是另外一回事,因为加了对象时候,默认是显示string的,就是把对象toString之后显示在list里面。


下面代码可以实现你的要求了,但是要让按钮能点击还要写些代码。

/*
* ButtonCellRenderer.java
*
* Created on 2006年10月12日, 下午12:34
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
import java.awt.*;
import javax.swing.*;

/**
*
* @author Administrator
*/
public class ButtonCellRenderer extends JButton implements ListCellRenderer
{
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);
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;
}
}
------------------------------------------------------------------------------------
/*
* TestFrame.java
*
* Created on 2006年10月12日, 下午12:38
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
import java.awt.*;
import javax.swing.*;
/**
*
* @author Administrator
*/
public class TestFrame extends JFrame
{
private String[] data = {"one", "two", "three", "four"};
private JList dataList;
private JScrollPane jsp;

/** Creates a new instance of TestFrame */
public TestFrame()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dataList = new JList(data);
dataList.setCellRenderer(new ButtonCellRenderer());

jsp = new JScrollPane(dataList);
Container c = this.getContentPane();
c.add(jsp, BorderLayout.CENTER);

this.setVisible(true);
}

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



↑返回目录
前一篇: JAVA 5.0的API文档中的尖括号(<>)什么意思
后一篇: String a = "hello"