简体   繁体   English

JPanel 未添加新组件

[英]JPanel not adding new components

I'm building a GUI where i need to add dynamically to a JPanel some Label, but the code is not working for some reason:我正在构建一个 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:", SwingConstants.LEFT), 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", SwingConstants.LEFT), 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();
        }
    } 

i need to add dynamically...我需要动态添加...

When you add components dynamically to a panel you need to invoke:当您将组件动态添加到面板时,您需要调用:

  1. revalidate() and revalidate()
  2. repaint() (sometimes needed) repaint() (有时需要)

on the panel.在面板上。

By default a component has a size of (0, 0) so there is nothing to paint.默认情况下,组件的大小为 (0, 0),因此无需绘制任何内容。

The revalidate() will invoke the layout manager and the repaint() makes sure the entire panel is repainted revalidate()将调用布局管理器, repaint()确保整个面板重新绘制

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

Specifying the BorderLayout.PAGE_START doesn't seem to make sense.指定BorderLayout.PAGE_START似乎没有意义。 You can only add a single component to any area in the BorderLayout.您只能向 BorderLayout 中的任何区域添加单个组件。 Your panel must be using some other layout (not the BorderLayout) if you see multiple comonents.如果您看到多个组件,您的面板必须使用其他布局(不是 BorderLayout)。 Therefore that constraint is not needed.因此,不需要该约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM