【问题标题】:JPanel not adding new componentsJPanel 未添加新组件
【发布时间】:2020-09-30 19:49:15
【问题描述】:

我正在构建一个 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();
        }
    } 

【问题讨论】:

  • 我需要动态添加 - 当您动态添加组件时,您需要在面板上调用revalidate()repaint()。默认情况下,组件的大小为 (0, 0),因此无需绘制任何内容。 revalidate() 将调用布局管理器,repaint() 确保重新绘制整个面板。
  • @camickr 好的,我已经添加了代码,现在可以使用了,谢谢,请考虑给出答案

标签: java swing user-interface label jpanel


【解决方案1】:

我需要动态添加...

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

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

在面板上。

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

revalidate() 将调用布局管理器,repaint() 确保重新绘制整个面板

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多