Home > Software engineering >  Call a variable from a button action & display an error message in case of one
Call a variable from a button action & display an error message in case of one

Time:12-19

Edited:

When I click on the START button of the GUI I would like to be executed the code in his section and close when finished or print an error message if there is one like from the Console.

I am faced with 2 problems that I have problem to solve:

  • Passing the paths I get from the GUI of the other 2 action buttons to the third action.
  • Displaying the error from the GUI if there is one (if it works fine I can simple exit from the program)

Here's what I did:

import java.awt.EventQueue;
import java.awt.Font;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;

public class GuiTraduttore extends JFrame implements ActionListener {

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GuiTraduttore frame = new GuiTraduttore();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}


/**
 * Create the frame.
 */
//Dichiarazione button
private final Action action_btnNewButton_1 = new SwingAction_btnNewButton_1();
private final Action action_btnNewButton_1_2 = new SwingAction_btnNewButton_1_2();
private final Action action_btnSalvaIn = new SwingAction_btnSalvaIn();
private final Action action_btnStart = new SwingAction_btnStart();


public GuiTraduttore() {
    setIconImage(Toolkit.getDefaultToolkit().getImage(GuiTraduttore.class.getResource("/icon/6.png")));
    setTitle("Traduttore");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 629, 483);
    getContentPane().setLayout(null);
    
    JLabel lblNewLabel = new JLabel("Path Scope.xml :");
    lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
    lblNewLabel.setBounds(25, 201, 557, 26);
    getContentPane().add(lblNewLabel);
    
    JLabel lblToolchainIit = new JLabel("Location of the files: ");
    lblToolchainIit.setFont(new Font("Consolas", Font.BOLD, 22));
    lblToolchainIit.setBounds(25, 7, 577, 26);
    getContentPane().add(lblToolchainIit);
    
    JLabel lblPathBtimplementation = new JLabel("Path bt-implementation :");
    lblPathBtimplementation.setFont(new Font("Tahoma", Font.PLAIN, 18));
    lblPathBtimplementation.setBounds(25, 147, 557, 26);
    getContentPane().add(lblPathBtimplementation);
    
    JLabel lblpathDestinazione = new JLabel("Path Destination final file Scope.xml  :");
    lblpathDestinazione.setFont(new Font("Tahoma", Font.PLAIN, 18));
    lblpathDestinazione.setBounds(25, 346, 387, 26);
    getContentPane().add(lblpathDestinazione);
    
    JTextArea pathScope1 = new JTextArea();
    pathScope1.setEditable(false);
    pathScope1.setBounds(25, 228, 513, 22);
    getContentPane().add(pathScope1);
    
    JTextArea textArea_7 = new JTextArea();
    textArea_7.setEditable(false);
    textArea_7.setBounds(25, 374, 557, 22);
    getContentPane().add(textArea_7);
    
    JButton btnNewButton = new JButton("START");
    btnNewButton.setAction(action_btnStart);
    btnNewButton.setFont(new Font("Consolas", Font.PLAIN, 14));
    btnNewButton.setBounds(225, 407, 160, 26);
    getContentPane().add(btnNewButton);
    
    JButton btnNewButton_1 = new JButton("...");
    btnNewButton_1.setAction(action_btnNewButton_1);
    btnNewButton_1.setBounds(543, 173, 39, 26);
    getContentPane().add(btnNewButton_1);

    
    JButton btnNewButton_1_2 = new JButton("...");
    btnNewButton_1_2.setAction(action_btnNewButton_1_2);
    btnNewButton_1_2.setBounds(543, 227, 39, 26);
    getContentPane().add(btnNewButton_1_2);
    
    JButton btnSalvaIn = new JButton("Save to : ");
    btnSalvaIn.setAction(action_btnSalvaIn);
    btnSalvaIn.setFont(new Font("Consolas", Font.PLAIN, 14));
    btnSalvaIn.setBounds(422, 342, 160, 26);
    getContentPane().add(btnSalvaIn);
    
    JTextArea txtrInsertTheRight = new JTextArea();
    txtrInsertTheRight.setFont(new Font("Consolas", Font.PLAIN, 18));
    txtrInsertTheRight.setWrapStyleWord(true);
    txtrInsertTheRight.setLineWrap(true);
    txtrInsertTheRight.setEditable(false);
    txtrInsertTheRight.setTabSize(0);
    txtrInsertTheRight.setText("Insert the right paths of the location for the folder \"bt-implementation\" (the folder that contains all the files of the project with IIT standards files to be parsed in only one file) and the Scope.xml.");
    txtrInsertTheRight.setBounds(26, 44, 556, 92);
    getContentPane().add(txtrInsertTheRight);
    
    JTextArea txtrInsertTheRight_1 = new JTextArea();
    txtrInsertTheRight_1.setWrapStyleWord(true);
    txtrInsertTheRight_1.setText("Insert the right paths of the location where to save the final Scope.xml file and click on the start button.");
    txtrInsertTheRight_1.setTabSize(0);
    txtrInsertTheRight_1.setLineWrap(true);
    txtrInsertTheRight_1.setFont(new Font("Consolas", Font.PLAIN, 18));
    txtrInsertTheRight_1.setEditable(false);
    txtrInsertTheRight_1.setBounds(25, 261, 556, 63);
    getContentPane().add(txtrInsertTheRight_1);
    
    JTextArea pathBtImplementation = new JTextArea();
    pathBtImplementation.setText("gfbgn");
    pathBtImplementation.setEditable(false);
    pathBtImplementation.setBounds(25, 174, 513, 22);
    getContentPane().add(pathBtImplementation);
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    
}

//Action JButton btnNewButton_1
private class SwingAction_btnNewButton_1 extends AbstractAction {
    public SwingAction_btnNewButton_1() {
        putValue(NAME, "...");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }
    public void actionPerformed(ActionEvent e) {
    
            JFileChooser fileChooser1 = new JFileChooser();
            fileChooser1.setCurrentDirectory(new File("."));
            //seleziona solo cartelle
            fileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );
            //prende i file da aprire 0 / 1
            int risposta = fileChooser1.showOpenDialog(null);
            if (risposta == JFileChooser.APPROVE_OPTION) {
                String cartella = new String (fileChooser1.getSelectedFile().getAbsolutePath());
                System.out.println(cartella);
            }
        
    }
}

//JButton btnNewButton_1_2
private class SwingAction_btnNewButton_1_2 extends AbstractAction {
    public SwingAction_btnNewButton_1_2() {
        putValue(NAME, "...");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }
    public void actionPerformed(ActionEvent e) {
        
        JFileChooser fileChooser2 = new JFileChooser();
        fileChooser2.setCurrentDirectory(new File("."));
        //seleziona solo cartelle
        fileChooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );
        //prende i file da aprire 0 / 1
        int risposta = fileChooser2.showOpenDialog(null);
        if (risposta == JFileChooser.APPROVE_OPTION) {
            String scopeCartella = new String (fileChooser2.getSelectedFile().getAbsolutePath());
            System.out.println(scopeCartella);
        }
        
    }
}

//JButton btnSalvaIn
private class SwingAction_btnSalvaIn extends AbstractAction {
    public SwingAction_btnSalvaIn() {
        putValue(NAME, "Save to :");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }
    public void actionPerformed(ActionEvent e) {
        
        JFileChooser fileChooserSave = new JFileChooser();
        fileChooserSave.setCurrentDirectory(new File("."));
        //seleziona solo cartelle
        fileChooserSave.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );
        //prende i file da aprire 0 / 1
        int risposta = fileChooserSave.showSaveDialog(null);
        if (risposta == JFileChooser.APPROVE_OPTION) {
            String scopeFinal = new String (fileChooserSave.getSelectedFile().getAbsolutePath());
            System.out.println(scopeFinal);
        }
        
    }
}

//button action start


private class SwingAction_btnStart extends AbstractAction {
    public SwingAction_btnStart() {
        putValue(NAME, "START");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }
    public void actionPerformed(ActionEvent e) {
        
        //button action code where to pass the 3 paths
        // 1) cartella 2) scopeCartella 3) scopeFinal
        
    }
}
}

CodePudding user response:

What you need to do is make use of "dependency injection".

That is, you need to create some kind of "model" which can be shared amongst you Actions which provide the means to "set" the properties that they control and "get" the properties which they need.

Now, you could use multiple interfaces to further limit what each Action can do (because not all actions need access to all the functionality), but I'll leave that up to you.

Now start with one or more interfaces

public interface Model {
    public void setSourceFile(File file);
    public void setDestinationPath(File file);
    
    public File getSourceFile();
    public File getDestinationPath();
}

Maybe reduce the code duplication by providing an abstract action which fills in some of the common features...

private abstract class ModelAction extends AbstractAction {
    
    private Model model;

    public ModelAction(Model model) {
        this.model = model;
    }

    public Model getModel() {
        return model;
    }
    
}

And then fill in the required needs...

private class SwingAction_btnNewButton_1 extends ModelAction {
    
    public SwingAction_btnNewButton_1(Model model) {
        super(model);
        putValue(NAME, "...");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }

    public void actionPerformed(ActionEvent e) {

        JFileChooser fileChooser1 = new JFileChooser();
        fileChooser1.setCurrentDirectory(new File("."));
        //seleziona solo cartelle
        fileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //prende i file da aprire 0 / 1
        int risposta = fileChooser1.showOpenDialog(null);
        if (risposta == JFileChooser.APPROVE_OPTION) {
            getModel().setSourceFile(fileChooser1.getSelectedFile());
        }

    }
}

//JButton btnNewButton_1_2 private class SwingAction_btnNewButton_1_2 extends ModelAction {

    public SwingAction_btnNewButton_1_2(Model model) {
        super(model);
        putValue(NAME, "...");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }

    public void actionPerformed(ActionEvent e) {

        JFileChooser fileChooser2 = new JFileChooser();
        fileChooser2.setCurrentDirectory(new File("."));
        //seleziona solo cartelle
        fileChooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //prende i file da aprire 0 / 1
        int risposta = fileChooser2.showOpenDialog(null);
        if (risposta == JFileChooser.APPROVE_OPTION) {
            getModel().setDestinationPath(fileChooser2.getSelectedFile());
        }

    }
}

//JButton btnSalvaIn private class SwingAction_btnSalvaIn extends ModelAction {

    public SwingAction_btnSalvaIn() {
        putValue(NAME, "Save to :");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }

    public void actionPerformed(ActionEvent e) {

        JFileChooser fileChooserSave = new JFileChooser();
        fileChooserSave.setCurrentDirectory(new File("."));
        //seleziona solo cartelle
        fileChooserSave.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //prende i file da aprire 0 / 1
        int risposta = fileChooserSave.showSaveDialog(null);
        if (risposta == JFileChooser.APPROVE_OPTION) {
            getModel().setDestinationPath(fileChooserSave.getSelectedFile());
        }

    }
}

//button action start
private class SwingAction_btnStart extends ModelAction {

    public SwingAction_btnStart(Model model) {
        super(model);
        putValue(NAME, "START");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }

    public void actionPerformed(ActionEvent e) {
        File sourceFile = getModel().getSourceFile();
        File destinationPath = getModel().getDestinationPath();
        //button action code where to pass the 3 paths
        // 1) cartella 2) scopeCartella 3) scopeFinal
    }
}

nb: I can't make heads or tails of your code so I'm guessing at what each Action is doing, so you'll need to fill out those details

You may also find:

of some use

null layouts

And because they are a complete pain in the ... code. null layout are a bad idea which are going to constantly come back and byte you. Instead, take the time and effort to learn how to make use of the layout functionality available in Swing.

See Laying Out Components Within a Container for more details

  • Related