2015-04-14 5 views
1

Je travaille sur l'interface graphique en Java. Je ne pouvais pas comprendre comment je peux insérer une nouvelle ligne pour chaque champ. Quelqu'un peut il m'aider avec ce problème? Voici mon code:Insérer une nouvelle ligne pour chaque champ dans Java GUI

public class InsertPanel extends JPanel{ 
    public InsertPanel() { 
     setBackground(Color.yellow); 
     setPreferredSize(new Dimension(540, 500)); 

     JLabel isbnLabel = new JLabel("ISBN: "); 
     JTextField isbnTextFld = new JTextField(10); 

     JLabel authorLabel = new JLabel("Author: "); 
     JTextField authorTextFld = new JTextField(10); 

     JLabel titleLabel = new JLabel("Title: "); 
     JTextField titleTextFld = new JTextField(10); 

     JLabel priceLabel = new JLabel("Price: "); 
     JTextField priceTextFld = new JTextField(10); 

     JButton submitBtn = new JButton("Submit"); 

     JTextArea textArea = new JTextArea(10, 30); 

     add(isbnLabel); 
     add(isbnTextFld); 
     add(authorLabel); 
     add(authorTextFld); 
     add(titleLabel); 
     add(titleTextFld); 
     add(priceLabel); 
     add(priceTextFld); 
     add(submitBtn); 
     add(textArea, BorderLayout.CENTER); 
    } 
} 

Ces champs dans la sortie étaient sur la même ligne. Je veux ressembler à

ISBN:

Auteur:

Titre:

Prix:

Envoyer

TextArea:

Merci beaucoup!

+0

FlowLayout et force un saut de ligne? – JClassic

+0

@JClassic: euh, pourquoi pas. –

Répondre

2

Pensez à utiliser un GridBagLayout

Peut-être quelque chose comme ...

GridBagLayout

public class InsertPanel extends JPanel { 

    public InsertPanel() { 
     setBackground(Color.yellow); 

     setLayout(new GridBagLayout()); 

     JLabel isbnLabel = new JLabel("ISBN: "); 
     JTextField isbnTextFld = new JTextField(10); 

     JLabel authorLabel = new JLabel("Author: "); 
     JTextField authorTextFld = new JTextField(10); 

     JLabel titleLabel = new JLabel("Title: "); 
     JTextField titleTextFld = new JTextField(10); 

     JLabel priceLabel = new JLabel("Price: "); 
     JTextField priceTextFld = new JTextField(10); 

     JButton submitBtn = new JButton("Submit"); 

     JTextArea textArea = new JTextArea(10, 30); 

     GridBagConstraints gbc = new GridBagConstraints(); 
     gbc.gridx = 0; 
     gbc.gridy = 0; 

     add(isbnLabel, gbc); 
     gbc.gridy++; 
     add(authorLabel, gbc); 
     gbc.gridy++; 
     add(titleLabel, gbc); 
     gbc.gridy++; 
     add(priceLabel, gbc); 

     gbc.gridx++; 
     gbc.gridy = 0; 
     add(isbnTextFld, gbc); 
     gbc.gridy++; 
     add(authorTextFld, gbc); 
     gbc.gridy++; 
     add(titleTextFld, gbc); 
     gbc.gridy++; 
     add(priceTextFld, gbc); 
     gbc.gridy++; 
     add(submitBtn, gbc); 

     gbc.gridx++; 
     gbc.gridy = 0; 
     gbc.gridheight = gbc.REMAINDER; 
     add(new JScrollPane(textArea), gbc); 
    } 

} 

Voir How to Use GridBagLayout pour plus de détails