问题
The following code describes a button that is instantiated in a JPanel with a BoxLayout in Page Axis:
private class AddInputSetButton extends JButton {
public AddInputSetButton() {
super("+");
setMinimumSize(new Dimension(100, 100));
pack();
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addInputGroup();
}
});
}
}
I have tried setSize(), setPreferredSize(), and setMinimumSize() to no avail, none of them resize the button. I am still relatively new to Java GUIs, so hopefully it is something simple.
How do I adjust the size of the button?
EDIT: After further inspection, setPreferredSize() changes the size of the JPanel containing the buttons to the right size, but the buttons remain the same size.
回答1:
JButtons
(and a few other components) can be a bit goofy in layout managers. The layout manager is noticing that your button has a preferred size that needs to be respected, so it's adjusting your pane to accommodate. But your JButton
is happy doing it's thing (what it thinks is right) unless you really force it to consider the size it's supposed to be.
If you're manually sizing your button (which isn't necessarily recommended), I'd say you should set all three properties (Minimum, maximum, and preferred). Maximum is the key - it forces the button to consider the other two sizes.
Here's a simple example that should work.
import java.awt.Dimension;
import javax.swing.*;
public class ButtonSizes {
private static class AddInputSetButton extends JButton {
Dimension d;
public AddInputSetButton(int width, int height) {
super("+");
d = new Dimension(width, height);
setMinimumSize(d);
setMaximumSize(d);
setPreferredSize(d);
}
}
public static void main(String[] args) {
Box buttons = Box.createVerticalBox();
buttons.add(new AddInputSetButton(100,100));
buttons.add(new AddInputSetButton(200,200));
buttons.add(new AddInputSetButton(300,300));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(buttons);
frame.pack();
frame.setVisible(true);
}
}
来源:https://stackoverflow.com/questions/21734374/setminimumsize-not-working-for-jbutton