How to resize a button (JButton) when adding characters to it? Layout null! Now, when adding characters, it adds about three characters somewhere, and then it appears ... and all the other added characters are not visible. Maybe you need to make some settings for the button ...

  • The question is rather vague. The behavior of the swing components, including size, is determined by many different factors - the owner, his Layout om, the settings ... You did not say anything about it. Most likely, you need to deal with the layout. - m. vokhm

2 answers 2

Usually, the position and size of the components in the container are controlled by the LayoutManager installed in the container. In your case, when the layout manager is null , there is no one to manage it. Therefore, the size and position of the components must be controlled manually.

For example, you can add code that changes the text on a button with a code that will increase the width of the button:

 JButton btn = new JButton("AAA"); btn.addActionListener( ae -> {btn.setText(btn.getText()+"A"); Dimension dim = btn.getSize(); btn.setSize(dim.width + 10, dim.height);} ); 

Or you can create your own button class by inheriting from JButton and override the setText method:

 public void setText(String text) { super(text); Dimension dim = getSize(); setSize(text.length * 10, dim.height); } 

But it would be more correct not to reinvent the wheel, but to use the appropriate linker.

    After adding characters you need to write

     button1.setSize(button1.getPreferredSize()); button1.setBounds(button1.getX(),button1.getY(),button1.getWidth(), button1.getHeight());