【发布时间】:2017-09-03 03:25:31
【问题描述】:
我有一个 arrayList<Integer> 和 arrayList<JLabel>。 Integer 将钱保存为整数,而 JLabel 保存与字符串相同的值。我想从两个标签中随机删除元素。例如,如果在 JLabel 中删除了 20TL(tl 是货币),我也想在整数数组列表中删除它。这很简单。但后来我想计算 ArrayList 中剩余资金的平均值。这是我的另一个数组列表,用于将 0 到 23 个数字随机排列。因此,我删除了 IntList 和 JLabel 列表中的相同元素。
ArrayList<Integer> Numbers = new ArrayList<Integer>();
for(int n = 0; n<24; n++){
Numbers.add(n);
}
Collections.shuffle(Numbers);
那么这是我的两个列表。
ArrayList<Integer> Money = new ArrayList<Integer>();
Money.add(1); Money.add(5); Money.add(10); Money.add(25); Money.add(50); Money.add(100); Money.add(500); Money.add(1000); Money.add(2000);
Money.add(5000); Money.add(10000); Money.add(20000); Money.add(25000); Money.add(30000); Money.add(40000); Money.add(50000); Money.add(100000); Money.add(200000);
Money.add(300000); Money.add(400000); Money.add(500000); Money.add(750000); Money.add(1000000); Money.add(2000000);
String[] para =new String[] {"1 TL","5 TL","10 TL","25 TL", "50 TL","100 TL","500 TL",//create an array for moneys
"1.000 TL","2.000 TL","5.000 TL","10.000 TL","20.000 TL","25.000 TL",
"30.000 TL","40.000 TL","50.000 TL","100.000 TL",
"200.000 TL","300.000 TL","400.000 TL","500.000 TL","750.000 TL"
,"1.000.000 TL","2.000.000 TL"};
ArrayList <JLabel> myLabel = new ArrayList<JLabel>();
for(int i=0; i < 12 ; i++){
JLabel holder = new JLabel();
holder.setText(para[i]);
myLabel.add(holder);
p2.add(holder);//add the label to the panel
}
for(int j=12; j<para.length; j++){
JLabel holder2 = new JLabel();
holder2.setText(para[j]);
myLabel.add(holder2);
p3.add(holder2);
}
这是我在 actionListener 方法中删除 style.this
private int asd = 0;
///// some code
myLabel.get(Numbers.get(asd)).setVisible(false);
Money.remove(Numbers.get(asd));
当我尝试在 intarraylist 中删除钱时,计算方法无法正常工作。因为例如,如果 Numbers 数组的第一个元素是 5,那么 50 将被删除。并且 arrayList 将被缩小。之后,当 Numbers.get(asd) 等于 23 时,int arraylist 中将没有第 23 个元素。因为它缩小了并且没有这样的第 23 个元素。我希望我能很好地告诉我我的问题。
Ps:我尝试使用数组而不是数组列表。但我无法计算左侧的平均值。因为删除某些元素时数组不会缩小。
【问题讨论】:
-
你看起来过于复杂了。为什么不使用
JList<Integer>,用DefaultListModel<Integer>填充它并只处理一个集合——这里是列表模型。 -
为了获得更好的帮助,事实上,让我们全面快速了解您的问题的最佳方式是创建并发布一个 minimal example program,这是一个小而完整的程序,仅有必要的代码来演示您的问题,我们可以复制、粘贴、编译和运行而无需修改。
-
很抱歉弄得一团糟。我试试看。但是我看不到模型。请给我看。
标签: java arrays swing arraylist