[英]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.