Reputation: 5
public void mouseClicked(MouseEvent e){
JLabel label = ((JLabel)e.getSource());
//searches for the label in the label arrayList
for(int i = 0; i < labels.size(); i++)
if(labels.get(i) == label){
JLabel newLabel = new JLabel();
newLabel.setIcon(label.getIcon());
newLabel.addMouseMotionListener(motionListener);
modelPanel.add(newLabel);
newLabel.setLocation(150, 160);
newLabel.setVisible(true);
modelPanel.revalidate();
modelPanel.repaint();
System.out.println("added" +modelPanel.getX()+ " " + modelPanel.getY());
System.out.println(newLabel.getX() + " " + newLabel.getY());
return;
}
}
the above code is supposed to create a new JLabel and add it to the JPanel modelPanel. the System.out.println shows the object has been added but it fails to show on the screen during runtime.
modelPanel doesn't have a layoutManager as I am building an application that allows a user to drag and drop the created labels in any part of the modelPanel.
How do I make the JLabels show on the modelPanel?
Upvotes: 0
Views: 3288
Reputation: 8348
Using a null LayoutManager
means you need to do the job of the absent LayoutManager, this includes setting both the location and size of the child Component (the latter of which is not done in your code). A very simple example which dynamically adds JLabels to a null layout JPanel:
JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setLayout(null);
final int size = 400;
javax.swing.Timer timer = new javax.swing.Timer(500, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JLabel lab = new JLabel("HERE");
lab.setLocation((int)(size * Math.random()), (int)(size * Math.random()));
lab.setSize(new Dimension(40,20));
panel.add(lab);
panel.repaint();
}
});
frame.add(panel);
frame.setSize(size, size);
frame.setVisible(true);
timer.start();
Upvotes: 4