我正在制作一个简单的聊天 GUI。我遇到了一个问题,我的程序没有随着聊天的进行而向下滚动。我也不确定如何在程序中添加滚动条/窗格,而不会通过将我的主要文本区域放入面板并破坏界面外观来搞砸一切。如何调整主聊天框,而不会通过将其chatBox
放入 JPanel 来搞砸并使其看起来很丑陋。我将在下面发布我的所有代码。
MainGUI类:
package coltGUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
public class MainGUI implements ActionListener {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
MainGUI gui = new MainGUI();
gui.display();
}
JButton sendMessage;
JTextField messageBox;
JTextArea chatBox;
public void display() {
JFrame frame = new JFrame("Colt Chat");
JPanel southPanel = new JPanel();
frame.getContentPane().add(BorderLayout.SOUTH, southPanel);
southPanel.setBackground(Color.BLUE);
southPanel.setLayout(new GridBagLayout());
messageBox = new JTextField(30);
sendMessage = new JButton("Send Message");
chatBox = new JTextArea();
chatBox.setEditable(false);
frame.getContentPane().add(BorderLayout.CENTER, chatBox);
chatBox.setLineWrap(true);
GridBagConstraints left = new GridBagConstraints();
left.anchor = GridBagConstraints.WEST;
GridBagConstraints right = new GridBagConstraints();
right.anchor = GridBagConstraints.EAST;
right.weightx = 2.0;
southPanel.add(messageBox, left);
southPanel.add(sendMessage, right);
sendMessage.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(470, 300);
}
public void actionPerformed(ActionEvent event) {
if (messageBox.getText().length() < 1) {
// do nothing
} else {
chatBox.append(messageBox.getText() + "\n");
messageBox.setText("");
}
}
}