我並不是Java的新手(我已經使用它一年了),但這是我第一次使用swing。我試圖讓一個非常簡單的聊天客戶端同時學習socket和swing。我的問題是「我必須做些什麼才能正確對齊我的面板?」。我嘗試了很多東西(雖然我沒有在我的代碼中)。通常我會自己做這樣的事情,但我需要尋求幫助。我需要改變wieghtx,重量級嗎?我想讓客戶看起來像這樣。使用GridBagLayout對齊面板
這是它目前的樣子。
這裏是我的代碼。
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
GridBagConstraints c = new GridBagConstraints();
//Main Panel
JPanel window = new JPanel();
window.setLayout(new GridBagLayout());
window.setBackground(Color.black);
//Panels
JPanel display = new JPanel();
JPanel chat = new JPanel();
chat.setLayout(new GridBagLayout());
JPanel users = new JPanel();
display.setBackground(Color.blue);
c.gridx = 0;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(display, c);
chat.setBackground(Color.red);
c.gridx = 0;
c.gridy = 3;
c.gridheight = 2;
c.gridwidth = 1;
c.insets= new Insets(5,5,5,5);
window.add(chat, c);
users.setBackground(Color.green);
c.gridx = 2;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(users, c);
//Buttons
//Text fields
JTextArea text = new JTextArea("DEREADFADSFEWFASDFSADFASDF");
c.gridx = 0;
c.gridy = 0;
chat.add(text);
JTextField input = new JTextField("type here to chat", 50);
c.gridx = 0;
c.gridy = 1;
c.insets= new Insets(5,5,5,5);
chat.add(input);
add(window);
}
static class ActLis implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
}
的GridBagLayout是相當困難與手工編寫,特別是對人的新擺動。通過使用BorderLayout,您可以更簡單地實現該佈局,其左側面板包含三個左側組件。 – Vulcan
同意GridBagLayout過於複雜,特別是如果你是新手揮杆。我建議使用MigLayout或JGoodies FormLayout。允許複雜的佈局,但使如何佈局面板更清晰。 –
相關:http://stackoverflow.com/questions/10333559/gridbaglayout-jscrollpane-how-to-reduce-row-height – assylias