溫馨提示×

Java Swing中CheckedListBox的最佳實(shí)踐

小樊
83
2024-09-03 13:49:08
欄目: 編程語言

在Java Swing中,沒有名為CheckedListBox的組件,但是可以使用JList和JCheckBox結(jié)合使用來創(chuàng)建一個(gè)帶有復(fù)選框的列表

  1. 首先,創(chuàng)建一個(gè)自定義的ListModel,用于存儲(chǔ)帶有復(fù)選框的列表項(xiàng):
import javax.swing.*;

public class CheckedListModel extends DefaultListModel {
    public void addElement(Object obj) {
        super.addElement(new CheckedListItem(obj));
    }
}
  1. 接下來,創(chuàng)建一個(gè)CheckedListItem類,用于存儲(chǔ)列表項(xiàng)及其狀態(tài)(選中或未選中):
public class CheckedListItem {
    private Object item;
    private boolean isChecked;

    public CheckedListItem(Object item) {
        this.item = item;
        this.isChecked = false;
    }

    public Object getItem() {
        return item;
    }

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean isChecked) {
        this.isChecked = isChecked;
    }
}
  1. 創(chuàng)建一個(gè)自定義的ListCellRenderer,用于在JList中顯示帶有復(fù)選框的列表項(xiàng):
import javax.swing.*;
import java.awt.*;

public class CheckedListCellRenderer extends JCheckBox implements ListCellRenderer {
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        CheckedListItem item = (CheckedListItem) value;
        setComponentOrientation(list.getComponentOrientation());
        setFont(list.getFont());
        setBackground(list.getBackground());
        setForeground(list.getForeground());
        setSelected(item.isChecked());
        setEnabled(list.isEnabled());
        setText(item.getItem().toString());
        setFocusPainted(false);
        return this;
    }
}
  1. 在主窗口中添加JList并設(shè)置自定義的ListModel和ListCellRenderer:
import javax.swing.*;

public class CheckedListBoxDemo {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Checked List Box Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);

        CheckedListModel model = new CheckedListModel();
        model.addElement("Item 1");
        model.addElement("Item 2");
        model.addElement("Item 3");

        JList checkedListBox = new JList(model);
        checkedListBox.setCellRenderer(new CheckedListCellRenderer());
        checkedListBox.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                int index = checkedListBox.locationToIndex(e.getPoint());
                if (index != -1) {
                    CheckedListItem item = (CheckedListItem) model.getElementAt(index);
                    item.setChecked(!item.isChecked());
                    checkedListBox.repaint();
                }
            }
        });

        frame.getContentPane().add(new JScrollPane(checkedListBox));
        frame.setVisible(true);
    }
}

這樣,你就創(chuàng)建了一個(gè)帶有復(fù)選框的列表。當(dāng)用戶點(diǎn)擊列表項(xiàng)時(shí),相應(yīng)的復(fù)選框?qū)⒈贿x中或取消選中。你可以根據(jù)需要修改這些代碼以適應(yīng)你的應(yīng)用程序。

0