当前位置: 代码迷 >> 综合 >> java 列表框(JList)自定义外观样式
  详细解决方案

java 列表框(JList)自定义外观样式

热度:36   发布时间:2024-02-27 13:41:00.0

说明

JList不仅仅支持简单控件组成的列表项,也可以支持复杂的组件,需要实现ListCellRenderer接口,并重写getListCellRendererComponent方法。

实例1-通过paint方法绘制复杂控件(适应性广,但复杂)

package com.example.gui.list;import javax.swing.*;
import java.awt.*;public class List3 {private JFrame mainWin = new JFrame("Renderer List");//初始化JListprivate String[] friends = {"111", "222", "333"};private JList friendList = new JList(friends);public void init() {//JList设置自定义RendererfriendList.setCellRenderer(new MyRenderer());mainWin.add(friendList);mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);mainWin.pack();mainWin.setVisible(true);}//继承JPanel,返回的this就是Component的子类private class MyRenderer extends JPanel implements ListCellRenderer {private String name;@Overridepublic Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {name = value.toString();return this;}@Overridepublic Dimension getPreferredSize() {return new Dimension(40, 70);}//绘制自定义控件@Overridepublic void paint(Graphics g) {if (name != null) {g.setColor(Color.BLACK);g.drawString(name, 10, 10);}}}public static void main(String[] args) {new List3().init();}
}

实例2-通过JPanel来组合控件(使用简易,但适用范围较窄)

import javax.swing.*;
import java.awt.*;public class List2 {private JFrame mainWin = new JFrame("Renderer List");//初始化JListprivate String[] friends = {"111", "222", "333"};private JList friendList = new JList(friends);public void init() {//JList设置自定义RendererfriendList.setCellRenderer(new MyRenderer());mainWin.add(friendList);mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);mainWin.pack();mainWin.setVisible(true);}//继承JPanel,返回的this就是Component的子类private class MyRenderer extends JPanel implements ListCellRenderer {private JLabel jlName;private JLabel jlImage;@Overridepublic Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {String name = value.toString();//关键之处,再添加控件之前,清除界面上的控件//否则界面会重复添加控件this.removeAll();//JPanel添加组件,很方便jlName = new JLabel(name);//利用JLabel来显示图片jlImage = new JLabel();ImageIcon image = new ImageIcon("tree.png");image.setImage(image.getImage().getScaledInstance(35, 50, Image.SCALE_DEFAULT));jlImage.setIcon(image);jlImage.setSize(40, 50);Box vBox = Box.createVerticalBox();vBox.add(jlImage);vBox.add(jlName);this.add(vBox);return this;}@Overridepublic Dimension getPreferredSize() {return new Dimension(40, 70);}}public static void main(String[] args) {new List2().init();}
}

 

  相关解决方案