GridLayout导致我的组件消失

时间:2015-04-09 14:37:41

标签: java swing jframe layout-manager

我正在尝试创建一个窗口,其下方有一个可滚动的JTextArea和一个JTextField。我希望框架看起来像一个聊天窗口;一个,大的可滚动文本区域和单个带衬里的文本框架。我尝试过变种,但是我不能让文本区域滚动而不会使整个窗口可滚动。这太令人讨厌了。我当前的迭代只将一个面板绘制到屏幕上:

private void buildGUI() {

    Container chatClientContainer = getContentPane();
    chatClientContainer.setLayout(new BorderLayout());

    JPanel messagesReceivedPanel = new JPanel();
    messagesReceivedPanel.setLayout(new GridLayout(1, 1, 5, 5));
    JTextArea messagesReceived = new JTextArea("area");
    messagesReceivedPanel.add(messagesReceived);

    JPanel draftPanel = new JPanel();
    draftPanel.setLayout(new GridLayout(1, 1, 5, 5));
    JTextField draftMessage = new JTextField("field");
    draftPanel.add(draftMessage);

    chatClientContainer.add(new JScrollPane(messagesReceivedPanel));
    chatClientContainer.add(draftPanel);

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int windowWidth = 400;
    int windowHeight = 600;
    int posX = ((int) screenSize.getWidth())/2 - windowWidth/2;
    int posY = (int) screenSize.getHeight()/2 - windowHeight/2;

    setBounds(posX, posY, windowWidth, windowHeight);
    setResizable(true);
    setVisible(true);
}

我如何按照我想要的方式定位?

1 个答案:

答案 0 :(得分:2)

为什么不直接使用BorderLayout?放置JTextArea的JScrollPane BorderLayout.CENTER和JTextField(不是JTextFrame)BorderLayout.PAGE_END。

例如:

import java.awt.BorderLayout;

import javax.swing.*;

public class ChatPanel extends JPanel {
   private static final long serialVersionUID = 1L;
   private static final int ROWS = 15;
   private static final int COLS = 30;
   private JTextArea textArea = new JTextArea(ROWS, COLS);
   private JTextField textField = new JTextField(COLS);

   public ChatPanel() {
      JScrollPane scrollPane = new JScrollPane(textArea);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

      setLayout(new BorderLayout());
      add(scrollPane, BorderLayout.CENTER);
      add(textField, BorderLayout.PAGE_END);
   }

   private static void createAndShowGUI() {
      ChatPanel paintEg = new ChatPanel();

      JFrame frame = new JFrame("ChatPanel");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(paintEg);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }
}