当我在外部的 Action 监听器中创建 jspinner 时,我在另一个 Action 监听器中有一个 Action 监听器,它可以工作,但在内部的 Action 监听器中却不能。这是我的代码。问题是什么?
这是不起作用的代码,如果我将 sp 和 js 放在内部操作监听器之外,它就会起作用。
menuItem = new JMenuItem("Insert Exams", KeyEvent.VK_E);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
count = 0;
jt = new ArrayList[3];
for (int i = 0; i < 3; i++)
jt[i] = new ArrayList<JTextField>();
panel = new JPanel();
panel.setLocation(0, 0);
panel.setSize(d.width, d.height);
panel.setLayout(null);
JButton add = new JButton("add Exam");
add.setSize(120, 80);
add.setLocation(250, 100);
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
sp = new SpinnerNumberModel(1, 1, 5, 1);
js = new JSpinner(sp);
js.setSize(100, 30);
js.setLocation(450, 80 + count * 50);
panel.add(js);
for (int i = 1; i < 3; i++) {
JTextField jt1 = new JTextField(20);
jt1.setSize(150, 30);
jt1.setLocation(450 + i * 200, 80 + count * 50);
jt[i].add(jt1);
panel.add(jt1);
}
count++;
repaint();
}
});
panel.add(add);
setContentPane(panel);
}
});
最佳答案
您应该使用revalidate
而不是repaint
。
您还应该依赖 LayoutManager
而不是使用 setSize
和 setLocation
关于java - JSpinner 在 Action 监听器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17914931/