日期:2014-05-20 浏览次数:20755 次
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import javax.swing.*; public class ChatClientFrame extends JFrame { private JTextArea textArea; private Action send; private JTextField inputField; public ChatClientFrame(String title) { super(title); textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); send = new AbstractAction("Send") { @Override public void actionPerformed(ActionEvent e) { String message = inputField.getText(); inputField.setText(""); // ... send message logic } }; inputField = new JTextField(); layoutComponents(); pack(); } private void layoutComponents() { textArea.setPreferredSize(new Dimension(500, 500)); JScrollPane center = new JScrollPane(textArea); center.setBorder(BorderFactory.createCompoundBorder( center.getBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5))); FlowLayout layout = new FlowLayout(FlowLayout.LEFT); JPanel south = new JPanel(layout); JButton button = new JButton(send); int width = center.getPreferredSize().width - button.getPreferredSize().width - (layout.getHgap() * 3); int height = button.getPreferredSize().height; inputField.setPreferredSize(new Dimension(width, height)); south.add(inputField); south.add(button); getContentPane().add(center, BorderLayout.CENTER); getContentPane().add(south, BorderLayout.SOUTH); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame f = new ChatClientFrame("Chat Client"); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }); } }