1

这是我的代码:

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();
        }
    }
}

“jTextField9”获取文本更新,但面板“jPanel7”不更新分配给它的新标签。

4

1 回答 1

2

这是我快速拼凑的代码片段,它为 aJPanelrepaints添加了标签

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 );
      }
    } );

  }
}
于 2012-06-25T22:01:49.633 回答