Reputation: 9663
This is my code:
private class ValueReporter implements ListSelectionListener {
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()) {
jTextField9.setText(jList2.getSelectedValue().toString());
JLabel someLabel = new JLabel("Some new Label");
jPanel7.add(someLabel);
jPanel7.revalidate();
}
}
}
The "jTextField9" get's update with the text but the panel "jPanel7" doesn't update the new label that was assigned to it.
Upvotes: 1
Views: 4747
Reputation: 36621
Here a code snippet I quickly threw together which adds labels to a JPanel
and repaint
s
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class UpdatingJPanel extends JPanel{
public UpdatingJPanel() {
Timer timer = new Timer( 1500, new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
UpdatingJPanel.this.add( new JLabel( "A label" ) );
UpdatingJPanel.this.revalidate();
UpdatingJPanel.this.repaint();
if( UpdatingJPanel.this.getComponentCount() == 0 ){
( ( Timer ) e.getSource() ).stop();
}
}
} );
timer.setRepeats( true );
timer.start();
}
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
@Override
public void run() {
JFrame testFrame = new JFrame( );
testFrame.getContentPane().add( new UpdatingJPanel() );
//not using pack() as the panel is still empty and I want avoid
//resizing when adding labels as that triggers a repaint
testFrame.setSize( 200,200 );
testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
testFrame.setVisible( true );
}
} );
}
}
Upvotes: 2