简体   繁体   English

JButton文本不在图标中,setBounds不起作用

[英]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: JFrame是这样的:

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: 并且按钮有2个问题:

  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?) 由于一些奇怪的原因, setBounds无法正常工作,按钮总是出现在顶部中心(似乎只能在没有布局的情况下使用,任何替代方法都可以设置按钮的位置和大小,但我喜欢?)

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?) (目前只找到了逐个更改它们的解决方案,还有其他办法吗?)

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. 默认情况下,水平文本位置设置为TRAILING,这就是它位于图标一侧的原因。

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. TLDR:使用布局管理器,他们将为您调整大小和位置。

setBounds() only works when you use absolute layout, whereas JPanel uses FlowLayout by default. setBounds()仅在使用绝对布局时有效,而JPanel默认使用FlowLayout。 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. 但是,对于绝对布局,您还必须手动设置x / y / width / height,因此通常最好使用布局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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