问题描述
我正在构建一个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();
}
}
解决方法
我需要动态添加...
将组件动态添加到面板时,需要调用:
-
revalidate()
和 -
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)。因此不需要此约束。