Swing Componente zur Läufzeit ändern

Hein_nieH

Bekanntes Mitglied
Hallo Fans der Bits und Bytes,

ich benötige mal wieder externe Hilfe, da ich trotz Suche im Forum nicht weiter komme.
Ich habe einen einfachen Dialog gebaut, in welchem man einen Dateipfad manuell in ein JTextField eingeben kann.
Der Dialog soll ähnlich wie ein JFileChooser funktionieren.
Während der manuellen Eingabe soll geprüft werden, ob der Pfad existiert.
Hierzu frage ich einen mit dem JTextField verbundenen DocumentListener ab und werte bei jeder Änderung das Ergebnis aus.

Jetzt das Problem:
Im Dialog habe ich als Test zwei Labels eingebaut, welche in Abhängigkeit der Ergebnisauswertung angezeigt (setvisible) werden sollen.
Das Ändern der Labels funktioniert leider nicht.
Ich habe das ganze in eine SwingWorker-Routine eingebaut.
Im done-Ereignis (SwingWorker --- void done() ) sollen die Labels geändert werden, was leider nicht funktioniert.
Mir sind mitlerweile die Ideen ausgegangen, wie ich das Problem lösen kann.

Die Fehlermeldung sieht etwa so aus:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at gui.folderdialog.FolderByTextbox.setCheckResult(FolderByTextbox.java:192)
at gui.folderdialog.FolderByTextbox.insertUpdate(FolderByTextbox.java:152)
at java.desktop/javax.swing.text.AbstractDocument.fireInsertUpdate(AbstractDocument.java:203)
at java.desktop/javax.swing.text.AbstractDocument.handleInsertString(AbstractDocument.java:757)
at java.desktop/javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:716)
at java.desktop/javax.swing.text.PlainDocument.insertString(PlainDocument.java:131)

Bei dem Thema SwingWorker habe ich sehr wenig Erfahrung.
Vielleicht kann mir jemand helfen.

Gruss Hein_nieH


Java:
package gui.folderdialog;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.JDialog;
import javax.swing.JLabel;


public class FolderByTextbox implements ActionListener, DocumentListener
{
    //TODO Button ICON
    //TODO Panel + ICON Prüfung
    private final String buttonComandRemoveRecentPath = "BUTTON_COMAND_REMOVE_RECENT_PATH";
    private final String buttonComandSetRecentPath = "BUTTON_COMAND_SET_RECENT_PATH";
    private final String buttonComandOk = "BUTTON_COMAND_OK";
    private final String buttonComandCancel = "BUTTON_COMAND_CANCEL";
    
    
    private JDialog dialog;//Extra dialog mandatory
    private JLabel lblCheckResultOk;
    private JLabel lblCheckResultError;
    private JTextField txtfield;   
    private boolean bolOkStatus = false;
    private String strDialog = "";
    private String strDialogButton = "";
    private String strRecentPath = "";

    
    public FolderByTextbox(String strDialog, String strDialogButton, String strRecentPath)
    {
        this.strDialog = strDialog;
        this.strDialogButton = strDialogButton;
        this.strRecentPath = strRecentPath;
        initGui();
    }//Constructor
    
    
    private void initGui()
    {
        dialog = new JDialog();
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setBounds(50, 100, 1000, 150);
        dialog.setTitle(this.strDialog);
        dialog.setModal(true);//Important set Dialog modal
        Container cp = dialog.getContentPane();
        cp.setLayout( new BorderLayout() );
        
        //Panel Check Path Result
        JLabel lblCheckResultOk = new JLabel("ok");
        JLabel lblCheckResultError = new JLabel("error");
        lblCheckResultOk.setVisible(true);
        lblCheckResultError.setVisible(false);
        JPanel pnlCheckPath = new JPanel();
        pnlCheckPath.add(lblCheckResultOk);
        pnlCheckPath.add(lblCheckResultError);
        
        //Panel Textfield
        txtfield = new JTextField(100);
        txtfield.setText(this.strRecentPath);
        txtfield.getDocument().addDocumentListener(this);
        JPanel pnlTextfield = new JPanel();
        pnlTextfield.add(txtfield);
                    
        //Panel Button
        JButton btnRemoveRecentPath = new JButton("remove");
        btnRemoveRecentPath.setActionCommand(buttonComandRemoveRecentPath);
        btnRemoveRecentPath.addActionListener(this);
        //btnRemoveText.setMnemonic(KeyEvent.VK_ENTER);//Tastaturbestaetigung Alt+Enter
        
        JButton btnSetRecentPath = new JButton("insert");
        btnSetRecentPath.setActionCommand(buttonComandSetRecentPath);
        btnSetRecentPath.addActionListener(this);
        //btnRemoveText.setMnemonic(KeyEvent.VK_ENTER);//Tastaturbestaetigung Alt+Enter
                
        JButton btnOk = new JButton(this.strDialogButton);
        btnOk.setActionCommand(buttonComandOk);
        btnOk.addActionListener(this);
        btnOk.setMnemonic(KeyEvent.VK_ENTER);//Tastaturbestaetigung Alt+Enter
        
        JButton btnCancel = new JButton("Cancel");
        btnCancel.setActionCommand(buttonComandCancel);
        btnCancel.addActionListener(this);
        btnCancel.setMnemonic(KeyEvent.VK_ESCAPE);
        
        JPanel pnlButton = new JPanel();
        pnlButton.add(btnRemoveRecentPath);
        pnlButton.add(btnSetRecentPath);
        pnlButton.add(btnCancel);
        pnlButton.add(btnOk);
        
        //Result to content pane
        cp.add(pnlCheckPath,BorderLayout.NORTH);
        cp.add(pnlTextfield,BorderLayout.CENTER);
        cp.add(pnlButton,BorderLayout.SOUTH);
    }
    
    private boolean checkPathExists(String strPath)
    {
        Path pathCurr = Paths.get(strPath);
        if(Files.exists(pathCurr) && Files.isDirectory(pathCurr)) return true;
        return false;
    }//checkPathExists
    
    
    //@Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();
        if ( cmd.equals(buttonComandRemoveRecentPath) )    this.txtfield.setText(""); //remove pressed
        if ( cmd.equals(buttonComandSetRecentPath) )     this.txtfield.setText(this.strRecentPath); //set pressed
        if ( cmd.equals(buttonComandOk) )
        {
            this.bolOkStatus = true; //OK pressed
            dialog.setVisible(false); //hide Dialog
            dialog.dispose(); //Dispose Dialog to continue
            //System.out.println("Debug ok pressed: " + bolOkStatus);//DEBUG ++++++++++++++++++++++++++++++++++++++++++++++++++
        }
        if ( cmd.equals(buttonComandCancel) )             
        {   
            this.bolOkStatus = false; //Escape pressed
            dialog.setVisible(false); //hide Dialog
            dialog.dispose(); //Dispose Dialog to continue
            //System.out.println("Debug cancel pressed: " + bolOkStatus);//DEBUG ++++++++++++++++++++++++++++++++++++++++++++++++++
        }
    }//actionPerformed
    
    @Override
    public void insertUpdate(DocumentEvent e)
    {
        System.out.println("Event: Insert");
        String str = "";
        boolean bool = true;
        try
        {
            str = e.getDocument().getText( 0, e.getDocument().getLength() );
            bool = checkPathExists(str);
            setCheckResult( bool );
            System.out.println("Event: " + str);
        }
        catch (BadLocationException e1)
        {
            e1.printStackTrace();
        }

    }//insertUpdate


    @Override
    public void removeUpdate(DocumentEvent e)
    {
        //System.out.println("Event: Remove");
        String str = "";
        boolean bool = true;
        try
        {
            str = e.getDocument().getText( 0, e.getDocument().getLength() );
            bool = checkPathExists(str);
            setCheckResult( bool );
            System.out.println("Event: " + str);
        }
        catch (BadLocationException e1)
        {
            e1.printStackTrace();
        }

    }//removeUpdate


    @Override
    public void changedUpdate(DocumentEvent e)
    {
        //System.out.println("Event: Update");
    }//changedUpdate
    
    /*
    private void setCheckResult(boolean bool)
    {
        this.lblCheckResultError.setVisible(bool); // Das funktioniert nicht !!!!!!!!!!!!
        this.lblCheckResultOk.setVisible(bool); // Das funktioniert nicht !!!!!!!!!!!!!!!!!
    }
    */
    
    
    private void setCheckResult(boolean bool)
    {
        //Hier muss ein SwingWorker eingebaut werden
         new SwingWorker<Void,Void>()
         {
                @Override
                public Void doInBackground()
                {
                    return null;
                }
                
                public void done()
                {
                    FolderByTextbox.this.lblCheckResultError.setVisible(bool); // Das funktioniert nicht !!!!!!!!!!!!
                    FolderByTextbox.this.lblCheckResultOk.setVisible(bool); // Das funktioniert nicht !!!!!!!!!!!!
                }
         }.execute();
    }//setCheckResult
    
    
    public String getResult()
    {
        String strReturn="";
        if(this.bolOkStatus==true)
        {
            //Check is path + Check Path exists
            strReturn = null;
            if ( checkPathExists(this.txtfield.getText()) )
                strReturn = this.txtfield.getText();
        }
        if(this.bolOkStatus==false)
        {
            strReturn = null;
        }
        return strReturn;
    }//getResult
    
    
    public static String getFolderByTextbox(String strDialog, String strDialogButton, String strRecentPath)
    {
        FolderByTextbox selpath = new FolderByTextbox(strDialog, strDialogButton, strRecentPath);
        selpath.dialog.setVisible(true);//Important!! Call Dialog here
        return selpath.getResult();
    }//getIndexRecent

}//class
 
this.lblCheckResultError ist null, weil du in der Methode initGui diese Variable (und andere) als lokale Variablen deklarierst. Diese verdecken damit die Instanzvariablen, die du eigentlich setzen wolltest.
 
Du hast eine NullPointerException.

Du hast einen typischen Fehler gemacht (ich habe es nicht zu genau angesehen, aber das ist mir direkt ins Auge gesprungen):
  • Du erstellst Instanzvariablen: private JLabel lblCheckResultError;
  • Du initialisierst diese aber nicht, da du eine neue lokale Variable erstellst: JLabel lblCheckResultError = new JLabel("error");

Wenn Du bei der Zuweisung das JLabel weg lässt, dann hast Du keine Deklaration einer lokalen Variable mit Initialisierung mehr sondern eine Zuweisung in die Instanzvariable.
 
Hallo,

Problem ist gelöst.
Es lag tatsächlich an der deklarierung der Label-Variablen, also einen Flüchtigkeitsfehler.
Vielen Dank für die gegebenen Hinweise 🙂

Gruss Hein_nieH
 

Zurück
Oben