复合,按钮和图标

时间:2011-11-18 22:28:53

标签: java composite

我的程序应该在对话中创建圆圈图标。 我有三个按钮,每个按钮代表要制作的图标的颜色。 所以,如果我在各种按钮上单击10次,我的程序应该创建10个不同颜色的圆圈。 这是我的代码,有两个类:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CompositeIcon extends JFrame {
        static CircleIcon icon;

    public static void main(String[] args) {
        final JFrame frame = new JFrame();
        final JLabel label = new JLabel();
            JButton redBut = new JButton("Red");
            JButton blueBut = new JButton("Blue");
            JButton greenBut = new JButton("Green");

            icon = new CircleIcon();

            redBut.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        icon.addIcon(new CircleIcon(50, Color.red));
        label.setIcon(icon);
        frame.repaint();
        frame.pack();
        }
    });

            blueBut.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        icon.addIcon(new CircleIcon(50, Color.blue));
        label.setIcon(icon);
        frame.repaint();
        frame.pack();
        }
    });

            greenBut.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        icon.addIcon(new CircleIcon(50, Color.green));
        label.setIcon(icon);
        frame.repaint();
        frame.pack();
        }
    });


        frame.setLayout(new FlowLayout());
        label.setPreferredSize(new Dimension(400, 200));
        frame.add(redBut);
        frame.add(blueBut);
        frame.add(greenBut);
        frame.add(label);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

我的另一堂课:

import java.util.*;
import java.awt.*;
import javax.swing.*;

public class CircleIcon implements Icon {
        private ArrayList<Icon> icons;
        private int width;
        private int height;

    public CircleIcon() {
        icons = new ArrayList<Icon>();
    }

    public void addIcon(Icon icon) {
        icons.add(icon);
        width += icon.getIconWidth();
        int iconHeight = icon.getIconHeight();
        if (height < iconHeight)
            height = iconHeight;
    }

    public int getIconHeight() {
        return height;
    }

    public int getIconWidth() {
        return width;
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
        for (Icon icon : icons) {
            icon.paintIcon(c, g, x, y);
            x += icon.getIconWidth();
        }
    }
} 

此时我的程序甚至不会编译,问题出在CompositeIcon-class中, 在icon.addIcon(new CircleIcon(50, Color.red));处为“红色按钮”,而在蓝色和绿色处则相同。

1 个答案:

答案 0 :(得分:1)

我测试了你的代码。您的CircleIcon类缺少构造函数。将其添加到您的圈子图标类。

 public CircleIcon(int number, Color awtColor) {
        // do whatever here
    }