简体   繁体   中英

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. I'm trying to create a custom JButton class which can be called from anywhere with custom text to make things easier. 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.

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.

make sure you dont have any layout by adding this to the JFrame

this.setLayout(null); 

else the button will be adjusted to the layout

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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