1
我正在嘗試在Java中實現GridBagLayout,以便爲我正在構建的程序創建一個登錄對話框。我正在尋求乾淨的Google登錄。我遇到的主要問題是我使用GridBagConstraints
設置的約束條件不起作用。這是我希望對話框的樣子。在Java中實現GridBagLayout的問題
這裏是因爲我想實現對話框的代碼。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login_Dialog extends JDialog{
// SEtting up the required components for the sign in
/**
*
*/
private static final long serialVersionUID = 1L;
protected JLabel username_Label = new JLabel("Username");
protected JLabel password_Label = new JLabel("Username");
protected JTextField username_Field = new JTextField(30);
protected JTextField password_Field = new JTextField(30);
protected JButton sign_In = new JButton("Sign in!");
public Login_Dialog() {
setSize(600,400);
setTitle("Sign in");
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
add(username_Label);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
add(username_Field);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 2;
add(password_Label);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 4;
add(password_Field);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 5;
add(sign_In);
setVisible(true);
}
}
UPDATE:
我已經做了一些改變,似乎我達到我想要的結果。現在的問題是,一切都居中,按鈕的長度太寬。另外,我希望textfield和label更大。
這裏是更新爲GridBagLayout
//cusotmization of buttons
Dimension signD = sign_In.getPreferredSize();
signD.height = 50;
signD.width = 30;
sign_In.setPreferredSize(signD);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
add(username_Label,c);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 0;
c.gridy = 1;
add(username_Field,c);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 0;
c.gridy = 2;
add(password_Label,c);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 0;
c.gridy = 3;
add(password_Field,c);
//
// c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 0;
c.gridy = 5;
//
add(sign_In,c);
但將我所用'GridBagConstraints'使用的代碼給我想要的結果嗎? –
我稍後會添加一個完整的示例,但我現在很忙。嘗試一下! – phil
好的,我會試試看,然後回覆給你。 –