我们有一个 Controller ,其中有一个预先声明的 JList 和 JLabel,我们将它们添加到 JPanel 中。在初始布局/添加代码之外,我可以更新 JLabel (例如更改其文本),但我无法更改 JList 的选择(例如 jlist.setSelection(index) ),它将更新 UI。代码如下:
public class Test {
private JPanel myPanel;
private JList myList;
private JLabel myLabel;
public Test() {
//Some init code here...
this.myPanel = new JPanel();
this.myPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
String[] values = {"Value1", "Value2", "Value3", "Value4"}; //etc. etc.
this.myList = new JList(values);
this.myPanel.add(this.myList, gbc); //Add to panel
this.myLabel = new JLabel("Label1");
this.myPanel.add(this.myLabel, gbc); //Add to panel
//Add some code here to add it to a frame or something to display
}
public void updateLabel(String workingNewLabel) {
//The following works...
this.myLabel.setText(workingNewLabel);
// as in the label component in the JPanel will
//now be updated to the new value of workingNewLabel
}
public void changeSelectionInListToSomeIndex(int nonWorkingNewIndex) {
//The following does NOT update the JList in the panel...
//the selection remains whatever it was last set to.
this.myList.setSelectedIndex(nonWorkingNewIndex);
}
}
我已经能够通过迭代 myPanel 中的所有组件查找 JList 组件然后将其设置为 myList 例如来解决这个问题。
//Code that goes after the line this.myPanel.add(this.myList, gbc);
for(Component component : this.myPanel.getComponents() ) {
//Iterate through it all until...
if (component.getClass() == this.myList.getClass()) {
this.myList = (JList) component; //cast the component as JList
}
}
为什么我需要对 JList 执行此操作而不是对 JLabel 执行此操作?这是一种解决方法,但看起来非常黑客化。
提前致谢! -丹尼尔
最佳答案
@JB 是对的。这是一个工作sscce :
/** @see http://stackoverflow.com/q/9540263/230513 */
public class Test {
private static Test test = new Test();
private JPanel myPanel;
private JList myList;
private JLabel myLabel;
public Test() {
myPanel = new JPanel();
myPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
String[] values = {"Value1", "Value2", "Value3", "Value4"};
myList = new JList(values);
myPanel.add(this.myList, gbc);
myLabel = new JLabel("Label1");
myPanel.add(this.myLabel, gbc);
myPanel.add(new JButton(new AbstractAction("Select Value3") {
@Override
public void actionPerformed(ActionEvent e) {
test.updateList(2);
}
}));
}
public void updateLabel(String label) {
myLabel.setText(label);
}
public void updateList(int index) {
myList.setSelectedIndex(index);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(test.myPanel);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
关于java - 将 JList 添加到 JPanel 与 JLabel 不同(除了明显的之外),为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9540263/