Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You cannot move a button just like that, the layout manager tells it where it should be. Calling setText triggers the effect of layout manager for the whole component hierarchy. If you really want to do this, you should set a null layout manager, and manage all the sizes and locations of all components manually.</p> <p>Even if your button was moving in your original code, it was not painted correctly as soon as it left its original place - you could accidentally abuse Swing, but not completely.</p> <p>Working solution:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MovingButton { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { buildFrame(); } }); } private static void buildFrame() { JFrame f = new JFrame("Test"); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JPanel p = new JPanel(); p.setPreferredSize(new Dimension(500, 500)); p.setLayout(null); final JLabel label = new JLabel("Starting Text on Label"); label.setLocation(200, 0); label.setSize(label.getPreferredSize()); p.add(label); final JButton b = new JButton("Button"); b.setSize(b.getPreferredSize()); b.setLocation(0, 0); p.add(b); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b.setLocation((int)b.getLocation().getX() + 20, (int)b.getLocation().getY() + 20); label.setText(String.valueOf(System.nanoTime())); } }); f.add(p); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload