1
我的程序應該在對話框中創建圓形圖標。 我有三個按鈕,每個都代表要製作的圖標的顏色。 所以,如果我在各種按鈕上點擊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);
}
}
而我的其他類:
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));
爲「紅色按鈕」,藍色和綠色相同。
什麼是例外? – r0ast3d
如果我嘗試運行,並按下我的一個按鈕,我得到錯誤代碼: 「線程中的異常」AWT-EventQueue-0「java.lang.Error:未解決的編譯問題: \t構造函數CircleIcon(int,Color )未定義 \t at CompositeIcon $ 1.actionPerformed(CompositeIcon.java:20) – user1054685
@ user1054685爲什麼要創建一個圖標陣列 – mKorbel