Ich benutze eine Gridbaglayout für mein Layout, und ich frage mich, wie man es neu anordnen, so dass das Textfeld Textfeld direkt über das Passwort Textfeld und das Login geht Schaltfläche geht unter das Passwort Textfeld.Java Swing - Wie stapelt man Benutzername Textfeld und Passwort Textfeld
Allerdings möchte ich etwas wie folgt aus:
Mein Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestingJavaCode {
public TestingJavaCode() {
JFrame appFrame = new JFrame();
JPanel loginPanel = new JPanel();
appFrame.setSize(1200, 800);
loginPanel = new JPanel(new GridBagLayout());
// Button for logging in, with respective GridBagConstraint
// setFocusable is set to false to take out the border around the text
JButton loginButton = new JButton("Login");
GridBagConstraints lButtonC = new GridBagConstraints();
loginButton.setFocusable(false);
// Username text-field and JLabel with respective GridBagConstraints
JTextField tfUsername = new JTextField(15);
GridBagConstraints tfUserC = new GridBagConstraints();
JLabel txtUser = new JLabel("Username: ");
GridBagConstraints txtUserC = new GridBagConstraints();
// Password text-field and JLabel with respective GridBagConstraints
JPasswordField tfPassword = new JPasswordField(15);
GridBagConstraints tfPassC = new GridBagConstraints();
JLabel txtPassword = new JLabel("Password: ");
GridBagConstraints txtPassC = new GridBagConstraints();
// Add all components to the JFrame
// Making sure to add the text before the text-fields
loginPanel.add(txtUser, txtUserC);
loginPanel.add(tfUsername, tfUserC);
loginPanel.add(txtPassword, txtPassC);
loginPanel.add(tfPassword, tfPassC);
loginPanel.add(loginButton, lButtonC);
// Show the frame
appFrame.add(loginPanel);
appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
appFrame.setVisible(true);
}
public static void main(String[] args) {
new TestingJavaCode();
}
}
EDIT: Ich bin offen für die Verwendung anderer Layout-Manager.
warum fügen Sie die Etiketten dann 'loginPanel.add (txtUser, txtUserC);' –
@ScaryWombat ich die Etiketten auch wollen. Ich möchte etwas wie das Bild, das ich gepostet habe, aber ich möchte die Etiketten auf der linken Seite der Textfelder, wie mein Code produziert. – Theo
Nun, Sie müssen tatsächlich einige Einschränkungen festlegen, um dem Layout-Manager mitzuteilen, wo die Komponenten positioniert werden sollen. Sehen Sie sich die gridx/y-Einschränkungen an, die im Swing-Lernprogramm zu [Verwendung von GridBagLayout] (http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html) beschrieben sind. Das Tutorial enthält ein funktionierendes Beispiel, das Sie herunterladen und ändern können. – camickr