简体   繁体   中英

set location on event doesn't work

i have the following code, where i try to make some jLabels/jComboBox visible/invisible and move the location of those that are visible on jRadioButton click.

the issue is that the location is updated only on second click.

    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);

}  

I dont know why it is not working for you, mayby you are modifying somewhere else your GUI, or event is not fired at all. Here is working example. You should pase the code where you actually append the listener to the button. You did that right? It should be something like:

    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            singleButtonActionPerformed(e)
        }
    });

or Java8 variant using Lambdas

button.addActionListener(this::singleButtonActionPerformed)

but using this depends on context. It should be the object hta holds given method.

Here is working example with button and radio button (as suggested)

public class 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);

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM