三天了,,三天没睡了,就因为这个程序,请各位帮帮忙看看!!!!!!
//本程序是本人用JB按书上做的,所以在JB是可以运行的,现在不一定可以编译过不过大家看重点就好了,我在这里先谢谢各位了!
//本例通过实现javax.swing.ListCellRenderer接口来创建自定义的列表单元渲染类OwnCellRenderer,并且为了使列表单元同时显示图标和文//本,OwnCellRenderer同时继承JLable类,图标显示在左,文本显示在右(当然,按我们对JLable的了解,图标和文本的位置是可以随意换的//)
//问题1,怎样才能让文本在左,图标在右?也就是说,怎样随意调整图标和文本的位置?
//问题2,在OwnCellRenderer类唯一实现的一个方法getListCellRendererConmponent()里的if(value!=null){
//String text=value.toString();是什么意思?toString()不是应该是一个异常输出吗?怎么此时变成文本设置了?
//this.setIcon(icons[index]);//在标签中设置图标 其中的索引是从何而来的?
//问题3此自定义类既然已继承了JLabel类为什么JLabel中的setHorizontalAligment()方法不能用
//顺便问一个问题,列表框中怎么样才能初始选中多个选项?
//最后一个问题,程序编写完成后怎么样在没有jb的机器上运行,也就是说怎么样打包,怎么生成可执行文件?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*
public class jlabledome {
public static void main(String args[] ){
jbInit();
}
private void jbInit() throws Exception{
Icon[] icons={icon1,icon2,icon3,icon4,icon5,icon6};
list=new JList(iconnames);//创建以iconnames数组元素为列表单元文本中的列表组件
list.setCellRenderer(new OwnCellRenderer(icons));//设置list的单元渲染对象为自定义的OwnCellRenderer对象
this.getContenPane().add(new JScrollPane(list));//将list对象复制到JScrollPane
}
class OwnCellRenderer extends JLabel impelments ListCellRenderer{
Icon[] icons;//列表中显示的图标数组
public OwnCellRenderer(Icon[] icons)
{
this.icons=icons;
this.setOpaque(true);
this.setFont(new Font("Dialog",Font.PLAIN,14));
}
public Component getListCellRendererConmponent(JList list,Object value, int index, boolean isSelected, boolean cellHasFocue){
if(value!=null){
String text=value.toString();
this.setText(text) ;//设置显示文本
}
this.setIcon(icons[index]);//在标签中设置图标
if (isSelected){//如果列表单元被选中,设置背景颜色、前景色分别为列表单元被选中的默认背景颜色、前景色
this.setBackground(list.getSelectionBackground());
this.setForeground(list.getSelectionForeground());
}
else{
//如果列表单元没被选中,设置背景颜色、前景色分别为列表单元没被选中的默认颜色
this.setBackground(list.getBackground());
this.setForeground(list.getForeground());
}
return this;//返回本对象为列表单元的渲对象
}
class JListDemo extends JFrame{
String[] iconnames={"电脑","软件","软盘","画图","公文包","网上邻居"};//列表单元显示的文本
JList list;//列表单元显示的图标
Icon icon1=new ImageIcon(ClassLoader.getSystemResouurce("images/1.ico"));
Icon icon2=new ImageIcon(ClassLoader.getSystemResouurce("images/2.ico"));
Icon icon3=new ImageIcon(ClassLoader.getSystemResouurce("images/3.ico"));
Icon icon4=new ImageIcon(ClassLoader.getSystemResouurce("images/4.ico"));
Icon icon5=new ImageIcon(ClassLoader.getSystemResouurce("images/5.ico"));
Icon icon6=new ImageIcon(ClassLoader.getSystemResouurce("images/6.ico"));
}
}