如何将ItemListener添加到我自己的组件中?

时间:2014-10-27 23:44:43

标签: java checkbox components itemlistener

燮!
我正在编写自己的CheckBoxGroup,并且不了解如何添加ItemListener。

private ItemListener itemListener;    
public void addItemListener(ItemListener itemListener){
   this.itemListener = itemListener;
}

这就是我所拥有的一切 实际上,我无法理解如何使用Item类来链接itemListener 我真的无法添加更多文本,但stackoverflow要求我这样做 所以,有一些" blah-blah-blah"。

这里的完整代码

package a3ro;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Aero on 14.10.2014.
 */
public class ACheckBoxGroup extends JComponent{
    private List<Item> item;
    private Color foreground;
    private Color background;
    private Color trueColor;
    private Color falseColor;
    private Font font;
    private int width;
    private int height;
    private int fontMaxSize;
    private FontMetrics fm;
    private int fontH;

    private int[] heights;

    private static final int hC = 3;

    private boolean form = true;
    private static final boolean CIRCLE = true;
    private static final boolean SQUARE = false;

    private static final int MIN_FONT_SIZE = 8;
    private static final int MAX_FONT_SIZE = 32;

    private ItemListener itemListener;

    public void addItemListener(ItemListener itemListener){
        this.itemListener = itemListener;
    }

    public void removeItemListener(){
        this.itemListener = null;
    }

    public ACheckBoxGroup(){
        item = new LinkedList<Item>();
        //background & foreground is initialize in paintComponent method
        trueColor = Color.green;
        //falseColor is null default
        this.setPreferredSize(new Dimension(150, 50));
        fontMaxSize = 16;
        setFont(new Font("Dialog", Font.PLAIN, fontMaxSize));
        updateSize();
        fm = getFontMetrics(getFont());
        fontH = fm.getHeight();


        enableEvents(AWTEvent.ACTION_EVENT_MASK);
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int y = e.getY();
                if (y <= item.size() * fontH * hC) {
                        item.get(y / (fontH * hC)).changeValue();
                }
                repaint();
            }
        });

    }

    public boolean[] getValues(){
        boolean[] retArr = new boolean[item.size()];
        for (int i = 0; i < item.size(); i++){
            retArr[i] = item.get(i).getValue();
        }
        return retArr;
    }

    public void add(String name){
        if(!name.equals("")) {
            for (Item i : item) {
                if (i.getName().equals(name)) {
                    return;
                }
            }
            item.add(new Item(name));
        }
        else{
            JOptionPane.showMessageDialog(null, "Пустое имя не допустимо.");
        }
    }

    public void add(boolean value, String name){
        if(!name.equals("")) {
            for (Item i : item) {
                if (i.getName().equals(name)) {
                    return;
                }
            }
            item.add(new Item(value, name));
        }
        else{
            JOptionPane.showMessageDialog(null, "Пустое имя не допустимо.");
        }
    }

    public void removeByNumber(int number){
        if (number <= item.size() && number >= 0) {
            item.remove(number);
        }
        JOptionPane.showMessageDialog(null, "Указаный элемент не найден.");
    }

    public void removeByName(String name){
        for (int i = 0; i < item.size(); i++){
            if (item.get(i).getName().equals(name)){
                item.remove(i);
                return;
            }
        }
        JOptionPane.showMessageDialog(null, "Указаный элемент не найден.");
    }

    public void setForm(boolean form){
        this.form = form;
    }

    public boolean getForm(){
        return this.form;
    }

    @Override
    public Color getForeground() {
        return foreground;
    }

    @Override
    public void setForeground(Color foreground) {
        this.foreground = foreground;
    }

    @Override
    public Color getBackground() {
        return background;
    }

    @Override
    public void setBackground(Color background) {
        this.background = background;
    }

    public Color getTrueColor() {
        return trueColor;
    }

    public void setTrueColor(Color trueColor) {
        this.trueColor = trueColor;
    }

    public Color getFalseColor() {
        return falseColor;
    }

    public void setFalseColor(Color falseColor) {
        this.falseColor = falseColor;
    }

    @Override
    public Font getFont() {
        return font;
    }

    @Override
    public void setFont(Font font){
        if (font.getSize() <= MAX_FONT_SIZE && font.getSize() >= MIN_FONT_SIZE){
            this.font = font;
            setFontMaxSize(font.getSize());
            updateHeights();
        }
    }

    private void innerSetFont(Font font){
        this.font = font;
    }


    public int getFontMaxSize() {
        return fontMaxSize;
    }

    public void setFontMaxSize(int fontMaxSize) {
        this.fontMaxSize = fontMaxSize;
    }



    public Item get(String name){
        for (Item i : item){
            if(i.getName().equals(name)){
                return i;
            }
        }
        return null;
    }

    public void changeName(String oldName, String newName){
        if(get(oldName) != null){
            get(oldName).setName(newName);
        }
    }

    public Item get(int number){
        if (item.size() > number){
            return item.get(number);
        }
        return null;
    }

    public void updateHeights(){
        heights = new int[fontMaxSize + 1];
        for (int i = MIN_FONT_SIZE; i < heights.length; i++){
            heights[i] = getFontMetrics(new Font(getFont().getName(), getFont().getStyle(), i)).getHeight();
        }
    }

    private void updateSize(){
        fm = getFontMetrics(font);
        int maxStringWidth = 0;
        for (Item i : item){
            if (fm.stringWidth(i.getName()) > maxStringWidth){
                maxStringWidth = fm.stringWidth(i.getName());
            }
        }
        this.setMinimumSize(new Dimension(fontH * hC + maxStringWidth, (item.size() + 1 * fontH * hC)));
        width = this.getWidth();
        height = this.getHeight();
        //if all items can't be displayed cause of component height - we set the font smaller
        fontH = fm.getHeight();
        int optimalHeight = height / (item.size() == 0 ? 1 : item.size() * hC);
        int optimalFont = Arrays.binarySearch(heights, MIN_FONT_SIZE, heights.length, optimalHeight);
        if (optimalFont < 0){
            optimalFont = -optimalFont - 1;
        }
        innerSetFont(new Font(getFont().getName(), getFont().getStyle(), optimalFont));
    }


    public void paintComponent(Graphics g){
        updateSize();
        if (background == null){
            background = this.getParent().getBackground();
            if(foreground == null) {
                foreground = background.darker();
            }
            if (falseColor == null){
                falseColor = this.getParent().getBackground();
            }
        }
        g.setColor(background);
        g.fillRect(0, 0, width, height);
    }

    public void paintBorder(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        int H = fm.getMaxDescent();
        for (int i = 0; i < item.size(); i++){
            g2d.setColor(getForeground());
            g2d.drawString(item.get(i).getName(), ((width / 2) - (fm.stringWidth(item.get(i).getName()) / 2)), (fontH * 2 + (fontH * i * hC) - H));
            if(getForm()) {
                g2d.drawOval(fontH, fontH + (fontH * i * hC), fontH, fontH);
                if (item.get(i).getValue()) {
                    g2d.setColor(trueColor);
                    g2d.fillOval(fontH + 1, fontH + (fontH * i * hC) + 1, fontH - 1, fontH - 1);
                }
                else {
                    g2d.setColor(falseColor);
                    g2d.fillOval(fontH + 1, fontH + (fontH * i * hC) + 1, fontH - 1, fontH - 1);
                }
            }
            else{
                g2d.drawRect(fontH, fontH + (fontH * i * hC), fontH, fontH);
                if (item.get(i).getValue()) {
                    g2d.setColor(trueColor);
                    g2d.fillRect(fontH + 1, fontH + (fontH * i * hC) + 1, fontH - 1, fontH - 1);
                }
                else {
                    g2d.setColor(falseColor);
                    g2d.fillRect(fontH + 1, fontH + (fontH * i * hC) + 1, fontH - 1, fontH - 1);
                }

            }

        }

    }

    public void paintChildren(Graphics g){

    }


    public class Item{
        private boolean value;
        private String name;
        private boolean clickable = true;

        public Item(String name){
            this.name = name;
        }

        public Item(boolean value, String name){
            this.value = value;
            this.name = name;
        }

        public Item(){
            this.value = false;
            this.name = "ACheckBoxItem";
        }

        public void setClickable(boolean clickable){
            this.clickable = clickable;
        }

        public boolean getClickable(){
            return this.clickable;
        }

        public void changeValue(){
            if (clickable) {
                value = !value;
            }

        }

        public boolean getValue(){
            return this.value;
        }

        public void setName(String name){
            if (!name.equals("")) {
                for (Item i : item) {
                    if (name.equals(i.getName())) {
                        JOptionPane.showMessageDialog(null, "Данное имя уже занято.");
                        return;
                    }
                }
                this.name = name;
            }
            else{
                JOptionPane.showMessageDialog(null, "Пустые имена недопустимы.");
            }
        }

        public String getName(){
            return this.name;
        }


    }
}

1 个答案:

答案 0 :(得分:0)

JComponent通过名为EventListenerList的{​​{1}}字段提供protected

你应该可以使用......

listenerList

listenerList.add(ItemListener.class, itemListener);

添加和删除侦听器。

有关详细信息,请参阅javax.swing.event.EventListenerList