Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setSize() not working?

I have a program which takes two buttons, one that is regular and one that has a picture that changes depending on mouse roll over. Currently, since the picture is large, JButton custom is very large as well, can I change the size of custom and keep the image (and roll over image) proportionate? I have tried setSize, and it does't do anything. Any feedback would be appreciated!

 custom.setSize(50, 50);

Here is all of my code:

Main class:

package Buttons;

import javax.swing.JFrame;

public class Main_buttons{

public static void main(String[] args) {

    ButtonClass press = new ButtonClass();
    press.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    press.setSize(500,500);
    press.setVisible(true);
    }
}

Other class:

package Buttons;

import java.awt.FlowLayout; //layout proper
import java.awt.event.ActionListener; //Waits for users action
import java.awt.event.ActionEvent; //Users action
import javax.swing.JFrame; //Window
import javax.swing.JButton; //BUTTON!!!
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane; //Standard dialogue box

public class ButtonClass extends JFrame {

private JButton regular;
private JButton custom;

public ButtonClass() { // Constructor
    super("The title"); // Title
    setLayout(new FlowLayout()); // Default layout

    regular = new JButton("Regular Button");
    add(regular);

    Icon b = new ImageIcon(getClass().getResource("img.png"));
    Icon x = new ImageIcon(getClass().getResource("swag.png"));
    custom = new JButton("Custom", b);
    custom.setRolloverIcon(x); //When you roll over the button that says custom the image will change from b to x
    custom.setSize(50, 50);
    add(custom);

    Handlerclass handler = new Handlerclass();
    regular.addActionListener(handler);
    custom.addActionListener(handler);


}

public class Handlerclass implements ActionListener { // This class is inside the other  class


    public void actionPerformed(ActionEvent eventvar) { // This will happen
                                                        // when button is
                                                        // clicked
        JOptionPane.showMessageDialog(null, String.format("%s", eventvar.getActionCommand()));//Opens a new window with the name of the button
    }
}





}

1 Answers

As some users have mentioned, you can override getPreferredSize() and getMinimum/MaximumSize(). Or you could just call the setter methods for the preferred, maximum, and minimum sizes. If you set the preferred size and the maximum size...

custom.setPreferredSize(new Dimension(50, 50));
custom.setMaximumSize(new Dimension(50, 50));

then you will usually get that size.

like image 111
M3579 Avatar answered Apr 17 '26 11:04

M3579