I'm trying to change button size but when I set width, height automatically changes too even though height has own value. How can I change only width (or height)? I need this to my "reset" and "calc" buttons. Code (without unnecessary other code)
class Wind extends JButton {
//declaration of variables
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int s = (int) (d.getWidth() < d.getHeight() ? d.getHeight() : d.getWidth());
return new Dimension(s, s);
}
public static void main(final String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JComponent gui = new JPanel(new FlowLayout());
for (int ii = 1; ii < 20; ii++) {
final JButton button = new Wind("");
gui.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
gui.setBorder(new EmptyBorder(4, 3, 4, 8));
final JButton reset = new Wind("Reset");
Dimension dim = new Dimension(40,80);
reset.setPreferredSize(dim);
gui.add(reset);
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JFrame f = new JFrame("Name of my frame");
f.add(gui);
final JButton cal = new Wind("Calc");
gui.add(cal);
cal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { }
});
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.pack();
f.setVisible(true);
f.setSize(350, 450);
f.setResizable(false);
}
};
SwingUtilities.invokeLater(r);
}
}
Because of your
getPreferredSize()
method -I think you want to use (depending on your objective) -