簡體   English   中英

在 Action Listener 中刷新 JFrame

[英]Refreshing a JFrame while in an Action Listener

下面的代碼片段在 JLabel 中設置文本,該文本被添加到 JPanel,JPanel 附加到 JFrame。無論我做什么(例如 repaint()、revalidate() 等),我都無法更新 UI文本,直到 Action Listener 完成。

我以前從未遇到過這個問題,這可能是因為我從來沒有在一次觸發 Action Listener 時發生過幾件事。 我錯過了什么?

TL;DR 為什么即使我在每個 listPanel.add() 之后放入 repaint() 之后,以下內容在完成觸發 Action Listener 之前也不會更新屏幕上的文本?

final JFrame guiFrame = new JFrame();
final JPanel listPanel = new JPanel();
listPanel.setVisible(true);
final JLabel listLbl = new JLabel("Welcome");
listPanel.add(listLbl);

startStopButton.addActionListener(new ActionListener(){@Override public void         actionPerformed(ActionEvent event){
     if(startStopButton.getText()=="Start"){
                startStopButton.setVisible(false);
                listPanel.remove(0);

     JLabel listLbl2 = new JLabel("Could not contact”);
                listPanel.add(listLbl2);

     JLabel listLbl2 = new JLabel("Success”);
                listPanel.add(listLbl2);
     }
}
guiFrame.setResizable(false);
guiFrame.add(listPanel, BorderLayout.LINE_START);
guiFrame.add(startStopButton, BorderLayout.PAGE_END);

//make sure the JFrame is visible
guiFrame.setVisible(true);

編輯:我試圖實現 SwingWorker,但在操作界面完成觸發之前界面仍然不會更新。 這是我的 SwingWorker 代碼:

@Override
protected Integer doInBackground() throws Exception{
    //Downloads and unzips the first video.  
    if(cameraBoolean==true)
        panel.add(this.downloadRecording(camera, recording));
    else
        panel.add(new JLabel("Could not contact camera "+camera.getName()));

    panel.repaint();
    jframe.repaint();
    return 1;
}

private JLabel downloadRecording(Camera camera, Recording recording){
    //does a bunch of calculations and returns a jLabel, and works correctly
}

protected void done(){
    try{
        Date currentTime = new Timestamp(Calendar.getInstance().getTime().getTime());
        JOptionPane.showMessageDialog(jframe, "Camera "+camera.getName()+" finished downloading at "+currentTime.getTime());
    }catch (Exception e){
        e.printStackTrace();
    }
}

基本上,SwingWorker(正如我實現的那樣)沒有正確更新 JPanel 和 JFrame。如果我嘗試在“done()”中進行重繪,它們也不會更新。 我錯過了什么?

此外,一旦 JOptionPane 顯示自身,就無法向我的 jframe 添加更多面板。我也不確定是什么原因造成的。

動作偵聽器正在Event Dispatch Thread上執行。 對於類似的任務,請考慮使用SwingWorker

這將允許您處理您的邏輯,而不會阻止JFrame的更新(以及重繪)。

從高層次來看,這就是我的意思:

startStopButton.addActionListener(new ActionListener(){@Override public void         actionPerformed(ActionEvent event){
     if(startStopButton.getText()=="Start"){
          // Start SwingWorker to perform whatever is supposed to happen here.
     }

如果需要,您可以在此處找到有關如何使用SwingWorker一些信息。

我嘗試使用多線程,效果很好!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM