user1090694
user1090694

Reputation: 639

JButton text not in the icon and setBounds not working

I have a panel something like this:

class A extends JPanel{
    private JButton button;

    A(int width, int height){
        setSize(width, height);
        button = new JButton("text");
        button.setIcon(IconLoadedHere);
        button.setBounds(50, 50, getWidth()/5, getHeight()/5);
        button.setBorder(BorderFactory.createEmptyBorder());
        add(button);
     }
}

The JFrame is like this:

public class window extends JFrame{
    private JPanel panel;

    public window(){
        panel = new JPanel();
         setTitle("test");
         setSize(1280, 720);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setVisible(true);
    }
    public void loadA(){
         remove(panel);
         panel = new A(getWidth(), getHeight());
             add(panel);
         validate();
    }
}

And have 2 problems with the button:

  1. I'd like to have the text over the image, is that possible (preferably in the middle of the image)? currently it appears on the left of it. (SOLVED)

  2. for some weird reason setBounds is not working, button always appear on top center (seems that only can be used without layout, any alternative to set the buttons place and size to however i preffer?)

And also 1 question: If I want to resize the window, what do I do to make the button and text to resize accordingly? (currently only found the solution on changing them one by one, is there any other way?)

Upvotes: 1

Views: 994

Answers (2)

Cyrille Ka
Cyrille Ka

Reputation: 15523

To control the way the text is displayed in the button you should use:

button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.CENTER);

This will put the text in the center of the button.

By default, the horizontal text position is set to TRAILING, and that is why it is positionned on the side of the icon.

For the layout part of the question, you should really read the relevant part of the official tutorial. TLDR: use layout managers, they will do the resizing and positioning for you.

Upvotes: 4

Jimmt
Jimmt

Reputation: 902

setBounds() only works when you use absolute layout, whereas JPanel uses FlowLayout by default. To disable that I think it's

panel.setLayout(null);

However, with absolute layout, you will also have to manually set x/y/width/height, so it's usually better to use a layout.

Upvotes: 1

Related Questions