如何从Java的内部类读取变量?
我设计了这个方法来显示一个带有我需要返回的值的滑块的窗口。你能告诉我如何检索JSlider值,目前我得到的错误是:“从内部类引用的局部变量必须是最终的或有效的最终的”?如何从Java的内部类读取变量?
private static int displayFontPanel(JFrame w){
JFrame window = new JFrame("Font Settings");
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
int fontSize = 14;
window.setSize(400, 200);
window.setLocationRelativeTo(w);
JSlider fntSize = new JSlider(8,40,20);
fntSize.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
fontSize = ((JSlider)evt.getSource()).getValue();
}
});
fntSize.setLabelTable(fntSize.createStandardLabels(8));
fntSize.setPaintLabels(true);
panel.add(fntSize, BorderLayout.CENTER);
window.setContentPane(panel);
window.setVisible(true);
return fontSize;
}
我会使用的AtomicInteger的不是int:
private static int displayFontPanel(JFrame w){
JFrame window = new JFrame("Font Settings");
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
final AtomicInteger fontSize = new AtomicInteger(14);
window.setSize(400, 200);
window.setLocationRelativeTo(w);
JSlider fntSize = new JSlider(8,40,20);
fntSize.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
fontSize.set(((JSlider)evt.getSource()).getValue());
}
});
fntSize.setLabelTable(fntSize.createStandardLabels(8));
fntSize.setPaintLabels(true);
panel.add(fntSize, BorderLayout.CENTER);
window.setContentPane(panel);
window.setVisible(true);
return fontSize.get();
}
哇!从来没有听说过这个,但工作和看起来更正统。 – florin27
更改方法签名
public void stateChanged(final ChangeEvent evt) {
之后,你就可以做
((JSlider) evt.getSource()).getValue()
这个答案解释比我为什么变量需要最终更好:https://stackoverflow.com/a/4732617/3061857
我做了改变,但是这并没有解决任何问题。我怎样才能从stateChanged方法获得getValue?这是我的问题:错误:从内部类引用的局部变量必须是最终的或有效的最终 fontSize =((JSlider)evt.getSource())。getValue(); – florin27
代码错误是否真的涉及到滑块,而不是fontSize
?如果是后者,那么你必须“欺骗”系统一点。闭包中引用的变量必须是最终的,即在下面的代码中保持不变。
但是,如果你骗一点,并宣布fontSize
为数组(final int[] fontSize = new int[1]
)并修改其内容,就可以工作了,就像这样:
fntSize.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
fontSize[0] = ((JSlider)evt.getSource()).getValue();
}
});
是的,它做到了。谢谢!但为什么它必须如此复杂?!是否有另一种解决方案来解决这个问题? – florin27
该错误已经告诉你该怎么做。该变量必须是最终才能在内部类中访问 –
使其最终导致我另一个错误:无法将值赋予最终变量sliderValue sliderValue =((JSlider)evt.getSource())。getValue(); – florin27