2017-02-27 1 views
-1

私のコードの一部に問題があります。label.setText - 別のテキストエリアで変更しますか?

label1.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae) { 
      label1.setText(-Here i want the button to open up a new "update window, and it will update the label to the text i'll provide in a seperate window); 
     } 
    }); 

追加のフォームなしなしでそれを行うにはどのような方法がありますか?私はいくつかのラベルを持っていると付け加えたいと思います。

答えて

2

1つの方法は、アップデートダイアログから結果を返すことです。これを使用して、label1のテキストを更新することができます。ここで使用することですJOptionPane

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

public class Test { 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       JFrame frame = new JFrame(); 
       frame.setMinimumSize(new Dimension(200, 85)); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new FlowLayout()); 

       JLabel label = new JLabel("Original Text"); 
       frame.add(label); 

       JButton button = new JButton("Click Me"); 
       frame.add(button); 

       // to demonstrate, a JOptionPane will be used, but this could be replaced with a custom dialog or other control 
       button.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
         int result = JOptionPane.showConfirmDialog(frame, "Should I update the label?", "Test", JOptionPane.OK_CANCEL_OPTION); 
         // if the user selected 'Ok' then updated the label text 
         if(result == JOptionPane.OK_OPTION) { 
          label.setText("Updated text"); 
         } 
        } 
       }); 
       frame.setVisible(true); 

      } 
     }); 
    } 
} 

別のアプローチからの結果の戻りに基づいてラベルテキストを更新例です更新に耳を傾け、それに応じてラベルテキストを変更することになるObserverObservable。 Observerの詳細については、この質問をご覧ください。When should we use Observer and Observable

関連する問題