JTextArea 和 JScrollBar 的交互问题

Interaction problem JTextArea and JScrollBar

我遇到了一些在 Internet 上找不到的问题。我使用 JTextArea 和 JScrollBar。当填充 JTextArea window 时,它会增加。这很可能是由于滚动,因为没有它它可以在旧的 class 中工作,但是在填充时不可能写更多,所以我决定添加滚动。

Launch

Problem

旧代码:

private static final String IP_ADDRESS = "192.168.56.1";
private static final int PORT = 8000;
private static final int WIDTH = 600;
private static final int HEIGHT = 400;

private final JTextArea log = new JTextArea();
private final JTextField fieldNickName = new JTextField("Admin");
private final JTextField fieldInput = new JTextField();

private TCPConnection connection;

private ClientWindow(){
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(WIDTH, HEIGHT);
    setLocationRelativeTo(null);//-
    setAlwaysOnTop(true);//-
    log.setEditable(false);
    log.setLineWrap(true); //-
    add(log, BorderLayout.CENTER);
    fieldInput.addActionListener(this);
    add(fieldInput, BorderLayout.SOUTH);
    add(fieldNickName, BorderLayout.NORTH);
    setVisible(true);
    try {
        connection = new TCPConnection(this, IP_ADDRESS, PORT);
    } catch (IOException ex) {
        printMessage("Database exception: " + ex);
    }
}

public static void goToChat(){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new ClientWindow();
        }
    });
}

@Override
public void actionPerformed(ActionEvent e) {
    String message = fieldInput.getText();
    if (message.trim().equals("")) return;
    fieldInput.setText(null);
    connection.sendString(fieldNickName.getText() + ": " + message);
}

@Override
public void onConnectionReady(TCPConnection tcpConnection) {
    printMessage("Database ready ...");

}

@Override
public void onReceiveString(TCPConnection tcpConnection, String value) {
    printMessage(value);
}

@Override
public void onDisconnect(TCPConnection tcpConnection) {
    printMessage("Database close!");
}

@Override
public void onException(TCPConnection tcpConnection, Exception ex) {
    printMessage("Database exception: " + ex);
}

private synchronized void printMessage(final String message){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            log.append(message + "\n");
            log.setCaretPosition(log.getDocument().getLength());
        }
    });
}

}

现在:

private static final String IP_ADDRESS = "192.168.56.1";
private static final int PORT = 8000;
private static final String nickname = ClientEntrance.getNickname();
private static CopyOnWriteArrayList<String> allNickname = new CopyOnWriteArrayList<>();
private static ConcurrentHashMap<String, String> hashMap= new ConcurrentHashMap<>();
private JLabel jLabel1;
private JLabel labelForNickname;
private JLabel jLabel3;
private static JLabel jLabel4;
private JScrollBar jScrollBar1;
private JTextField jTextField1;
private JTextField fieldInput;
private JTextArea log;

private TCPConnection connection;

private ClientWindow() {
    initComponents();
    try {
        connection = new TCPConnection(this, IP_ADDRESS, PORT);
    } catch (IOException ex) {
        printMessage("Database exception: " + ex);
    }
}

private void initComponents() {
    allNickname.add(nickname);
    jLabel1 = new JLabel();
    jTextField1 = new JTextField();
    log = new JTextArea(10, 10);
    jScrollBar1 = new JScrollBar();
    fieldInput = new JTextField();
    labelForNickname = new JLabel();
    jLabel3 = new JLabel();
    jLabel4 = new JLabel();

    log.setEditable(false);
    jLabel1.setText("jLabel1");

    jTextField1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setResizable(false);
    setAlwaysOnTop(true);
    setLocationRelativeTo(null);
    log.setWrapStyleWord(true);
    log.setLineWrap(true);
    DefaultCaret caret = (DefaultCaret)log.getCaret();
    caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);

    fieldInput.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            messageActionPerformed(evt);
        }
    });

    labelForNickname.setText("Your nickname: " + nickname);

    jLabel3.setText("Users online:");
    addNewNicknames();

    String all = "";
    for (String s : allNickname) {
        all += s + "\n";
    }//FIXME: Threads!!!!
    jLabel4.setVerticalAlignment(SwingConstants.TOP);

    GroupLayout layout = new GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(GroupLayout.Alignment.LEADING)
        .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(labelForNickname, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE)
                .addComponent(fieldInput)
                .addComponent(log))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollBar1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addGap(26, 26, 26)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel4, GroupLayout.PREFERRED_SIZE, 183, GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel3, GroupLayout.PREFERRED_SIZE, 173, GroupLayout.PREFERRED_SIZE))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(labelForNickname, GroupLayout.PREFERRED_SIZE, 16, GroupLayout.PREFERRED_SIZE)
            .addGap(8, 8, 8)
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                        .addComponent(log)
                        .addComponent(jScrollBar1, GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                    .addComponent(fieldInput, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGap(19, 19, 19))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel4, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGap(31, 31, 31))))
    );

    jLabel4.getAccessibleContext().setAccessibleName("");
    pack();
}

private void jTextField2ActionPerformed(ActionEvent evt) {

}

private void jTextField1ActionPerformed(ActionEvent evt) {

}

public static void goToChat(String id, String nickname) {
    CustomizeItemsJavaFX.start(ClientWindow.class);
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ClientWindow().setVisible(true);
        }
    });
}

public void messageActionPerformed(ActionEvent e) {
    String message = fieldInput.getText();
    if (message.trim().equals("")) return;
    fieldInput.setText(null);
    connection.sendString(nickname + ": " + message);
    // Database.writeToDatabaseNewMessages(message);
}

@Override
public void onConnectionReady(TCPConnection tcpConnection) {
    printMessage("Database ready ...");
}

@Override
public void onReceiveString(TCPConnection tcpConnection, String value) {
    printMessage(value);
}

@Override
public void onDisconnect(TCPConnection tcpConnection) {
    printMessage("Database close!");
}

@Override
public void onException(TCPConnection tcpConnection, Exception ex) {
    printMessage("Database exception: " + ex);
}

private synchronized void printMessage(final String message){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            log.append(message + "\n");
            log.setCaretPosition(log.getDocument().getLength());
        }
    });
}

private synchronized static void addNewNicknames(){
    StringBuilder all = new StringBuilder();
    for (String s : allNickname) all.append(s).append("\n");
    jLabel4.setText(all.toString());
}

}

请告诉我。我找不到答案。

停止。去阅读:

还有可能 JScrollPane JavaDocs

完成后,更新您的代码以将您 JTextArea 包裹在 JScrollPane 中,之后您将获得对滚动条的适当支持