我在做一个简单的聊天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("");
}
}
}
你可能想编辑一下你的'GridBagConstraints',所以输入字段会变得更宽:http://pastebin.com/6hmscQbQ – 2013-04-22 02:37:35
@Lonenebula你能更具体一点吗?我看了一下你的pastebin,但我不确定你想要我做什么。 – hasherr 2013-04-22 10:11:46
在上面的代码中'messageBox'的witdh是0。也许一些外观仍然会显示你输入的字母,但对我来说并不是这样。用你在pastebin中设置左右“GridBagCounstraints”代码的代码来解决这个问题。 (假设你想'messageBox'来填充'southPanel'中的空白空间)。但是,这会使'messageBox'掩盖它背后的蓝色背景。 – 2013-04-22 19:12:28