使用Swing的JList组件实现可滑动的图片列表

版权声明:转载麻烦告知。 https://blog.csdn.net/qq_40064948/article/details/81273790

先放效果图吧,代码是从程序里抽出来的,没有特意的做效果,挺丑的凑合着看吧

一、实现JList每一项以图片的形式展示并附带滚轮思路:

1.需要【JScrollPane】对象,将JList放置在JScrollPane上,而不是普通的JPane中。

    JScrollPane scrollPane = new JScrollPane(list);
    panel_1.add(scrollPane, BorderLayout.CENTER);

2.需要【JList】对象,JList对象中设置模型

    JList<File> list = new JList<File>();

3.需要【DefaultListCellRenderer】接口

(1)JList并不会显示图片,那么我们就重写JList的渲染器ListCellRenderer。可是ListCellRenderer是一个接口,在这里我们选择自定义一个DefaultListCellRenderer类,从API中,我们看到DefaultListCellRenderer继承了JLabel,这意味着我们可以使用这个类的对象,在绘制的时候直接设置JLabel标签的图标。而不用再去创建很多JLabel对象。

    public class ImageCellRender extends DefaultListCellRenderer {
        private static final long serialVersionUID = 1L;
    }

(2)真正控制如何绘制JList的是getListCellRendererComponent(参数列表)方法,所以我们在自定义类ImageCellRender 中需要重写getListCellRendererComponent(参数列表)方法,在重写里面的具体代码之前,我们先分析一下这个方法的参数列表:

    JList<? extends Object> list:正在绘制的JList 
    Object value:由list.getModel().getElementAt(index)返回的值 
    int index:单元格索引 
    boolean isSelected:如果选择了指定的单元格,则为true 
    cellHsaFocus:如果指定的单元格拥有焦点,则为true
  public class ImageCellRender extends DefaultListCellRenderer {
        private static final long serialVersionUID = 1L;
        public Component getListCellRendererComponent(JList<? extends Object> list,
		    	Object value, int index, boolean isSelected, boolean cellHasFocus){
        }
    }   

(3)分析:在这个方法中我们需要做什么?

    要setIcon(图标);我们需要一个ImageIcon对象
    setIcon(ImageIcon imageIcon);

    要ImageIcon对象,我们需要图片路径
    ImageIcon icon = new ImageIcon(String imagePath);

    要图片的路径,我们可以通过getListCellRendererComponent()方法传入图片文件
    String imagePath = xxxx.....

(4)从上面的分析中,我们知道我们需要一个【File】类型的对象,这个对象的路径是文件夹中的某一个图片。所以在这个方法中我们需要传入的Value值为File类型的对象。而这个File对象全部存放于JList中,所以我们可以给JList定义一个泛型JList<File>。 解释前面第2.点,为什么是JList需要加泛型<File>

4.需要【ListMode】对象

(1)重写好渲染器ImageCellRender之后,我们将开始往JList中存放元素。如果使用list.add()方法去添加元素,不利于我们对JList进行操作,JList为我们提供了一个list.setModel(ListModel listModel)方法。下面我们来看一下ListModel这个类。

(2)打开API我们会发现ListModel是一个接口,从名字来看实现子类中和ListModel相关的类有:AbstractListModel和DefaultListModel。点开DefaultListModel类后发现,DefaultListModel继承了AbstractListModel,而且具有很多对元素操作的方法。所以我们新建一个类,继承DefaultListModel,并对一些方法进行重写

    public class ImageListModel extends DefaultListModel<File> {
        private static final long serialVersionUID = 1L;
        private List<File> imageFile = new ArrayList<File>();
    	public void addElement(File file){
    		this.imageFile.add(file);
    	}
    	public int getSize(){
	    	return imageFile.size();
	    }
	    public File getElementAt(int index){
    		return imageFile.get(index);
    	}
    }

(3)创建一个imageFile集合对象,由于model中存放的都是File类型的对象,所以将List集合定义泛型为<File>,addElement(File file),每addElement元素就存进List集合中。getSize()返回List.size(),getElementAt(int index),返回集合中对应下标的元素。

5.需要【File】对象​​

(1)所有准备工作都做好了,那么我们现在需要创建File对象了。创建一个文件夹new File("文件路径"),从这个文件夹下获得文件夹中的全部文件,存进File[]数组中。使用foreach循环遍历files数组添加进listModel模型中。

    File[] files = new File("img\\head").listFiles();
    for(File file : files){
        listModel.addElement(file);
    }

(2)注意:我的“img\\head”中 放的全是png文件,如果路径下还有别的格式的文件(.txt .exe等)需要筛选!不然会报错!

    String fileName =f.getName();
    String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
    if(prefix.equals("xxx")){
        ....自行做处理
    }

二、代码

(1)Test extends JFrame

public class Test extends JFrame {

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Test frame = new Test();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Test() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 145, 297);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(245, 245, 245));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JScrollPane scrollPane = new JScrollPane();
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 124, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(300, Short.MAX_VALUE))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE))
		);
		
        //重这里开始看!!这里才是主体代码 前面都是系统自己生成的
        //重这里开始看!!这里才是主体代码 前面都是系统自己生成的
        //重这里开始看!!这里才是主体代码 前面都是系统自己生成的
		JList<File> list = new JList<File>();
		scrollPane.setViewportView(list);
		
		ImageListModel listModel = new ImageListModel();
		
		File[] files = new File("img\\head").listFiles();
		for(File file : files){
			listModel.addElement(file);
		}
		list.setModel(listModel);
		list.setCellRenderer(new ImageCellRender());
		
		contentPane.setLayout(gl_contentPane);
	}
}

(2)ImageCellRender extends DefaultListCellRenderer 

public class ImageCellRender extends DefaultListCellRenderer {
	private static final long serialVersionUID = 1L;
	public Component getListCellRendererComponent(JList<? extends Object> list,
			Object value, int index, boolean isSelected, boolean cellHasFocus){
		if(value instanceof File){
			File imageFile = (File) value;
			try{
				ImageIcon icon = new ImageIcon(imageFile.toURI().toURL());
                //这里将图片做了自适应处理
				icon.setImage(icon.getImage().getScaledInstance(50, 50, Image.SCALE_DEFAULT));
				setIcon(icon);
				setBackground(list.getSelectionBackground());   
				setForeground(list.getSelectionForeground()); 
				setBackground(list.getBackground());   
				setForeground(list.getForeground()); 
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return this;
	}

}

(3)ImageListModel extends DefaultListModel

public class ImageListModel extends DefaultListModel<File> {
	private static final long serialVersionUID = 1L;
	private List<File> imageFile = new ArrayList<File>();
	public void addElement(File file){
		this.imageFile.add(file);
	}
	public int getSize(){
		return imageFile.size();
	}
	public File getElementAt(int index){
		return imageFile.get(index);
	}
}

Over啦~ 初学Swing整理了下思路 希望跟我一样的初学者能看懂

来自一个喜欢编程的小姐姐 >.<

客官~有缘再见
 

猜你喜欢

转载自blog.csdn.net/qq_40064948/article/details/81273790