我正在尝试使用复合设计模式在JPanel上显示图标。我有一个扩展Icon的复合类,它有一个ArrayList,它包含一个实现Icon并扩展ImageIcon的自定义类。我想调用composites paintIcon()方法并循环遍历ArrayList,并绘制所有包含的Icons。如果我只是调用ImageIcon并将其添加到我的面板,我可以在屏幕上绘制一个Icon。我不明白为什么从CompositeIcon调用的paintIcon()不起作用。以下方法循环ArrayList,但似乎不从屏幕打印。当在GUI中调用setIcon()时,不应该将它绘制到JPanel上吗?
@Override
public void paintIcon(Component c, Graphics g, int i, int i1) {
for(int j = 0; j < icons.size(); j++){
icons.get(j).paintIcon(c, g, listX.get(j), listY.get(j));
}
}
到目前为止,我有一名测试员:
public class Display extends JFrame {
public CompositeIcons icons = new CompositeIcons();
public Display() throws MalformedURLException{
super();
this.setTitle("Composite Pattern");
this.setSize(600, 600);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setResizable(false);
this.setLayout(new FlowLayout());
ImageIcon image = new ImageIcon("discover.png");
IconOne iconOne = new IconOne("discover.png");
icons.addIcon(iconOne, 10, 10);
JPanel panel = new JPanel();
JLabel label = new JLabel();
label.setIcon(icons);
panel.add(label);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
panel.setPreferredSize(new Dimension(100,100));
this.add(panel);
this.setVisible(true);
}
}
和复合类:
public class CompositeIcons implements Icon {
private ArrayList<Icon> icons = new ArrayList();
private ArrayList<Integer> listX = new ArrayList();
private ArrayList<Integer> listY = new ArrayList();
public void addIcon(Icon icon, int x, int y){
icons.add(icon);
listX.add(x);
listY.add(y);
}
@Override
public void paintIcon(Component c, Graphics g, int i, int i1) {
for(int j = 0; j < icons.size(); j++){
icons.get(j).paintIcon(c, g, listX.get(j), listY.get(j));
}
}
@Override
public int getIconWidth() {
return 40;
}
@Override
public int getIconHeight() {
return 40;
}
}
和示例自定义Icon类:
public class IconOne extends ImageIcon implements Icon {
ImageIcon image;
int x, y;
public IconOne(String icon){
super(icon);
}
@Override
public void paintIcon(Component cmpnt, Graphics grphcs, int i, int i1) {
}
@Override
public int getIconWidth() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public int getIconHeight() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
答案 0 :(得分:0)
从IconOne中删除paintIcon方法。该类已经扩展了实现它的ImageIcon。