Textfeld nach ereigniss füllen

Status
Nicht offen für weitere Antworten.

Arogarth

Mitglied
Hallo,
ich hab da ma so nen problem.
Ich bekomme es nicht auf die Reihe, das Textfeld nach dem Drücken auf den Button zu füllen.
Hier der Quelltext:
Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class test {
	
	
	public static void main(String[] args) {
		JFrame f = new JFrame("Passwortgenerator");
		f.setSize(220,200);
		f.setLocation(200,300);
		f.setVisible(true);

		// Textfeld
		JTextField tf1 = new JTextField();
		tf1.setLocation(10,10);
		tf1.setSize(190,20);
		tf1.setVisible(true);
		f.add(tf1);	
		
	    ActionListener action_Start = new ActionListener()
		{
			public void actionPerformed (ActionEvent e)
			{
				
                               //----------/Funktioniert nicht----------------
				tf1.setText(generator._generator());				
				
			}
		};
		
		// Funktioniert
		tf1.setText(generator._generator());
		
		// Button Start
		JButton b1 = new JButton("Start");
		b1.setLocation(10,30);
		b1.setSize(90,25);
		b1.setVisible(true);
		b1.addActionListener(action_Start);
		f.add(b1);
		
		f.repaint();
	}
}
Danke
 
Versuchs mal so:
Code:
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 

public class test { 
	private JTextField tf1;
    
   public static void main(String[] args) { 
      new test();
   }
	   
	   public test()
	   {
		   
	   
	   JFrame f = new JFrame("Passwortgenerator"); 
      f.setSize(220,200); 
      f.setLocation(200,300); 
      f.setVisible(true); 

      // Textfeld 
      JTextField tf1 = new JTextField(); 
      tf1.setLocation(10,10); 
      tf1.setSize(190,20); 
      tf1.setVisible(true); 
      f.add(tf1);    
       
       ActionListener action_Start = new ActionListener() 
      { 
         public void actionPerformed (ActionEvent e) 
         { 
             
                               //----------/Funktioniert nicht---------------- 
            test.this.tf1.setText(generator._generator());             
             
         } 
      }; 
       
      // Funktioniert 
      tf1.setText(generator._generator()); 
       
      // Button Start 
      JButton b1 = new JButton("Start"); 
      b1.setLocation(10,30); 
      b1.setSize(90,25); 
      b1.setVisible(true); 
      b1.addActionListener(action_Start); 
      f.add(b1); 
       
      f.repaint();  //kannst du weglassen
   } 
}

Du kannst aus actionPerformed nicht auf die lokale Variable tf1 zugreifen, da du ja an dieser Stelle das Listener
Interface implementierst. Wenn aber tf1 eine globale variable ist, dann kannst du mit "Klassenname".this."globale
Variable drauf zugreifen.
 
Hab das jetzt so abgeändert:
Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Frame {
	private JTextField tf1;
	
	public static void main(String[] args) {
		new Frame();
	}
	public Frame()
	{
		JFrame f = new JFrame("Passwortgenerator");
		f.setSize(220,200);
		f.setLocation(200,300);
		f.setVisible(true);

		// Passwortfeld
		JTextField tf1 = new JTextField();
		tf1.setLocation(10,10);
		tf1.setSize(190,20);
		tf1.setVisible(true);
		f.add(tf1);
		
	    ActionListener action_Start = new ActionListener()
		{
			public void actionPerformed (ActionEvent e)
			{
				Frame.this.tf1.setText(generator._generator()); 
			}
		};
		
	    ActionListener action_Beenden = new ActionListener()
		{
			public void actionPerformed (ActionEvent e)
			{

			}
		};	
		tf1.setText(generator._generator());	
		
		// Button Start
		JButton b1 = new JButton("Start");
		b1.setLocation(10,30);
		b1.setSize(90,25);
		b1.setVisible(true);
		b1.addActionListener(action_Start);
		f.add(b1);
		
		// Button Start
		JButton b2 = new JButton("Beenden");
		b2.setLocation(110,30);
		b2.setSize(90,25);
		b2.setVisible(true);
		b2.addActionListener(action_Beenden);
		f.add(b2);
		
//		f.repaint();
	}
}
Dann bekomme ich aber folgende Fehlermeldungen in Eclipse:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Frame$1.actionPerformed(Frame.java:29)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Immer dann, wenn ich auf Start klicke.
 
Das liegt daran das dein Textfield nicht Global ist.

Außerdem sollte man nicht die komponenten auf dem Frame darstellen, sondern auf dem contentPane des Frames.


Code:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 

public class test { 
   private JTextField tf1; 
    
   public static void main(String[] args) { 
      new test(); 
   } 
   public test() 
   { 
      JFrame f = new JFrame("Passwortgenerator"); 
      f.setSize(220,200); 
      f.setLocation(200,300); 
      f.getContentPane().setLayout(new FlowLayout());

      // Passwortfeld 
      tf1 = new JTextField(); 
      tf1.setLocation(10,10); 
      tf1.setPreferredSize(new Dimension(190,20)); 
      tf1.setVisible(true); 
      f.getContentPane().add(tf1); 
      f.setVisible(true); 
       ActionListener action_Start = new ActionListener() 
      { 
         public void actionPerformed (ActionEvent e) 
         { 
            test.this.tf1.setText(generator._generator()); 
         } 
      }; 
       
       ActionListener action_Beenden = new ActionListener() 
      { 
         public void actionPerformed (ActionEvent e) 
         { 

         } 
      };    
      //tf1.setText("hallo");    
       
      // Button Start 
      JButton b1 = new JButton("Start"); 
      b1.setLocation(10,30); 
      b1.setSize(90,25); 
      b1.setVisible(true); 
      b1.addActionListener(action_Start); 
      f.getContentPane().add(b1); 
       
      // Button Start 
      JButton b2 = new JButton("Beenden"); 
      b2.setLocation(110,30); 
      b2.setSize(90,25); 
      b2.setVisible(true); 
      b2.addActionListener(action_Beenden); 
      f.getContentPane().add(b2); 
       
//      f.repaint(); 
   } 
}
 
ich habe so ein ähnliches Problem.
Ich möchte, nachdem ich auf dem Suchen Button gedrückt habe,
etwas ausgeben lassen, derzeit nur ein system.out.println zum überprüfen..//dort ist dann der Fehler, ist ziemlich weit unten...NullPointerException, aber warum??
ganz unten, sind dann Textfeld, Button etc...

ach bin neu, und versuch mich einfach mal an Java!

Code:
public class Main extends JFrame implements ActionListener, WindowListener
   
{ 
    JEditorPane pane;  
    JPanel panel;
    TextField t;
    Button s,d;
    
        
   
    public static void main(String args[] ) 
    { 
        Main f = new Main();
        f.setSize(500, 300); 
        f.setLocation(250, 200); 
        f.setResizable(false);
        f.setTitle("Hilfe");
        f.setVisible(true);
        f.show();
    
    }
      
  public Main() 
    { 
      
      Calendar cal = Calendar.getInstance();
        SimpleDateFormat formater = new SimpleDateFormat();
        
        MenuBar hauptMenue = new MenuBar(); 
        
        Menu menue1 = new Menu("Einführung"); 
        Menu menue2 = new Menu("Programmbedienung"); 
        Menu menue3 = new Menu("Installation"); 
        Menu menue4 = new Menu("Suchen");
        Menu menue5 = new Menu( formater.format(cal.getTime()) );
       
        menue1.add("Einführung");
        menue1.addSeparator(); //grenze

        menue2.add("Menu1"); 
        menue2.add("Menu2"); 
        menue2.add("Menu3"); 
        menue2.addSeparator(); //grenze
        
        menue3.add("Menu4"); 
        menue3.add("Menu5"); 
        menue3.add("Menu6");
        menue3.addSeparator();//grenze
        
        menue4.add("Suchen");      
        menue4.add("beenden"); 
        menue4.addSeparator();//grenze
        
        hauptMenue.add(menue1); 
        hauptMenue.add(menue2); 
        hauptMenue.add(menue3); 
        hauptMenue.setHelpMenu(menue4); 
        hauptMenue.add(menue5); 
        
        setMenuBar(hauptMenue);
         
        menue1.addActionListener(this);
        menue2.addActionListener(this);
        menue3.addActionListener(this);
        menue4.addActionListener(this);
        menue5.addActionListener(this);
       
        
        addWindowListener(this); 
        
       
        
        this.pane = new JEditorPane("text/html","<html><body><head></head>
<center>" +
                                    "[img]H:/java/üben/simcoat/logo.jpg[/img]" +
                                    "
<font face='Arial' size='22' Color='green'>SIMCOAT Hilfe</font>
" +
                                    "

Version: 0.1</center>


</body></html>");
        this.pane.setVisible(true);
        getContentPane().add(pane); //Logo anzeigen
        
        this.panel = new JPanel();
        this.panel.setVisible(false);
        getContentPane().add(panel); //Panel für suchen
     
        JScrollPane scrollPane = new JScrollPane(pane);
        add(scrollPane, BorderLayout.CENTER);

  }
  
    public void actionPerformed(ActionEvent evt) 
    { 
     
     if (evt.getActionCommand().equals(" Löschen "))      
     {
      t.setText(" ");
     }
     
     if (evt.getActionCommand().equals(" Suchen ")) 
      {   
      
      String inhalt = t.getText(); ------------------------>NullPointerException!!! Aber warum?????
      if (inhalt.length() == 0)  
       {
        /*Frame dia = new Frame();
        dia.setSize(200,100);
        dia.setLocation(200,150);
        dia.setTitle("Meldung");       
        dia.show();*/
        System.out.println("es steht nichts drine");    
       }
        else
        {     
        System.out.println("es steht was drine");
        }
       }
      //suchen();
      
      
       if (evt.getSource() instanceof MenuItem) 
         { 
         String menuAdd = evt.getActionCommand();
         System.out.println(menuAdd);
         
           if (menuAdd == "beenden")
             {
             System.exit(0);
             }//----------------------------------------------------------------
         
           //Einlesen Html-Seiten 
           else if(menuAdd.equals(" Menu1 "))
             {
              bauteilverarbeitung();
             }//----------------------------------------------------------------
         
           //nächste Seite
           else if(menuAdd.equals("Menu2"))
             {
              einstellung();  
              }//---------------------------------------------------------------
         
           //nächste Seite
           else if(menuAdd.equals("Menu3"))
             {
              ergebnissdarstellung();
             }//----------------------------------------------------------------
         
           //nächste Seite
           else if(menuAdd.equals("Menu4"))
             {
              vorraussetzung();
             }//----------------------------------------------------------------
         
           //nächste Seite
           else if(menuAdd.equals("Menu6"))
             {
              installation();
             }//----------------------------------------------------------------
         
            //nächste Seite
           else if(menuAdd.equals("Menu5"))
             {
             javaD();
             }//----------------------------------------------------------------
         
           else if(menuAdd.equals("Einführung"))
             {
              einfuhrung();
             }//----------------------------------------------------------------
         
           //<<<<<<Suchformular
           else if(menuAdd.equals("Suchen"))
             {   
              suchenformular();
             }//----------------------------------------------------------------
       
           else
            {
             String htmlContent = "<html><body>" + menuAdd + "<body></html>";
             //this.text.setText(htmlContent);
             this.pane.setText(htmlContent);
            }
         
        }
}

    
 
    public void windowClosing(WindowEvent evt) 
    { 
        System.exit(0); 
    } 

    public void windowOpened(WindowEvent evt){} 
    public void windowIconified(WindowEvent evt){} 
    public void windowDeiconified(WindowEvent evt){} 
    public void windowClosed(WindowEvent evt){} 
    public void windowActivated(WindowEvent evt){} 
    public void windowDeactivated(WindowEvent evt){} 

    private void bauteilverarbeitung() {
       try {
            this.panel.setVisible(false);
            this.pane.setVisible(true);
            this.pane.setPage("file:///H:/java/üben/simcoat/bauteilverarbeitung.html");
           } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void einstellung() {
        try {
            this.panel.setVisible(false);
            this.pane.setVisible(true);
            this.pane.setPage("file:///H:/java/üben/simcoat/einstellung.html");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void ergebnissdarstellung() {
        
        try {
           this.panel.setVisible(false); 
           this.pane.setVisible(true); 
           this.pane.setPage("file:///H:/java/üben/simcoat/ergebnissdarstellung.html");
             } catch (IOException ex) {
             ex.printStackTrace();
         }
    }

    private void vorraussetzung() {
        
        try {
            this.panel.setVisible(false);
            this.pane.setVisible(true);
            this.pane.setPage("file:///H:/java/üben/simcoat/vorraussetzung.html");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void installation() {
        
        try {
            this.panel.setVisible(false);
            this.pane.setVisible(true);
            this.pane.setPage("file:///H:/java/üben/simcoat/installation_java.html");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void javaD() {
        
        try {
            this.panel.setVisible(false);
            this.pane.setVisible(true);
            this.pane.setPage("file:///H:/java/üben/simcoat/install_java_3d.html");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void einfuhrung() {
        
        try {
            this.panel.setVisible(false);
            this.pane.setVisible(true);
            this.pane.setPage("file:///H:/java/üben/simcoat/Einfuhrung.html");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void suchenformular() {
        panel.setLayout(null);
        this.pane.setVisible(false);
        this.panel.setVisible(true);
       
        Button s = new Button (" Suchen ");
        s.setBounds(200,50,50,25);
        s.setForeground(Color.BLUE);
        s.setBackground(Color.WHITE);
        s.addActionListener(this);
        this.panel.add(s);
        
        Button d = new Button (" Löschen ");
        d.setBounds(250,50,50,25);
        d.setForeground(Color.ORANGE);
        d.setBackground(Color.WHITE);
        d.addActionListener(this);
        this.panel.add(d);
       
        Label l = new Label ("Search Word: ");
        l.setBounds(100,30,100,15);
        this.panel.add(l);
        
        TextField t = new TextField();
        t.setBounds(200,30,200,20);
        t.addActionListener(this);   
        this.panel.add(t);
     
    }

           

}
[/code]
 
Status
Nicht offen für weitere Antworten.

Neue Themen


Zurück
Oben