[英]set location on event doesn't work
我有以下代码,在这里我尝试使一些jLabels / jComboBox可见/不可见,并移动那些在jRadioButton单击上可见的位置。
问题是该位置仅在第二次单击时才更新。
private void SingleButtonActionPerformed(java.awt.event.ActionEvent evt) {
this.serverLabel.setVisible(true);
this.serverList.setVisible(true);
this.serverLabel.setLocation(this.hostGroupLabel.getLocation().x, this.cpuCountSpinner.getLocation().y);
this.serverList.setLocation(this.cpuCountSpinner.getLocation().x, this.cpuCountSpinner.getLocation().y);
this.jXDatePickerStartDate.setLocation(153, jXDatePickerStartDate.getLocation().y);
this.requestedRamLabel.setVisible(false);
this.ramText.setVisible(false);
this.cpuLabel.setVisible(false);
this.cpuCountSpinner.setVisible(false);
}
我不知道为什么它对您不起作用,可能是您在GUI的其他地方进行了修改,或者根本未触发事件。 这是工作示例。 您应该在实际将侦听器附加到按钮的位置插入代码。 你说对了吗 应该是这样的:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
singleButtonActionPerformed(e)
}
});
或使用Lambdas的Java8变体
button.addActionListener(this::singleButtonActionPerformed)
但是使用this
取决于上下文。 它应该是对象hta拥有给定方法的对象。
这是按钮和单选按钮的工作示例(建议)
公共类SettingLocation {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(400, 400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
f.setContentPane(p);
p.setLayout(new FlowLayout());
JButton b = new JButton("Click me");
b.setBounds(150, 150,100,100);
p.add(b);
JRadioButton rb=new JRadioButton("Exmaple radio");
p.add(rb);
rb.addActionListener(new ActionListener() {
Random r = new Random();
@Override
public void actionPerformed(ActionEvent e) {
rb.setLocation(r.nextInt(300), r.nextInt(300));
}
});
b.addActionListener(new ActionListener() {
Random r = new Random();
@Override
public void actionPerformed(ActionEvent e) {
b.setLocation(r.nextInt(300), r.nextInt(300));
}
});
f.setVisible(true);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.