gpt4 book ai didi

java - 复合、按钮和图标

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:37 27 4
gpt4 key购买 nike

我的程序应该在对话中创建圆形图标。我有三个按钮,每个按钮代表要制作的图标的颜色。因此,如果我点击不同的按钮 10 次,我的程序应该创建 10 个不同颜色的圆圈。这是我的代码,分为 2 个类:

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);
}
}

还有我的其他类(class):

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 类中,对于“红色按钮”,在 icon.addIcon(new CircleIcon(50, Color.red)); 处,对于蓝色和绿色也是如此。

最佳答案

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

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

关于java - 复合、按钮和图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8189955/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com