我正在尝试更改按钮大小,但是当我设置宽度时,即使高度有自己的值,高度也会自动更改。如何仅更改宽度(或高度)?我需要这个到我的"重置"和"计算"按钮。代码(没有不必要的其他代码)
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);
}
}
好吧,据我所知,您强制Wind
实例的宽度和高度具有相同的值:
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int s = (int) (d.getWidth() < d.getHeight() ? d.getHeight() : d.getWidth());
return new Dimension(s, s);
}
Wind#getPreferredSize
返回一个 Dimension
实例,该实例包含 Wind
实例所需的宽度和高度。在您的情况下,它会返回一个由两倍相同值组成的Dimension
的新实例:s
,这是您通过 Wind#setPreferredSize
设置的宽度和高度中最大的一个。您可能想按照弗里施刚刚建议@Elliott做:)
顺便说一下,你也在做最后的事情:
frame.pack()
...
frame.setSize(...);
在我看来,您应该执行其中之一,但是将这两种方法都称为:)
因为你getPreferredSize()
的方法 -
// sets s to the least of height and width.
int s = (int) (d.getWidth() < d.getHeight() ? d.getHeight() : d.getWidth());
return new Dimension(s, s); // <-- sets height and width the same.
我想你想使用(取决于你的目标)-
if (d.getWidth() < d.getHeight()) {
return new Dimension(d.getWidth(), d.getHeight());
}
return new Dimension(d.getHeight(), d.getWidth());