从按钮操作中调用变量并在出现错误时显示错误消息

Posted

技术标签:

【中文标题】从按钮操作中调用变量并在出现错误时显示错误消息【英文标题】:Call a variable from a button action & display an error message in case of one 【发布时间】:2022-01-21 03:06:36 【问题描述】:

编辑:

当我点击 GUI 的开始按钮时,我希望执行他部分中的代码并在完成后关闭,或者如果控制台中有类似的错误消息,则打印一条错误消息。

我面临 2 个需要解决的问题:

将从其他 2 个操作按钮的 GUI 获得的路径传递给第三个操作。 如果有错误,则从 GUI 显示错误(如果工作正常,我可以简单地退出程序)

这就是我所做的:

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
        
    


【问题讨论】:

1.请不要在链接中添加代码。如果您有相关代码,请在此处显示。 2. 我敦促您不要尝试将线性控制台程序与事件驱动的 GUI 合并。最好将 Traduttore.java 类更改为一个新类,该类可以以事件驱动方式(或线性控制台方式)使用,并且可以充当 GUI 的模型。 我最初尝试在这里发布它,但它对于***来说太长了。第一部分的代码,为了完整起见,我不知道什么可能有用,什么没有。至于在一堂课上做这一切,我已经尝试过这条路线,我仍在尝试,但我一直遇到问题。所以让这部分工作正常,我想我只是在 GUI 类中调用它而不是重做所有事情。 您可以添加更多代码,只要您添加一定数量的文字,充分解释您的代码和您的问题。确保您添加的文本有助于澄清您的代码和您的问题,而不是某些发布以绕过代码/文本预期比率的“垃圾”文本。最好创建并发布一个有效的minimal reproducible example 程序作为呈现的代码。 @AliasCartellano 如果我不需要从 GUI 获取路径,这将是一个很好的解决方法 @HovercraftFullOfEels 编辑了所有帖子,因为我即将解决第一个问题,它与我正在使用的所有库有关 【参考方案1】:

你需要做的是利用“依赖注入”。

也就是说,您需要创建某种可以在Actions 之间共享的“模型”,它提供了“设置”他们控制的属性和“获取”他们需要的属性的方法。

现在,您可以使用多个 interfaces 来进一步限制每个 Action 可以执行的操作(因为并非所有操作都需要访问所有功能),但这由您来决定。

现在从一个或多个interfaces 开始

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

也许可以通过提供abstract 操作来减少代码重复,该操作填充了一些常见功能...

private abstract class ModelAction extends AbstractAction 
    
    private Model model;

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

    public Model getModel() 
        return model;
    
    

然后填写需要的...

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 私有类 SwingAction_btnNewButton_1_2 扩展 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 私有类 SwingAction_btnSalvaIn 扩展 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:我无法对您的代码做出正面或反面,所以我猜测每个 Action 正在做什么,所以您需要填写这些详细信息

您还可以找到:

How do you dynamically compile and load external java classes? How to compile and run inside the java program how to get the output of a java program?

有些用处

null 布局

而且因为它们在...代码中是一个完全的痛苦。 null 布局是个坏主意,它会不断地回来责备你。相反,花时间和精力学习如何利用 Swing 中可用的布局功能。

详情请见Laying Out Components Within a Container

【讨论】:

以上是关于从按钮操作中调用变量并在出现错误时显示错误消息的主要内容,如果未能解决你的问题,请参考以下文章

调度一个R脚本,在Windows上出现错误时显示弹出/消息框

React 登录错误消息在第一次调用时返回未定义,然后在第二次调用时显示错误

我在颤动中的捕获错误没有按我想要的那样工作。我想在出现错误但未显示时显示错误消息

discord.py - 出现 MissingRequiredArgument 错误时显示正确的命令语法

当 Apollo GraphQL 失败并出现错误时显示 MatSnackBar 消息

日期选择器仅在聚焦时显示错误