Home > Blockchain >  Java swing setSize works only in EventListner
Java swing setSize works only in EventListner

Time:10-05

setSize only works in the EventListner. It works with setPreferredSize. Why doesnt it work with setSize outside of the EventListner?

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {
 static int keyRange = 0;
 public static void main(String[] args) {
     JFrame frame = new JFrame();
     JPanel panel = new JPanel();
     frame.setLocationRelativeTo(null);
     frame.setSize(500, 600);
     JButton addMapkey = new JButton("Add mapkey");
     JTextField mapKey = new JTextField("Mapkey"   keyRange);
     JLabel allKeys = new JLabel();
     panel.add(mapKey);
     panel.add(addMapkey);
     panel.add(allKeys);
     panel.setLayout(new java.awt.FlowLayout());
     frame.getContentPane().add(panel);
     frame.setVisible(true);

     mapKey.setSize(mapKey.getText().length()*9,  addMapkey.getHeight());

     System.out.println(addMapkey.getHeight());
     addMapkey.addActionListener(e -> {
             keyRange  ;
             mapKey.setText("Mapkey"   keyRange);
             mapKey.setSize(mapKey.getText().length()*9,  addMapkey.getHeight());
     });
 }
}

CodePudding user response:

All modifications to the Swing and AWT components have to be performed on the Event Dispatch Thread, as described in the Initial Threads and The Event Dispatch Thread sections of the Java SE tutorial.

Quotes from those pages:

Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread.

Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

(emphasis above is mine).

The code above is ignoring these rules, therefore it is subject to unpredictable errors that are difficult to reproduce.

Please check the tutorials above and modify the code to follow the rules.

  • Related