简体   繁体   English

如何设置JButton的大小和图像?

[英]How to set size and image of JButton?

Sorry if this is a really stupid question but I can't figure out how to set the size of a JButton. 抱歉,如果这是一个非常愚蠢的问题,但是我不知道如何设置JButton的大小。 I'm trying to create a custom JButton class which can be called from anywhere with custom text to make things easier. 我正在尝试创建一个自定义JButton类,可以使用自定义文本在任何地方调用该JButton类,以简化操作。 I am also trying to set a background image which doesn't appear to be working either. 我也试图设置一个背景图像,它似乎也不起作用。 I have tried using this.setSize(1000, 1000) (surely this should work) but this does nothing at all. 我试过使用this.setSize(1000,1000)(当然这应该工作),但这根本不起作用。

Here is my code: 这是我的代码:

package menu;

import javax.swing.*;

@SuppressWarnings("serial")
public class Button extends JButton
{

    public Button(String name)
    {
        ImageIcon background = new ImageIcon("/assets/buttons/menu.png"); //Is this how you set a background image for a button?
        this.setText(name);
        this.setIcon(background);
        this.setLayout(null); //This hasn't made a difference
        this.setSize(300, 80); //This does nothing
    }
}

try 尝试

import javax.swing.JButton;


public class replaceButton **extends JButton**
{
    public replaceButton(String name)
    {
         this.setText(name);
         ImageIcon background = new ImageIcon("/assets/buttons/menu.png");
         this.setIcon(background);
         this.setSize(1000,1000);
    }
}

by extending JButton you give it the properties of a button. 通过扩展JButton,您可以为其提供按钮的属性。

make sure you dont have any layout by adding this to the JFrame 通过将其添加到JFrame来确保没有布局

this.setLayout(null); 

else the button will be adjusted to the layout 否则按钮将调整为布局

see http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html 参见http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

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

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