我有2個按鈕,一個名爲btnShort
,另一個名爲btnLong
。我希望它們具有相同的寬度,那麼最好的選擇是什麼?我如何建立2個相同寬度的JButton實例
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestCode2 {
public static void main(String[] args) {
JFrame window = new JFrame("Test2");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 200);
// ---------------------------------------------------------------------
GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
JPanel container = new JPanel(layout);
window.add(container);
constraints.gridy = 0;
JButton btnShort = new JButton("Short");
layout.setConstraints(btnShort, constraints);
container.add(btnShort);
constraints.gridy = 1;
JButton btnLong = new JButton("That's a long button");
layout.setConstraints(btnLong, constraints);
container.add(btnLong);
//This one won't work because button dimension is not known yet...
//btnShort.setPreferredSize(new Dimension(btnLong.getWidth(), btnLong.getHeight()));
// ---------------------------------------------------------------------
window.setVisible(true);
}
}
好吧,那很複雜。我沒有看到調用新的'Run()'方法的原因 - 它沒有工作,但我不明白爲什麼按鈕在這種情況下看起來不同! –
invokeLater的原因在[Inital Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)中有解釋。如果提供weightX約束,則這將更改列的所有組件的大小以佔用指定的空間量。此示例僅使用填充HORIZONTAL約束來請求列中的所有組件填充列 – MadProgrammer
對不起,但我仍然不明白爲什麼**您使用了'invokeLater()'?正如我所說,沒有任何工作正常,但有不同的方面(我不明白的另一件事) –