gpt4 book ai didi

java - 如何设置列表中的所有 JLabel 以更改显示的内容

转载 作者:行者123 更新时间:2023-11-30 07:29:36 25 4
gpt4 key购买 nike

已修复

我很抱歉这个糟糕的标题,但我花了 5 分钟的时间来表达它,抱歉。

我需要它,这样如果你按下所有的 JButton,它会获取 all2 中的图像,并将其放入 JLabel 标签(用列表制作)

我把 JLabel all2 放在 map() 上面,因为如果我不这样做,“ImageIcon setAll can't be resolve”。我没有将 JLabel 标签放在 map() 上方,因为它扰乱了使用列表 listofLabels 制作的 100 个 JLabel 的创建。它所显示的只是一个标签。 enter image description here enter image description here

public class mapMaker {

ArrayList<JLabel> listofLabels = new ArrayList<JLabel>(100);
ImageIcon forest = new ImageIcon("resources/terrains/forest.jpg");
ImageIcon wood = new ImageIcon("resources/terrains/wood.jpg");

JFrame frame = new JFrame("D&D");
JLabel all2=new JLabel( wood);



public map() {
int a=0,b=50;
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100,0,1000,700);
frame.getContentPane().setLayout(null);
frame.setVisible(true);


JButton all=new JButton("Set All To");
frame.getContentPane().add(all);
all.setBounds(600,450,150,50);
all.setFont(new Font("Courior", Font.BOLD, 25));
all.addActionListener(boardListener);

frame.getContentPane().add(all2);
all2.setBounds(800,450,50,50);
all.addActionListener(boardListener);


for ( i = 0; i < 100; i++) {
JLabel label =new JLabel(forest);
label.setIcon(forest);
listofLabels.add(label);
a=a+50;
if(a>549) {
b=b+50;
a=50;
}
frame.getContentPane().add(label);
label.setBounds(a, b, 50,50);
label.setTransferHandler(new TransferHandler("icon"));


}
}


ActionListener boardListener = new ActionListener (){
public void actionPerformed(ActionEvent e){
ImageIcon setAll=(ImageIcon) all2.getIcon();

![enter image description here][2]label.setIcon(setAll);



}
};;

public static void main(String[]args) {
new map();
}

最佳答案

为什么不简单地遍历 JLabel 的数组(或 ArrayList),将 JLabel 的所有图标设置为所选图标?

例如:

ActionListener boardListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Set All To")) {
ImageIcon setAll = (ImageIcon) all2.getIcon();
for (JLabel label : listofLabels) {
label.setIcon(setAll);
}
}
}
};

关于java - 如何设置列表中的所有 JLabel 以更改显示的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8399538/

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