JPanel不添加新组件

问题描述

我正在构建一个GUI,在该GUI中我需要向某些标签动态添加到JPanel,但是由于某些原因该代码无法正常工作

public class ChatClientGUI extends javax.swing.JFrame {

    /**
     * Creates new form ChatClientGUI
     * @param server : server remoto a cui connettersi
     */
    public ChatClientGUI(ChatServerIF server) {
        initComponents();
        ...    
        messagesPanel.add(new JLabel("Mex:",SwingConstants.LEFT),BorderLayout.PAGE_START);
        messagesPanel.add(new JLabel("Mex:",BorderLayout.PAGE_START);
        // those works,infact i see 2 "Mex:" label added to the JPanel
    }
    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        try {
            System.out.println("MEX SENT"); // I see this line in the terminal
            messagesPanel.add(new JLabel("New mex sent",BorderLayout.PAGE_START);
            // this does not work,nothing is added to the JPanel
            server.sendMessage(client,username.getSelectedItem(),messageText.getText());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } 

解决方法

我需要动态添加...

将组件动态添加到面板时,需要调用:

  1. revalidate()
  2. repaint()(有时需要)

在面板上。

默认情况下,组件的大小为(0,0),因此无需绘制任何内容。

revalidate()将调用布局管理器,而repaint()确保整个面板都被重新粉刷

messagesPanel.add(new JLabel("Mex:",SwingConstants.LEFT),BorderLayout.PAGE_START);
messagesPanel.add(new JLabel("Mex:",BorderLayout.PAGE_START);

指定BorderLayout.PAGE_START似乎没有意义。您只能将单个组件添加到BorderLayout中的任何区域。如果看到多个组件,则面板必须使用其他布局(不是BorderLayout)。因此不需要此约束。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...