lastFocusedComponent in ActionPerformed

  • Themenstarter Gelöschtes Mitglied 67058
  • Beginndatum
G

Gelöschtes Mitglied 67058

Gast
Hallo zusammen,
der Versuche von zwei Fenstern eines über "lastFocusedComponent" - mit Hilfe eines dritten Fensters - auszuwählen, ist für mich schwierig.
Im dritten "Control"-Fenster habe ich ein Texteingabefeld, dessen Wert ich jeweils in dem lastFocusedComponent-Fenster angezeigten möchte, also nur jeweils in einem der beiden anderen Fenster. Ich möchte mit dem dritten Control-Fenster steuern ich welchem der beiden anderen Fenster mein Text aus dem Eingabefeld angezeigt wird - es soll eben nicht in beiden Fenstern gleichzeitig angezeigt werden.
Zwei Probleme habe ich dabei: Zum einen schnappt sich das TextFeld des sog. "Control"-Fensters den Focus und gibt ihn nicht wieder frei, zum anderen kann ich zwar die lastFocusedComponents richtig bestimmen (außer nach "Click" ins Textfeld), aber danach nicht aussortieren was ich brauche.
Denn ob "Control"-Fenster oder Textfeld ist auch nicht wichtig, ich wollte nur zwischen Fenster1 und Fenster2 unterscheiden.
Ich habe so einiges aus dem Netz zusammenkopiert - wahrscheinlich geht es auch einfacher - aber ich poste es dennoch. Danke schon mal.

Java:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Objects;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Testing3 extends JPanel implements MouseListener, FocusListener
{
       static String tfFeld = "";   
       static JTextField textField1 = new JTextField("TextEingabe");
    
       static Component st = null;
       boolean havefocus;
       private ArrayList<PanelActionListener> listener = null;
      
       PanelActionListener panelActionListener = new PanelActionListener();
       PanelFocusListener pfl = new PanelFocusListener(panelActionListener);
       public Testing3(Component st) {
             super();
             this.tfFeld = tfFeld;
              
                // Button
                       JButton button1 = new JButton("Button");
                          
                   //TextField Eingabe
                  //    textField1 = new JTextField("TextEingabe");
                  //Ausgabe
                      JTextField ausgabeFeld = new JTextField("TextAusgabe");
                      
                      Testing2 t2 = new Testing2(st,textField1);
                      // addChangeListener(textField, e -> System.out.println("Entered text " + textField.getText()));
                      addChangeListener(textField1, e ->
                      {     
                          
                          this.tfFeld = textField1.getText();
                          setTfFeld(this.tfFeld);
                          
                          ausgabeFeld.setText(getTfFeld());
                          
                          
                          //t2.repaint();
                          
                          // t3.repaint();
                          System.out.println("Entered text " + " " + textField1.getText());

                      });
                       this.setLayout(new FlowLayout());
                       this.add(button1);
                       this.add(textField1); 
                       this.add(ausgabeFeld);
                      
                       listener = new ArrayList<PanelActionListener>();
                     this.addActionListener(panelActionListener);
                     this.addFocusListener(pfl);
                     addMouseListener(this);
                    
                     button1.addActionListener(panelActionListener);
                     button1.addFocusListener(pfl);
                        
                     textField1.addActionListener(panelActionListener);
                     textField1.addFocusListener(pfl);
                    
                     if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing3")){
                               havefocus = true;
                               System.out.println("ST in KONSTRUKTOR 3 - true: " + st.getClass().getName());
                         } else if (st != null) {
                                 havefocus=false;
                                 System.out.println("ST in KONSTRUKTOR 3 - false: " + st.getClass().getName());
                         }

                 setBackground(Color.lightGray);
                 setSize(300,200);
                 setLocation(200,100);
                 setVisible(true);
       }     
      
       public Testing3(Component st, String tfFeld) {
           this(st);
           this.tfFeld = tfFeld;
      
        // Button
               JButton button1 = new JButton("Button");
                  
           //TextField Eingabe
          //    textField1 = new JTextField("TextEingabe");
              
          //Ausgabe
              JTextField ausgabeFeld = new JTextField("TextAusgabe");
              
              Testing2 t2 = new Testing2(st,textField1);
              // addChangeListener(textField, e -> System.out.println("Entered text " + textField.getText()));
              addChangeListener(textField1, e ->
              {     
                  
                  this.tfFeld = textField1.getText();
                  setTfFeld(this.tfFeld);
                  
                  ausgabeFeld.setText(getTfFeld());
                  
                  
                  //t2.repaint();
                  
                  // t3.repaint();
                  System.out.println("Entered text " + " " + textField1.getText());

              });
              
       }


    public static String getTfFeld() {
        return tfFeld;
    }

    public static void setTfFeld(String stfFeld) {
        tfFeld = stfFeld;
    }

        
             protected void fireUpdate(ActionEvent evt) {
                for (PanelActionListener panelActionListener : listener) {
                    panelActionListener.actionPerformed(evt);
                }
            }
        
             private void addActionListener(PanelActionListener panelActionListener) {
              listener.add(panelActionListener);   
            }
            
             public void removePanelActionListener(PanelActionListener panelActionListener) {
                listener.remove(panelActionListener);
            }
            public void mouseClicked(MouseEvent evt) {
                this.st= pfl.getSt();
                System.out.println("LAST COMPONENT**************** mouseClicked in Testing3 *****************: " + st);
                  
                /**   if (st != null && st.getClass().getName().equals("FindActive4.Testing2")) {
                       havefocus = true;
                       new Testing2(st);
                      
                     } else {
                         havefocus=false;
                        // new Testing1(st);
                     }
                  // new Testing3(havefocus);
                   new Testing3(st);**/
                   fireUpdate(new ActionEvent(this, 0, "command"));
            }
            
            public void mousePressed(MouseEvent evt) {}
            public void mouseEntered(MouseEvent evt) {}
            public void mouseReleased(MouseEvent evt) {}
            public void mouseExited(MouseEvent evt) {}
        
            
            
           /**  if (!havefocus) {
                 PanelFocusListener pfl = new PanelFocusListener(new PanelActionListener());
                 String str1=pfl.getOppositeComponent(); 
                 PanelActionListener panelActionListener = new PanelActionListener();
                 String str = panelActionListener.getLastComponent(); 
                 g.drawString("in SeeFocus2 - last focused component: " + str + " " + str1, 10, 70);
             }**/
            
        
           public void focusGained(FocusEvent event)
           {
            // havefocus = true;
           //  setBackground(Color.yellow);
          //   repaint();
           }
        
           public void focusLost(FocusEvent event)
           {
            // havefocus = false;
           //  setBackground(Color.lightGray);
          //   repaint();
           }     
/**
* @param textField
* @param changeListener
*/
//Listen for changes in the text
/**
* Installs a listener to receive notification when the text of any
* {@code JTextComponent} is changed. Internally, it installs a
* {@link DocumentListener} on the text component's {@link Document},
* and a {@link PropertyChangeListener} on the text component to detect
* if the {@code Document} itself is replaced.
*
* @param text any text component, such as a {@link JTextField}
*        or {@link JTextArea}
* @param changeListener a listener to recieve {@link ChangeEvent}s
*        when the text is changed; the source object for the events
*        will be the text component
* @throws NullPointerException if either parameter is null
*/
public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
  Objects.requireNonNull(text);
  Objects.requireNonNull(changeListener);
  DocumentListener dl = new DocumentListener() {
      private int lastChange = 0, lastNotifiedChange = 0;

      @Override
      public void insertUpdate(DocumentEvent e) {
          changedUpdate(e);
      }

      @Override
      public void removeUpdate(DocumentEvent e) {
          changedUpdate(e);
      }

      @Override
      public void changedUpdate(DocumentEvent e) {
          lastChange++;
          SwingUtilities.invokeLater(() -> {
              if (lastNotifiedChange != lastChange) {
                  lastNotifiedChange = lastChange;
                  changeListener.stateChanged(new ChangeEvent(text));
              }
          });
      }
  };
  text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
      Document d1 = (Document)e.getOldValue();
      Document d2 = (Document)e.getNewValue();
      if (d1 != null) d1.removeDocumentListener(dl);
      if (d2 != null) d2.addDocumentListener(dl);
      dl.changedUpdate(null);
  });
  Document d = text.getDocument();
  if (d != null) d.addDocumentListener(dl);
}
/**** Aufruf: addChangeListener(someTextBox, e -> doSomething()); ****/
/*************************************************************************************************/
public static JFrame createDrawingFrame1(JPanel panel) {
    JFrame frame = new JFrame(Testing1.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.add(panel);
    frame.setSize(300, 200);
    frame.setLocation(300,0);
    return frame;
        }
     public static Testing1 createDrawingPanel1() {
         Testing1 wnd1 = new Testing1(st,textField1);
         wnd1.setFocusable(true);
         return wnd1;       
     }
     public static JFrame createDrawingFrame2(JPanel panel) {
         JFrame frame = new JFrame(Testing2.class.getSimpleName());
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.add(panel);
         frame.setSize(300, 200);
         frame.setLocation(600,0);
         return frame;
     }
     public static Testing2 createDrawingPanel2() {
         Testing2 wnd2 = new Testing2(st,textField1);
         wnd2.setFocusable(true);
         return wnd2;       
     }
     public static JFrame createDrawingFrame3(JPanel panel) {
      JFrame frame = new JFrame(Testing3.class.getSimpleName());
     // frame.setFocusable(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setContentPane(panel);                              //???
      frame.setSize(300,200);
      frame.setLocation(900,0);
     // frame.requestFocusInWindow();
      return frame;
     }
     public static Testing3 createDrawingPanel3() {
         Testing3 wnd3 = new Testing3(st,tfFeld);
         wnd3.setFocusable(true);   
         return wnd3;       
     }
    
        public static void main(String[] args) {
             createDrawingFrame1(createDrawingPanel1()).setVisible(true);
             createDrawingFrame2(createDrawingPanel2()).setVisible(true);
             createDrawingFrame3(createDrawingPanel3()).setVisible(true);
            }
}

class PanelFocusListener implements FocusListener {
    private PanelActionListener panelActionListener;
    boolean havefocus = false;
    static Component st= null;

    public PanelFocusListener(PanelActionListener panelActionListener) {
        this.panelActionListener = panelActionListener;
    }

    public void focusGained(FocusEvent fe) {
        this.panelActionListener.setLastFocusedComponent(fe.getOppositeComponent());//opposite
        setHavefocus(true);
        System.out.println(" gained (component)-----------"+isHavefocus()+"-------------------------------------------------------" );
        fe.getComponent().setBackground(Color.yellow);
      
        if (fe.getOppositeComponent() != null) {
            st = this.panelActionListener.getLastFocusedComponent();
            System.out.println("st (last focused component)------------ " + st.getClass().getName());
        }
      
        fe.getComponent().repaint();
      

        System.out.println("lost " +this.panelActionListener.getLastFocusedComponent());
    //  System.out.println("lost " + fe.getComponent().getClass().getName() + " / " + isHavefocus());
    }

    @Override
    public void focusLost(FocusEvent e) {
        // TODO Auto-generated method stub
        this.panelActionListener.setLastFocusedComponent(e.getComponent());
        setHavefocus(false);
        System.out.println("lost (component)----------- "+isHavefocus()+"-------------------------------------------------------" );
        e.getComponent().setBackground(Color.lightGray);
    
        if (e.getOppositeComponent() != null) {
            st = this.panelActionListener.getLastFocusedComponent();
            System.out.println("st (last focused component)------------ " + st.getClass().getName());
        }
    
        e.getComponent().repaint();

        //    this.panelActionListener.getLastFocusedComponent().repaint();
        System.out.println("gained (last focused component) " +this.panelActionListener.getLastFocusedComponent());
        //    System.out.println("gained " + e.getComponent().getClass().getName() + " / " + isHavefocus());
    }

    public boolean isHavefocus() {
        return havefocus;
    }

    public void setHavefocus(boolean havefocus) {
        this.havefocus = havefocus;
    }


    public Component getSt() {
        return st;
    }

    public void setSt(Component st) {
        this.st = st;
    }
}
/**************     Panel Action Listener    ******************************************************/ 
/**
* FocusListener welcher in einem PanelActionListener die Referenz zur zuletzt
* "fokusierten" Component ablegt.
*/

/**
* ActionListener welcher eine Referenz auf die zuletzt gewählte Component
* speichern kann. (Zusammen mit dem entsprechenden FocusListener verwenden!)
*/
class PanelActionListener implements ActionListener {
    private Component lastFocusedComponent;
    private JTextField textFeld = new JTextField();
    static Component st = null;
    static Component sti = null;
    
    public void actionPerformed(ActionEvent ae) {
        // if(this.lastFocusedComponent != null && this.lastFocusedComponent.equals(txtAnsichtIdent)) {
        //    Object obj =  ae.getSource();
        //       if (obj instanceof JTextField) {
        if(this.lastFocusedComponent != null ) {
            // das tun was du willst ;)
        
            System.out.println("ACTION PERFORMED lastFocusedComponent: " + lastFocusedComponent.getClass().getName());
            st = this.getLastFocusedComponent();
            System.out.println("ST:            " +  st.getClass().getName());   
    
            if (st.getClass().getName().equals("FindActive8_Textfield.Testing2")){   
                sti=st;
                System.out.println("STI t2: " + sti.getClass().getName());
            } else if (st.getClass().getName().equals("FindActive8_Textfield.Testing1")){
                sti= st;   
                System.out.println("STI t1: " + sti.getClass().getName());
            } else {
                //do nothing
            }
            new Testing2(st, textFeld);
            new Testing1(st,textFeld);   
        }
    }
    public void setLastFocusedComponent(Component newLastFocusedComponent) {
        this.lastFocusedComponent = newLastFocusedComponent;
    }
    public Component getLastFocusedComponent() {
        return lastFocusedComponent;
    }
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Objects;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Testing2 extends JPanel implements MouseListener, FocusListener
{
    static String tfFeld = "tfFeld";   

       private ArrayList<PanelActionListener> listener = null;
      
       PanelActionListener panelActionListener = new PanelActionListener();
       PanelFocusListener pfl = new PanelFocusListener(panelActionListener);
    
    static Component st = null;
       boolean havefocus = false;
       boolean focus = false;
            
       public Testing2(Component st, JTextField textField)
           {
             super();
          
                 havefocus= pfl.isHavefocus();
                   listener = new ArrayList<PanelActionListener>();
                   this.addActionListener(panelActionListener);
                   this.addFocusListener(pfl);
                   addMouseListener(this);
                
                   if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing2")){
                         havefocus = true;
                         System.out.println("ST in KONSTRUKTOR 2 - true: " + st.getClass().getName() + " --(Übereinstimmung)--");
                       } else if (st != null && !st.getClass().getName().equals("FindActive8_Textfield.Testing2")) {
                           havefocus=false;
                           System.out.println("ST in KONSTRUKTOR 2 - false: " + st.getClass().getName()+ " --(Keine Übereinstimmung)--");
                       }
                  
            
             setBackground(Color.lightGray);
             setSize(300,200);
             setLocation(200,100);
             /**  if (st != null){
             System.out.println("ST in TESTING2 - if not null ???????????????????"+st.getClass().getName());
         }**/
         if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing2")) {
             focus = true;
             System.out.println("ST in TESTING2???????????????????"+st.getClass().getName() + "b: " + focus);
            
             addChangeListener(textField, e ->
                  {     
                      
                          tfFeld = textField.getText();
                          System.out.println( "b: " + focus);
                      
                          this.repaint();
                          System.out.println("Entered text for Testing2" + " " + textField.getText());
                      
                  });
             System.out.println("t2: "+tfFeld);
             this.repaint();
         }
           //  setVisible(true);
           }

        public void paint(Graphics g)
        {
         super.paint(g);
        
         System.out.println("t2 in paint: "+tfFeld );
        
         g.drawString(tfFeld, 100, 100);
        
         havefocus= pfl.isHavefocus();
         System.out.println("havefocus in Testing2 " + havefocus);
         if (havefocus) {
           g.setColor(Color.black);
           g.drawString("Fokus erhalten",10,50);
         } else {
           g.setColor(Color.darkGray);
           g.drawString("Kein Fokus",10,50);
         }

        }
        
         protected void fireUpdate(ActionEvent evt)
            {
                for (PanelActionListener panelActionListener : listener) {
                    panelActionListener.actionPerformed(evt);
                }
            }
        
             private void addActionListener(PanelActionListener panelActionListener) {
              listener.add(panelActionListener);
                
            }
            
             public void removePanelActionListener(PanelActionListener panelActionListener) {
                listener.remove(panelActionListener);
            }
        
        public void mouseClicked(MouseEvent evt) {
            this.st= pfl.getSt();
            System.out.println("LAST COMPONENT**************** mouseClicked in Testing2 *****************: " + st);
              
            /**   if (st != null && st.getClass().getName().equals("FindActive4.Testing2")) {
                   havefocus = true;
                   new Testing2(st);
                  
                 } else {
                     havefocus=false;
                    // new Testing1(st);
                 }
              // new Testing3(havefocus);
               new Testing3(st);**/
               fireUpdate(new ActionEvent(this, 0, "command"));
        }
        
        public void mousePressed(MouseEvent evt) {}
        public void mouseEntered(MouseEvent evt) {}
        public void mouseReleased(MouseEvent evt) {}
        public void mouseExited(MouseEvent evt) {}
    
        
        
       /**  if (!havefocus) {
             PanelFocusListener pfl = new PanelFocusListener(new PanelActionListener());
             String str1=pfl.getOppositeComponent(); 
             PanelActionListener panelActionListener = new PanelActionListener();
             String str = panelActionListener.getLastComponent(); 
             g.drawString("in SeeFocus2 - last focused component: " + str + " " + str1, 10, 70);
         }**/
        
    
       public void focusGained(FocusEvent event)
       {
      //   havefocus = true;
       //  setBackground(Color.yellow);
      //   repaint();
       }
    
       public void focusLost(FocusEvent event)
       {
        // havefocus = false;
       //  setBackground(Color.lightGray);
      //   repaint();
       }
          
        /**
        * @param textField
        * @param changeListener
        */
        //Listen for changes in the text
        /**
        * Installs a listener to receive notification when the text of any
        * {@code JTextComponent} is changed. Internally, it installs a
        * {@link DocumentListener} on the text component's {@link Document},
        * and a {@link PropertyChangeListener} on the text component to detect
        * if the {@code Document} itself is replaced.
        *
        * @param text any text component, such as a {@link JTextField}
        *        or {@link JTextArea}
        * @param changeListener a listener to recieve {@link ChangeEvent}s
        *        when the text is changed; the source object for the events
        *        will be the text component
        * @throws NullPointerException if either parameter is null
        */
        public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
          Objects.requireNonNull(text);
          Objects.requireNonNull(changeListener);
          DocumentListener dl = new DocumentListener() {
              private int lastChange = 0, lastNotifiedChange = 0;

              @Override
              public void insertUpdate(DocumentEvent e) {
                  changedUpdate(e);
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                  changedUpdate(e);
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                  lastChange++;
                  SwingUtilities.invokeLater(() -> {
                      if (lastNotifiedChange != lastChange) {
                          lastNotifiedChange = lastChange;
                          changeListener.stateChanged(new ChangeEvent(text));
                      }
                  });
              }
          };
          text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
              Document d1 = (Document)e.getOldValue();
              Document d2 = (Document)e.getNewValue();
              if (d1 != null) d1.removeDocumentListener(dl);
              if (d2 != null) d2.addDocumentListener(dl);
              dl.changedUpdate(null);
          });
          Document d = text.getDocument();
          if (d != null) d.addDocumentListener(dl);
        }
        /**** Aufruf: addChangeListener(someTextBox, e -> doSomething()); ****/
        /*************************************************************************************************/

}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Objects;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Testing1 extends JPanel implements MouseListener, FocusListener
{
    static String tfFeld = "tfFeld";   
    static Component st;
       private ArrayList<PanelActionListener> listener = null;
      
       PanelActionListener panelActionListener = new PanelActionListener();
       PanelFocusListener pfl = new PanelFocusListener(panelActionListener);
    
    
       boolean havefocus = false;
       boolean focus = false;

    
            
       public Testing1(Component st, JTextField textField)
           {
             super();
             if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing1")) {
                 focus = true;
                 System.out.println("ST in TESTING1 "+st.getClass().getName() + " b: " + focus);
    
                 addChangeListener(textField, e ->
                      {     
                              tfFeld = textField.getText();
                              this.repaint();
                              System.out.println("Entered text - for Testing1" + " " + textField.getText());
                      });
                 System.out.println("t1: "+tfFeld);
                 this.repaint();
             }
                havefocus= pfl.isHavefocus();
                   //  addFocusListener(this);
                     listener = new ArrayList<PanelActionListener>();
                     this.addActionListener(panelActionListener);
                     this.addFocusListener(pfl);
                     addMouseListener(this);
                  
                     if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing1")){
                           havefocus = true;
                          
                           System.out.println("ST in KONSTRUKTOR 1 - true: " + st.getClass().getName());
                         } else if (st != null && !st.getClass().getName().equals("FindActive8_Textfield.Testing1")) {
                             havefocus=false;
                             System.out.println("ST in KONSTRUKTOR 1 - false: " + st.getClass().getName());
                        
                         }
             setBackground(Color.lightGray);
             setSize(300,200);
             setLocation(200,100);
           //  setVisible(true);
           }

        public void paint(Graphics g)
        {
         super.paint(g);
        
         System.out.println("t1 in paint: "+tfFeld );
        
         g.drawString(tfFeld, 100, 100);
        
         havefocus= pfl.isHavefocus();
         System.out.println("havefocus in Testing2 " + havefocus);
         if (havefocus) {
           g.setColor(Color.black);
           g.drawString("Fokus erhalten",10,50);
         } else {
           g.setColor(Color.darkGray);
           g.drawString("Kein Fokus",10,50);
         }

        }
        
         protected void fireUpdate(ActionEvent evt)
            {
                for (PanelActionListener panelActionListener : listener) {
                    panelActionListener.actionPerformed(evt);
                }
            }
        
             private void addActionListener(PanelActionListener panelActionListener) {
              listener.add(panelActionListener);
                
            }
            
             public void removePanelActionListener(PanelActionListener panelActionListener) {
                listener.remove(panelActionListener);
            }
        
        public void mouseClicked(MouseEvent evt) {
            this.st= pfl.getSt();
            System.out.println("LAST COMPONENT**************** mouseClicked in Testing1 *****************: " + st);
               fireUpdate(new ActionEvent(this, 0, "command"));
        }
        
        public void mousePressed(MouseEvent evt) {}
        public void mouseEntered(MouseEvent evt) {}
        public void mouseReleased(MouseEvent evt) {}
        public void mouseExited(MouseEvent evt) {}
    
        
        
       /**  if (!havefocus) {
             PanelFocusListener pfl = new PanelFocusListener(new PanelActionListener());
             String str1=pfl.getOppositeComponent(); 
             PanelActionListener panelActionListener = new PanelActionListener();
             String str = panelActionListener.getLastComponent(); 
             g.drawString("in SeeFocus2 - last focused component: " + str + " " + str1, 10, 70);
         }**/
        
    
       public void focusGained(FocusEvent event)
       {
        // havefocus = true;
       //  setBackground(Color.yellow);
      //   repaint();
       }
    
       public void focusLost(FocusEvent event)
       {
        // havefocus = false;
       //  setBackground(Color.lightGray);
      //   repaint();
       }
          
        /**
        * @param textField
        * @param changeListener
        */
        //Listen for changes in the text
        /**
        * Installs a listener to receive notification when the text of any
        * {@code JTextComponent} is changed. Internally, it installs a
        * {@link DocumentListener} on the text component's {@link Document},
        * and a {@link PropertyChangeListener} on the text component to detect
        * if the {@code Document} itself is replaced.
        *
        * @param text any text component, such as a {@link JTextField}
        *        or {@link JTextArea}
        * @param changeListener a listener to recieve {@link ChangeEvent}s
        *        when the text is changed; the source object for the events
        *        will be the text component
        * @throws NullPointerException if either parameter is null
        */
        public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
          Objects.requireNonNull(text);
          Objects.requireNonNull(changeListener);
          DocumentListener dl = new DocumentListener() {
              private int lastChange = 0, lastNotifiedChange = 0;

              @Override
              public void insertUpdate(DocumentEvent e) {
                  changedUpdate(e);
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                  changedUpdate(e);
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                  lastChange++;
                  SwingUtilities.invokeLater(() -> {
                      if (lastNotifiedChange != lastChange) {
                          lastNotifiedChange = lastChange;
                          changeListener.stateChanged(new ChangeEvent(text));
                      }
                  });
              }
          };
          text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
              Document d1 = (Document)e.getOldValue();
              Document d2 = (Document)e.getNewValue();
              if (d1 != null) d1.removeDocumentListener(dl);
              if (d2 != null) d2.addDocumentListener(dl);
              dl.changedUpdate(null);
          });
          Document d = text.getDocument();
          if (d != null) d.addDocumentListener(dl);
        }
        /**** Aufruf: addChangeListener(someTextBox, e -> doSomething()); ****/
        /*************************************************************************************************/

}
 
G

Gelöschtes Mitglied 67058

Gast
inzwischen habe ich bemerkt, daß es ein Problem bei Testing1 undTestin2 in der Zeile mit if (st != null) gibt. Allerdings ist mir nicht klar, wie ich das ordentlich lösen kann. Bin für jeden Tipp dankbar.
 

mihe7

Top Contributor
Den Code tue ich mir nicht an. Aber damit ich das richtig verstehe: Du hast drei Fenster. Eines davon hat ein JTextField, in das eine Eingabe erfolgen soll. Die anderen beiden haben ebenfalls ein JTextField, in das die Ausgabe erfolgen soll. Die Ausgabe soll aber in das zuletzt fokussierte Ausgabefeld erfolgen. Richtig?
 
G

Gelöschtes Mitglied 67058

Gast
Danke für die Antwort. Ja, die Ausgabe soll in das zuletzt fokussierte Fenster über paint erfolgen. Im dritten Fenster (das mit JTextFeld zur Eingabe) erfolgt die Ausgabe in ein Textfeld (Die Ausgabe in das Textfeld diente nur zum Weiterkommen mit "try and error" - nicht wichtig).
Inzwischen funktioniert die Ausgabe in das zuletzt fokussierte Fenster automatisch sobald ich etwas in das Feld tippe.

Habe trotzdem nochmals die lauffähige Version angefügt.
Mithilfe: this.lastFocusedComponent.getClass().getName().equals("FindActive8_Textfield.Testing1") oder ähnlich an verschiedenen Stellen unterscheide ich zwischen den Fenstern (dabei habe ich auf die Schnelle den PackageNamen hardcoded eingefügt).

Die neue Version habe ich gepostet, denn ich kann es so dennoch nicht verwenden. Ein weiteres Problem ist nun das Aktualisieren beim Anklicken/Verschieben, etc:
Ich weiß nicht, ob man dieses automatische Aktualisieren denn irgendwie umgehen kann? Falls jemand eine prinzipielle Antwort kennt, auch ohne Code, oder ein Beispiel mit Code aus einem anderen Kontext ... gerne posten.
Danke schon mal.

Java:
package FindActive8_Textfield;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Objects;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Testing3 extends JPanel implements MouseListener, FocusListener
{
       static String tfFeld = "";   
       static JTextField textField1 = new JTextField("TextEingabe");
    
       static Component st = null;
       boolean havefocus;
       private ArrayList<PanelActionListener> listener = null;
      
       PanelActionListener panelActionListener = new PanelActionListener();
       PanelFocusListener pfl = new PanelFocusListener(panelActionListener);
       public Testing3(Component st) {
             super();
             this.tfFeld = tfFeld;
              
                // Button
                       JButton button1 = new JButton("Button");
                          
                   //TextField Eingabe
                  //    textField1 = new JTextField("TextEingabe");
                  //Ausgabe
                      JTextField ausgabeFeld = new JTextField("TextAusgabe");
                      
                      //Testing2 t2 = new Testing2(st,textField1);
                      // addChangeListener(textField, e -> System.out.println("Entered text " + textField.getText()));
                      addChangeListener(textField1, e ->
                      {     
                          
                          this.tfFeld = textField1.getText();
                          setTfFeld(this.tfFeld);
                          
                          ausgabeFeld.setText(getTfFeld());
                          
                          
                          //t2.repaint();
                          
                          // t3.repaint();
                          System.out.println("Entered text " + " " + textField1.getText());

                      });
                       this.setLayout(new FlowLayout());
                       this.add(button1);
                       this.add(textField1);
                       this.add(ausgabeFeld);
                      
                       listener = new ArrayList<PanelActionListener>();
                     this.addActionListener(panelActionListener);
                     this.addFocusListener(pfl);
                     addMouseListener(this);
                    
                     button1.addActionListener(panelActionListener);
                     button1.addFocusListener(pfl);
                     button1.addMouseListener(this);
                        
                     textField1.addActionListener(panelActionListener);
                     textField1.addFocusListener(pfl);
                     textField1.addMouseListener(this);
                    
                    
                     if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing3")){
                               havefocus = true;
                               System.out.println("ST in KONSTRUKTOR 3 - true: " + st.getClass().getName());
                         } else if (st != null) {
                                 havefocus=false;
                                 System.out.println("ST in KONSTRUKTOR 3 - false: " + st.getClass().getName());
                         }

                 setBackground(Color.lightGray);
                 setSize(300,200);
                 setLocation(200,100);
                 setVisible(true);
       }     
      
       public Testing3(Component st, String tfFeld) {
           this(st);
           this.tfFeld = tfFeld;
      
        // Button
               JButton button1 = new JButton("Button");
                  
           //TextField Eingabe
          //    textField1 = new JTextField("TextEingabe");
              
          //Ausgabe
              JTextField ausgabeFeld = new JTextField("TextAusgabe");
              
              Testing2 t2 = new Testing2(st,textField1);
              // addChangeListener(textField, e -> System.out.println("Entered text " + textField.getText()));
              addChangeListener(textField1, e ->
              {     
                  
                  this.tfFeld = textField1.getText();
                  setTfFeld(this.tfFeld);
                  
                  ausgabeFeld.setText(getTfFeld());
                  
                  
                  //t2.repaint();
                  
                  // t3.repaint();
                  System.out.println("Entered text " + " " + textField1.getText());

              });
              
       }


    public static String getTfFeld() {
        return tfFeld;
    }

    public static void setTfFeld(String stfFeld) {
        tfFeld = stfFeld;
    }

        
             protected void fireUpdate(ActionEvent evt) {
                for (PanelActionListener panelActionListener : listener) {
                    panelActionListener.actionPerformed(evt);
                }
            }
        
             private void addActionListener(PanelActionListener panelActionListener) {
              listener.add(panelActionListener);   
            }
            
             public void removePanelActionListener(PanelActionListener panelActionListener) {
                listener.remove(panelActionListener);
            }
            public void mouseClicked(MouseEvent evt) {
                this.st= pfl.getSt();
                System.out.println("LAST COMPONENT**************** mouseClicked in Testing3 *****************: " + st);
                  
                /**   if (st != null && st.getClass().getName().equals("FindActive4.Testing2")) {
                       havefocus = true;
                       new Testing2(st);
                      
                     } else {
                         havefocus=false;
                        // new Testing1(st);
                     }
                  // new Testing3(havefocus);
                   new Testing3(st);**/
                   fireUpdate(new ActionEvent(this, 0, "command"));
            }
            
            public void mousePressed(MouseEvent evt) {}
            public void mouseEntered(MouseEvent evt) {}
            public void mouseReleased(MouseEvent evt) {}
            public void mouseExited(MouseEvent evt) {}
        
            
            
           /**  if (!havefocus) {
                 PanelFocusListener pfl = new PanelFocusListener(new PanelActionListener());
                 String str1=pfl.getOppositeComponent(); 
                 PanelActionListener panelActionListener = new PanelActionListener();
                 String str = panelActionListener.getLastComponent(); 
                 g.drawString("in SeeFocus2 - last focused component: " + str + " " + str1, 10, 70);
             }**/
            
        
           public void focusGained(FocusEvent event)
           {
            // havefocus = true;
           //  setBackground(Color.yellow);
          //   repaint();
           }
        
           public void focusLost(FocusEvent event)
           {
            // havefocus = false;
           //  setBackground(Color.lightGray);
          //   repaint();
           }     
/**
* @param textField
* @param changeListener
*/
//Listen for changes in the text
/**
* Installs a listener to receive notification when the text of any
* {@code JTextComponent} is changed. Internally, it installs a
* {@link DocumentListener} on the text component's {@link Document},
* and a {@link PropertyChangeListener} on the text component to detect
* if the {@code Document} itself is replaced.
*
* @param text any text component, such as a {@link JTextField}
*        or {@link JTextArea}
* @param changeListener a listener to recieve {@link ChangeEvent}s
*        when the text is changed; the source object for the events
*        will be the text component
* @throws NullPointerException if either parameter is null
*/
public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
  Objects.requireNonNull(text);
  Objects.requireNonNull(changeListener);
  DocumentListener dl = new DocumentListener() {
      private int lastChange = 0, lastNotifiedChange = 0;

      @Override
      public void insertUpdate(DocumentEvent e) {
          changedUpdate(e);
      }

      @Override
      public void removeUpdate(DocumentEvent e) {
          changedUpdate(e);
      }

      @Override
      public void changedUpdate(DocumentEvent e) {
          lastChange++;
          SwingUtilities.invokeLater(() -> {
              if (lastNotifiedChange != lastChange) {
                  lastNotifiedChange = lastChange;
                  changeListener.stateChanged(new ChangeEvent(text));
              }
          });
      }
  };
  text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
      Document d1 = (Document)e.getOldValue();
      Document d2 = (Document)e.getNewValue();
      if (d1 != null) d1.removeDocumentListener(dl);
      if (d2 != null) d2.addDocumentListener(dl);
      dl.changedUpdate(null);
  });
  Document d = text.getDocument();
  if (d != null) d.addDocumentListener(dl);
}
/**** Aufruf: addChangeListener(someTextBox, e -> doSomething()); ****/
/*************************************************************************************************/
public static JFrame createDrawingFrame1(JPanel panel) {
    JFrame frame = new JFrame(Testing1.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.add(panel);
    frame.setSize(300, 200);
    frame.setLocation(300,0);
    return frame;
        }
     public static Testing1 createDrawingPanel1() {
         Testing1 wnd1 = new Testing1(st,textField1);
         wnd1.setFocusable(true);
         return wnd1;       
     }
     public static JFrame createDrawingFrame2(JPanel panel) {
         JFrame frame = new JFrame(Testing2.class.getSimpleName());
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.add(panel);
         frame.setSize(300, 200);
         frame.setLocation(600,0);
         return frame;
     }
     public static Testing2 createDrawingPanel2() {
         Testing2 wnd2 = new Testing2(st,textField1);
         wnd2.setFocusable(true);
         return wnd2;       
     }
     public static JFrame createDrawingFrame3(JPanel panel) {
      JFrame frame = new JFrame(Testing3.class.getSimpleName());
     // frame.setFocusable(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setContentPane(panel);                              //???
      frame.setSize(300,200);
      frame.setLocation(900,0);
     // frame.requestFocusInWindow();
      return frame;
     }
     public static Testing3 createDrawingPanel3() {
         Testing3 wnd3 = new Testing3(st,tfFeld);
         wnd3.setFocusable(true);   
         return wnd3;       
     }
    
        public static void main(String[] args) {
             createDrawingFrame1(createDrawingPanel1()).setVisible(true);
             createDrawingFrame2(createDrawingPanel2()).setVisible(true);
             createDrawingFrame3(createDrawingPanel3()).setVisible(true);
            }
}

class PanelFocusListener implements FocusListener {
    private PanelActionListener panelActionListener;
    boolean havefocus = false;
    static Component st= null;

    public PanelFocusListener(PanelActionListener panelActionListener) {
        this.panelActionListener = panelActionListener;
    }

    public void focusGained(FocusEvent fe) {
        
        setHavefocus(true);
        System.out.println(" focusGained -----------"+isHavefocus()+ " " + fe.getComponent()+ "-----------------------------------------------" );
        fe.getComponent().setBackground(Color.yellow);
    //    setSt(fe.getComponent());
        this.panelActionListener.setLastFocusedComponent(fe.getOppositeComponent());
    }

    @Override
    public void focusLost(FocusEvent e) {
        // TODO Auto-generated method stub
        //setSt(e.getComponent());//???
        setHavefocus(false);
        System.out.println("focusLost----------- "+isHavefocus()+ " " + e.getComponent()+ "------------------------------------------------" );
        e.getComponent().setBackground(Color.lightGray);
        e.getComponent().repaint();
        
        this.panelActionListener.setLastFocusedComponent(e.getComponent());
    }

    public boolean isHavefocus() {
        return havefocus;
    }

    public void setHavefocus(boolean havefocus) {
        this.havefocus = havefocus;
    }


    public Component getSt() {
        return st;
    }

    public void setSt(Component st) {
        this.st = st;
    }
}
/**************     Panel Action Listener    ******************************************************/ 
/**
* FocusListener welcher in einem PanelActionListener die Referenz zur zuletzt
* "fokusierten" Component ablegt.
*/

/**
* ActionListener welcher eine Referenz auf die zuletzt gewählte Component
* speichern kann. (Zusammen mit dem entsprechenden FocusListener verwenden!)
*/
class PanelActionListener implements ActionListener {
    private Component lastFocusedComponent;
    private JTextField textFeld = new JTextField();
    static Component st = null;
    static String tfFeld = "";
    static boolean ueber = false;
       static boolean ueber1 = false;
    
    public void actionPerformed(ActionEvent ae) {
        //  das tun was du willst ;
        
        //    System.out.println("ACTION PERFORMED lastFocusedComponent: " + lastFocusedComponent.getClass().getName());
            st = this.getLastFocusedComponent();
            System.out.println("ACTION PERFORMED ST(getLastFocusedComponent):            " +  st.getClass().getName());   
    
            if (this.lastFocusedComponent != null && this.lastFocusedComponent.getClass().getName().equals("FindActive8_Textfield.Testing2")){   
                System.out.println("ACTION PERFORMED this.lastFocusedComponent): "+this.lastFocusedComponent);
                
                Testing2 t2= new Testing2(getLastFocusedComponent(), textFeld);
                Testing1 t1 = new Testing1(st,textFeld);
            } else if (this.lastFocusedComponent != null && this.lastFocusedComponent.getClass().getName().equals("FindActive8_Textfield.Testing1")){
                System.out.println("ACTION PERFORMED this.lastFocusedComponent): "+this.lastFocusedComponent);
                    
                Testing1 t1 = new Testing1(st,textFeld);
                Testing2 t2= new Testing2(getLastFocusedComponent(), textFeld);
            } else if (this.lastFocusedComponent != null && this.lastFocusedComponent.getClass().getName().equals("FindActive8_Textfield.Testing3")){
                System.out.println("ACTION PERFORMED this.lastFocusedComponent): "+this.lastFocusedComponent);   
            } else if(this.lastFocusedComponent != null && this.lastFocusedComponent.getClass().getName().equals("javax.swing.JTextField")) {
                System.out.println("ACTION PERFORMED this.lastFocusedComponent): "+this.lastFocusedComponent);
            } else {
                //do nothing
            }
    }
    public void setLastFocusedComponent(Component newLastFocusedComponent) {
        this.lastFocusedComponent = newLastFocusedComponent;
    }
    public Component getLastFocusedComponent() {
        return lastFocusedComponent;
    }
}

package FindActive8_Textfield;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Objects;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Testing2 extends JPanel implements MouseListener, FocusListener
{
    static String tfFeld = "tfFeld";   

       private ArrayList<PanelActionListener> listener = null;
      
       PanelActionListener panelActionListener = new PanelActionListener();
       PanelFocusListener pfl = new PanelFocusListener(panelActionListener);
    
    static Component st = new JTextField();
       boolean havefocus = false;
       static boolean ueber= false;
       static boolean ueber1 = false;

    public Testing2(Component getlfcst, JTextField textField)
           {
             super();
             this.st = getlfcst;
                 havefocus= pfl.isHavefocus();
                   listener = new ArrayList<PanelActionListener>();
                   this.addActionListener(panelActionListener);
                   this.addFocusListener(pfl);
                   addMouseListener(this);       
                
                   if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing2")){
                         havefocus = true;
                         System.out.println("ST in KONSTRUKTOR 2 - true: " + st.getClass().getName() + " --(Übereinstimmung)--");
                       ueber=true;
                      
                       } else if (st != null && !st.getClass().getName().equals("FindActive8_Textfield.Testing2")) {
                           havefocus=false;
                           System.out.println("ST in KONSTRUKTOR 2 - false: " + st.getClass().getName()+ " --(Keine Übereinstimmung)--");
                      
                       ueber=false;
                       }
                  
            
             setBackground(Color.lightGray);
             setSize(300,200);
             setLocation(200,100);
             /**  if (st != null){
             System.out.println("ST in TESTING2 - if not null ???????????????????"+st.getClass().getName());
         }**/
        //     havefocus= pfl.isHavefocus();
        // if (st != null) {
          //   if(st.equals(st))
        //     if(st.getClass().getName().equals("FindActive8_Textfield.Testing2")) {
            // if(!havefocus) {
        //     focus = true;
            // System.out.println("ST in TESTING2???????????????????"+st.getClass().getName() + "b: " + focus);
           //  st=this;
          //   st.getClass().getName().equals("FindActive8_Textfield.Testing2");
            // if (st.equals(this)){//&&
           //  this.st= st;
             System.out.println("this.st in TESTING2: "+this.st);
            
           //  if((st != null) && st.getClass().getName().equals("FindActive8_Textfield.Testing2")){   
           //      System.out.println("ST in KONSTRUKTOR 2 - true: " + st.getClass().getName() + " --(Übereinstimmung)--");
                // System.out.println("ST in KONSTRUKTOR 2 - true: " + st.getClass().getName() + " --(Übereinstimmung)--");
           //  if (st != null && (st.getClass().getName().equals("FindActive8_Textfield.Testing2") ||
           //          st.getClass().getName().equals("javax.swing.JTextField"))){       
             System.out.println("xxxxxxxxxxxxxxx: "+havefocus + ueber+ueber1);
            
             addChangeListener(textField, e ->
                  {     
                          tfFeld = textField.getText();
                          System.out.println( "b: " + havefocus);
                          if(ueber) {
                              this.repaint();
                          }
                          System.out.println("Entered text for Testing2" + " " + textField.getText());
                      
                  });
             System.out.println("t2: "+tfFeld);
            
            // this.repaint();
         }
           //  setVisible(true);
     //  }

        public void paint(Graphics g)
        {
         super.paint(g);
        
         System.out.println("t2 in paint: "+tfFeld );
        
         g.drawString(tfFeld, 100, 100);
        
         havefocus= pfl.isHavefocus();
         System.out.println("havefocus in Testing2 " + havefocus);
         if (havefocus) {
           g.setColor(Color.black);
           g.drawString("Fokus erhalten",10,50);
         } else {
           g.setColor(Color.darkGray);
           g.drawString("Kein Fokus",10,50);
         }

        }
        
         protected void fireUpdate(ActionEvent evt)
            {
                for (PanelActionListener panelActionListener : listener) {
                    panelActionListener.actionPerformed(evt);
                }
            }
        
             private void addActionListener(PanelActionListener panelActionListener) {
              listener.add(panelActionListener);
                
            }
            
             public void removePanelActionListener(PanelActionListener panelActionListener) {
                listener.remove(panelActionListener);
            }
        
        public void mouseClicked(MouseEvent evt) {
            this.st= pfl.getSt();
            System.out.println("LAST COMPONENT**************** mouseClicked in Testing2 *****************: " + st);
              
            /**   if (st != null && st.getClass().getName().equals("FindActive4.Testing2")) {
                   havefocus = true;
                   new Testing2(st);
                  
                 } else {
                     havefocus=false;
                    // new Testing1(st);
                 }
              // new Testing3(havefocus);
               new Testing3(st);**/
               fireUpdate(new ActionEvent(this, 0, "command"));
        }
        
        public void mousePressed(MouseEvent evt) {}
        public void mouseEntered(MouseEvent evt) {}
        public void mouseReleased(MouseEvent evt) {}
        public void mouseExited(MouseEvent evt) {}
    
        
        
       /**  if (!havefocus) {
             PanelFocusListener pfl = new PanelFocusListener(new PanelActionListener());
             String str1=pfl.getOppositeComponent(); 
             PanelActionListener panelActionListener = new PanelActionListener();
             String str = panelActionListener.getLastComponent(); 
             g.drawString("in SeeFocus2 - last focused component: " + str + " " + str1, 10, 70);
         }**/
        
    
       public void focusGained(FocusEvent event)
       {
      //   havefocus = true;
       //  setBackground(Color.yellow);
      //   repaint();
       }
    
       public void focusLost(FocusEvent event)
       {
        // havefocus = false;
       //  setBackground(Color.lightGray);
      //   repaint();
       }
          
        /**
        * @param textField
        * @param changeListener
        */
        //Listen for changes in the text
        /**
        * Installs a listener to receive notification when the text of any
        * {@code JTextComponent} is changed. Internally, it installs a
        * {@link DocumentListener} on the text component's {@link Document},
        * and a {@link PropertyChangeListener} on the text component to detect
        * if the {@code Document} itself is replaced.
        *
        * @param text any text component, such as a {@link JTextField}
        *        or {@link JTextArea}
        * @param changeListener a listener to recieve {@link ChangeEvent}s
        *        when the text is changed; the source object for the events
        *        will be the text component
        * @throws NullPointerException if either parameter is null
        */
        public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
          Objects.requireNonNull(text);
          Objects.requireNonNull(changeListener);
          DocumentListener dl = new DocumentListener() {
              private int lastChange = 0, lastNotifiedChange = 0;

              @Override
              public void insertUpdate(DocumentEvent e) {
                  changedUpdate(e);
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                  changedUpdate(e);
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                  lastChange++;
                  SwingUtilities.invokeLater(() -> {
                      if (lastNotifiedChange != lastChange) {
                          lastNotifiedChange = lastChange;
                          changeListener.stateChanged(new ChangeEvent(text));
                      }
                  });
              }
          };
          text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
              Document d1 = (Document)e.getOldValue();
              Document d2 = (Document)e.getNewValue();
              if (d1 != null) d1.removeDocumentListener(dl);
              if (d2 != null) d2.addDocumentListener(dl);
              dl.changedUpdate(null);
          });
          Document d = text.getDocument();
          if (d != null) d.addDocumentListener(dl);
        }
        /**** Aufruf: addChangeListener(someTextBox, e -> doSomething()); ****/
        /*************************************************************************************************/

}

package FindActive8_Textfield;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Objects;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Testing1 extends JPanel implements MouseListener, FocusListener
{
    static String tfFeld = "tfFeld";   
    static Component st;
       private ArrayList<PanelActionListener> listener = null;
      
       PanelActionListener panelActionListener = new PanelActionListener();
       PanelFocusListener pfl = new PanelFocusListener(panelActionListener);
    
    
       boolean havefocus = false;
       static boolean ueber = false;
       static boolean ueber1 = false;

    
            
       public Testing1(Component getst1, JTextField textField)
           {
             super();
             this.st=getst1;
            
             havefocus= pfl.isHavefocus();
               //  addFocusListener(this);
                 listener = new ArrayList<PanelActionListener>();
                 this.addActionListener(panelActionListener);
                 this.addFocusListener(pfl);
                 addMouseListener(this);
           //  if (st != null ) {
                //     if( st.getClass().getName().equals("FindActive8_Textfield.Testing1")) {
                
                 if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing1")){
                       havefocus = true;
                      
                       System.out.println("ST in KONSTRUKTOR 1 - true: " + st.getClass().getName() + " --(Übereinstimmung)--");
                       ueber1=true;
                      
                     } else if (st != null && !st.getClass().getName().equals("FindActive8_Textfield.Testing1")) {
                         havefocus=false;
                         System.out.println("ST in KONSTRUKTOR 1 - false: " + st.getClass().getName()+ " --(Keine Übereinstimmung)--");
                    
                     ueber1=false;
                     }
            //     System.out.println("ST in TESTING1 "+st.getClass().getName() + " b: " + focus);
                
                 System.out.println("this.st in TESTING1: "+this.st);
                 System.out.println("xxxxxxxxxxxxxxx: "+havefocus +ueber1+ ueber );
                 addChangeListener(textField, e ->
                      {     
                              tfFeld = textField.getText();
                              //if (this.st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing1")) {
                              if(ueber1) {
                                  this.repaint();
                              }
                              System.out.println("Entered text - for Testing1" + " " + textField.getText());
                      });
                 System.out.println("t1: "+tfFeld);
                
                // this.repaint();
           //  }
              
                
             setBackground(Color.lightGray);
             setSize(300,200);
             setLocation(200,100);
           //  setVisible(true);
           }

        public void paint(Graphics g)
        {
         super.paint(g);
        
         System.out.println("t1 in paint: "+tfFeld );
        
         g.drawString(tfFeld, 100, 100);
        
         havefocus= pfl.isHavefocus();
         System.out.println("havefocus in Testing2 " + havefocus);
         if (havefocus) {
           g.setColor(Color.black);
           g.drawString("Fokus erhalten",10,50);
         } else {
           g.setColor(Color.darkGray);
           g.drawString("Kein Fokus",10,50);
         }

        }
        
         protected void fireUpdate(ActionEvent evt)
            {
                for (PanelActionListener panelActionListener : listener) {
                    panelActionListener.actionPerformed(evt);
                }
            }
        
             private void addActionListener(PanelActionListener panelActionListener) {
              listener.add(panelActionListener);
                
            }
            
             public void removePanelActionListener(PanelActionListener panelActionListener) {
                listener.remove(panelActionListener);
            }
        
        public void mouseClicked(MouseEvent evt) {
            this.st= pfl.getSt();
            System.out.println("LAST COMPONENT**************** mouseClicked in Testing1 *****************: " + st);
               fireUpdate(new ActionEvent(this, 0, "command"));
        }
        
        public void mousePressed(MouseEvent evt) {}
        public void mouseEntered(MouseEvent evt) {}
        public void mouseReleased(MouseEvent evt) {}
        public void mouseExited(MouseEvent evt) {}
    
        
        
       /**  if (!havefocus) {
             PanelFocusListener pfl = new PanelFocusListener(new PanelActionListener());
             String str1=pfl.getOppositeComponent(); 
             PanelActionListener panelActionListener = new PanelActionListener();
             String str = panelActionListener.getLastComponent(); 
             g.drawString("in SeeFocus2 - last focused component: " + str + " " + str1, 10, 70);
         }**/
        
    
       public void focusGained(FocusEvent event)
       {
        // havefocus = true;
       //  setBackground(Color.yellow);
      //   repaint();
       }
    
       public void focusLost(FocusEvent event)
       {
        // havefocus = false;
       //  setBackground(Color.lightGray);
      //   repaint();
       }
          
        /**
        * @param textField
        * @param changeListener
        */
        //Listen for changes in the text
        /**
        * Installs a listener to receive notification when the text of any
        * {@code JTextComponent} is changed. Internally, it installs a
        * {@link DocumentListener} on the text component's {@link Document},
        * and a {@link PropertyChangeListener} on the text component to detect
        * if the {@code Document} itself is replaced.
        *
        * @param text any text component, such as a {@link JTextField}
        *        or {@link JTextArea}
        * @param changeListener a listener to recieve {@link ChangeEvent}s
        *        when the text is changed; the source object for the events
        *        will be the text component
        * @throws NullPointerException if either parameter is null
        */
        public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
          Objects.requireNonNull(text);
          Objects.requireNonNull(changeListener);
          DocumentListener dl = new DocumentListener() {
              private int lastChange = 0, lastNotifiedChange = 0;

              @Override
              public void insertUpdate(DocumentEvent e) {
                  changedUpdate(e);
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                  changedUpdate(e);
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                  lastChange++;
                  SwingUtilities.invokeLater(() -> {
                      if (lastNotifiedChange != lastChange) {
                          lastNotifiedChange = lastChange;
                          changeListener.stateChanged(new ChangeEvent(text));
                      }
                  });
              }
          };
          text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
              Document d1 = (Document)e.getOldValue();
              Document d2 = (Document)e.getNewValue();
              if (d1 != null) d1.removeDocumentListener(dl);
              if (d2 != null) d2.addDocumentListener(dl);
              dl.changedUpdate(null);
          });
          Document d = text.getDocument();
          if (d != null) d.addDocumentListener(dl);
        }
        /**** Aufruf: addChangeListener(someTextBox, e -> doSomething()); ****/
        /*************************************************************************************************/

}
 
G

Gelöschtes Mitglied 67058

Gast
Hallo nochmals, inzwischen funktioniert es in etwa so wie ich möchte. Habe nur eine Kleinigkeit in Testing1 und Testing2
geändert. Ein repaint beim Anklicken, Vergrößern, etc. des Fensters überschreibt mein Ausgabe jetzt nicht mehr.

@mihe7, danke fürs Antworten. Manchmal ist es schon hilfreich wenn jemand klar formuliert und sich das ansieht. Ich habe eine Woche gebraucht um das so zu bekommen - eigentlich viel zu lange für privat.

Testing2:
Java:
 this.addChangeListener(textField, e ->
                  {     
                      //if(ueber) {
                      if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing2")) {
                          tfFeld = textField.getText();
                          System.out.println( "b: " + havefocus);
                          
                              this.repaint();
                          
                          System.out.println("Entered text for Testing2" + " " + textField.getText());
                      }
                  });

Testing1:
Java:
addChangeListener(textField, e ->
                      {   
                          if (st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing1")) {
                              tfFeld = textField.getText();
                              //if (this.st != null && st.getClass().getName().equals("FindActive8_Textfield.Testing1")) {
                              //if(ueber1) {
                                  this.repaint();
                              //}
                              System.out.println("Entered text - for Testing1" + " " + textField.getText());
                          }
                      });
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
J actionperformed wird nicht aufgerufen/ repaint() AWT, Swing, JavaFX & SWT 6
B AWT actionPerformed Method funktioniert nicht AWT, Swing, JavaFX & SWT 12
K Event Handling Mit ActionPerformed und java.io arbeiten AWT, Swing, JavaFX & SWT 3
Q AWT Methodenaufruf aus actionPerformed-Methode AWT, Swing, JavaFX & SWT 4
L ActionPerformed Variable übergeben AWT, Swing, JavaFX & SWT 3
J in actionPerformed() Koordinaten ändern AWT, Swing, JavaFX & SWT 9
C actionPerformed mit mehren Aktionen AWT, Swing, JavaFX & SWT 3
C Actionperformed funktioniert nicht AWT, Swing, JavaFX & SWT 13
H actionPerformed aufteilen AWT, Swing, JavaFX & SWT 12
G if-bedinung in actionperformed AWT, Swing, JavaFX & SWT 4
P Swing actionPerformed()-Methode funktioniert nicht AWT, Swing, JavaFX & SWT 3
S AWT Java actionPerformed "Ok" Button AWT, Swing, JavaFX & SWT 4
V Labeltext ändert sich nicht in actionPerformed AWT, Swing, JavaFX & SWT 5
M actionPerformed() wird zu oft aufgerufen AWT, Swing, JavaFX & SWT 10
M Arbeiten mit actionPerformed(ActionEvent) oder Alternative AWT, Swing, JavaFX & SWT 7
M Swing Anfängerfrage: ActionPerformed AWT, Swing, JavaFX & SWT 3
B Swing NullPointerException bei actionPerformed() AWT, Swing, JavaFX & SWT 2
B actionPerformed Problem AWT, Swing, JavaFX & SWT 3
D JTree DefaultMutableTreeNode ActionPerformed AWT, Swing, JavaFX & SWT 3
J Aus ActionPerformed ein Plugin starten AWT, Swing, JavaFX & SWT 4
R paintComponent direkt bei actionPerformed aufrufen AWT, Swing, JavaFX & SWT 2
S ActionPerformed Fehler... AWT, Swing, JavaFX & SWT 9
O Button (ActionPerformed) soll neues JFrame erzeugen AWT, Swing, JavaFX & SWT 8
J Action before actionPerformed! AWT, Swing, JavaFX & SWT 4
E ActionListener/actionPerformed() feuert nicht AWT, Swing, JavaFX & SWT 2
E AWT Implementierung einer Anweisung in Methode ActionPerformed AWT, Swing, JavaFX & SWT 2
B Komisches Problem mit actionPerformed() AWT, Swing, JavaFX & SWT 2
K Swing: 2 Buttons und actionPerformed AWT, Swing, JavaFX & SWT 4
B actionPerformed reagiert nicht auf das Canvas-objekt AWT, Swing, JavaFX & SWT 11
B Objekt in "actionPerformed" erzeugen und nutzen AWT, Swing, JavaFX & SWT 3
F actionPerformed und static? AWT, Swing, JavaFX & SWT 20
B Exceptions in actionPerformed() weiterleiten AWT, Swing, JavaFX & SWT 9
S Variablenübergabe bei actionPerformed funktioniet nicht? AWT, Swing, JavaFX & SWT 12
X actionPerformed in einer Klasse Buttons AWT, Swing, JavaFX & SWT 2
T public void actionPerformed(...) ist statisch?? AWT, Swing, JavaFX & SWT 6

Ähnliche Java Themen


Oben