我已使用 Netbeans(使用 GUI 编辑器)向 GUI 添加了一个列表,并添加了三个值:红色、绿色和蓝色。 我想更改用户从列表中选择的图像的亮度,即,如果用户在列表中选择绿色,然后按增加亮度按钮,则只会增加绿色图像的亮度。 我已经添加了一个列表选择事件,按照此处的说明进行操作:http://docs.oracle.com/javase/tutorial/uiswing/components/list.html
我的事件代码如下:
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
// TODO add your handling code here:
jList1.getSelectedIndex();
if (jList1.getSelectedIndex() == 0) {
int listInt = 1;
}
if (jList1.getSelectedIndex() == 1) {
int listInt = 2;
}
if (jList1.getSelectedIndex() == 2) {
int listInt = 3;
}
}
我的亮度按钮代码如下:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println(listInt);
if (listInt == 1) {
increaseContrast(redImage);
update(redImage, redIcon, redLabel);
}
if (listInt == 2) {
increaseContrast(greenImage);
update(greenImage, greenIcon, greenLabel);
}
if (listInt == 3) {
increaseContrast(blueImage);
update(blueImage, blueIcon, blueLabel);
}
无论选择什么,总是将 0 打印到终端,这必定意味着第一个代码段不起作用。谁能帮忙解释一下为什么会发生这种情况?
最佳答案
因为您在 jList1ValueChanged
方法内声明和修改局部变量 listInt
,当您退出该函数时,这些变量会超出范围。当然,您想要更改对 jButton2ActionPerformed
也可见的实例变量(可能称为 listInt
),但只需在这些 if
语句中设置其值,而不是声明具有相同名称的局部变量。您得到 0 是因为这是 int 的默认初始化值(因此 listInt
)。
关于GUI 中的 Java 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21637808/