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:
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:
revalidate()
and repaint()
(sometimes needed) on the panel.
By default a component has a size of (0, 0) so there is nothing to paint.
The revalidate()
will invoke the layout manager and the repaint()
makes sure the entire panel is repainted
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. You can only add a single component to any area in the BorderLayout. Your panel must be using some other layout (not the BorderLayout) if you see multiple comonents. Therefore that constraint is not needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.