等待打开Java中按钮事件上的com端口,而不是控制台输入的端口选择

等待打开Java中按钮事件上的com端口,而不是控制台输入的端口选择,java,swing,serial-port,event-listener,Java,Swing,Serial Port,Event Listener,下面是我用来打开com端口的代码——它等待来自控制台扫描仪的用户输入号码来打开JComboBox中列出的端口。我有一个带有按钮的事件侦听器,我想用它来打开com端口。但在用户按下按钮打开端口之前,我不确定“停止”进一步执行的最佳实践。(控制台扫描器方便地允许程序在此时等待选择)。我只希望程序只在按下后打开端口时继续。 jcombo框显示了端口,我可以使用getSelectedIndex()获取端口号 包testPackage; 导入java.awt.BorderLayout; 导入java.aw

下面是我用来打开com端口的代码——它等待来自控制台扫描仪的用户输入号码来打开JComboBox中列出的端口。我有一个带有按钮的事件侦听器,我想用它来打开com端口。但在用户按下按钮打开端口之前,我不确定“停止”进一步执行的最佳实践。(控制台扫描器方便地允许程序在此时等待选择)。我只希望程序只在按下后打开端口时继续。 jcombo框显示了端口,我可以使用getSelectedIndex()获取端口号

包testPackage;
导入java.awt.BorderLayout;
导入java.awt.itemSelective;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.event.ItemEvent;
导入java.awt.event.ItemListener;
导入java.io.PrintWriter;
导入java.util.Scanner;
导入com.fazecast.jSerialComm.*;
导入javax.swing.*;
//要测试-从选择端口对话框(Com0Com端口6)中选择选项5
//打开终端程序-选择端口Com0Com 7
//以Ascii码发送数字
公共班机{
静态串口串口;
公共静态void main(字符串[]args){
Window1 Window1=新的Window1();
JComboBox commList=新的JComboBox();
窗口1.添加(commList);
JButton bigButton=新JButton(“选择通信端口”);
窗口1.添加(大按钮);
window1.pack();
window1.setVisible(true);
JLabel标签=新的JLabel(“我的标签”);
窗口1.添加(标签、边框布局、中心);
SerialPort[]端口=SerialPort.getCommPorts();
System.out.println(“选择端口:”);
int i=1;
用于(串行端口:端口){
System.out.println(i+++:“+port.getSystemPortName());
commList.addItem(port.getSystemPortName());
}
addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
System.out.println(“单击”);
label.setText(“选定”);
System.out.println(“所选:+commList.getSelectedItem());
System.out.println(“位置:+commList.getSelectedIndex());
//SerialPort SerialPort=端口[commList.getSelectedIndex()];
打开_serial();
}
私有void open_serial(){
serialPort=端口[commList.getSelectedIndex()];
}
});     
扫描仪s=新的扫描仪(System.in);
int chosenPort=s.nextInt();
SerialPort SerialPort=端口[chosenPort-1];
//System.out.println(“所选端口:“+chosenPort”);
//System.out.println(“所选:+commList.getSelectedItem());
//System.out.println(“位置:+commList.getSelectedIndex());
if(serialPort.openPort())
System.out.println(“端口已成功打开”);
否则{
System.out.println(“无法打开端口”);
s、 close();
返回;
}   
serialPort.setBaudRate(9600);
serialPort.SetComportTimeout(serialPort.TIMEOUT\u READ\u SEMI\u BLOCKING,0,0);
扫描仪数据=新扫描仪(serialPort.getInputStream());
int值=0;
//线程=新线程();
PrintWriter输出=新的PrintWriter(serialPort.getOutputStream());
输出。打印(“Hiya”);
output.flush();
系统输出打印项次(“打印1”);
while(data.hasNextLine()){
系统输出打印项次(值);
请尝试{value=Integer.parseInt(data.nextLine());}catch(异常e){}
输出。打印(“收到”);
output.flush();
}
System.out.println(“完成”);
data.close();
s、 close();
}
};
//-这是window1类
导入java.awt.Dimension;
导入java.awt.FlowLayout;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.UIManager;
公共类Window1扩展了JFrame{
/**
* 
*/
私有静态最终长serialVersionUID=1L;
JButton-BigButton;
公共窗口1(){
超级程序员;
setLookAndFeel();
此.setPreferredSize(新尺寸(400300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo=新的FlowLayout();
setLayout(flo);
setVisible(真);
}
私有void setLookAndFeel(){
试一试{
UIManager.setLookAndFeel(
“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”
);
}捕获(异常exc){
//忽略错误
}
}
}  
但在用户按下按钮打开端口之前,我不确定“停止”进一步执行的最佳实践

在等待用户输入时,我可以想到两种主要的方法来“暂停”Swing GUI:

  • 如果程序应该完全停止,则将端口选择放入一个模型对话框中,例如JOptionPane或更通用的模态JDialog。这将阻止调用代码(主GUI)与用户交互,直到对话框不再可见(已处理),或
  • 使用一种状态设计模式类型的程序,在该程序中,在选择端口之前不响应用户输入,例如在用户可能交互的位置设置if块,检查端口选择的状态并仅处理用户交互,直到端口选择有效为止。例如,您可以有一个变量,
    SerialPort selectedPort=null
    和其他监听器中的其他监听器(与端口选择无关的监听器)的顶部有:
    if(selectedPort==null){return;}
  • 如果你想了解更多的细节,请考虑创建和发布一个有效的问题,我可以帮助它适应你的需要。请查看此宝贵工具的链接


    package testPackage;
    
    import java.awt.BorderLayout;
    import java.awt.ItemSelectable;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import com.fazecast.jSerialComm.*;
    import javax.swing.*;
    
    
    //To test - Select option 5, from select a port dialogue (Com0Com port 6)
    //open terminal program - select port Com0Com 7 
    //send numbers as Ascii
    public class Main {
    static SerialPort serialPort; 
    
        public static void main(String[] args) {
    
            Window1 window1 = new Window1();
            JComboBox<String> commList = new JComboBox<>();
            window1.add(commList);  
            JButton bigButton = new JButton("Select Comm port");
            window1.add(bigButton);
    
            window1.pack();
            window1.setVisible(true);
            JLabel label = new JLabel("My label");
            window1.add(label, BorderLayout.CENTER);
    
            SerialPort[] ports = SerialPort.getCommPorts();
    
            System.out.println("Select a port:");
            int i = 1;
            for(SerialPort port : ports) {
                System.out.println(i++ +  ": " + port.getSystemPortName());
                commList.addItem(port.getSystemPortName());
            }
    
            bigButton.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Clicked");
                    label.setText("Selected");
                       System.out.println("Selected: " + commList.getSelectedItem());
                       System.out.println("Position: " + commList.getSelectedIndex());  
                      // SerialPort serialPort = ports[commList.getSelectedIndex()];
                       open_serial();
                }
    
                private void open_serial() {
                     serialPort = ports[commList.getSelectedIndex()];
    
    
                }
    
            });     
    
            Scanner s = new Scanner(System.in);
            int chosenPort = s.nextInt();
            SerialPort serialPort = ports[chosenPort - 1];
    //      System.out.println("Chosen port : " + chosenPort);
    //        System.out.println("Selected: " + commList.getSelectedItem());
    //        System.out.println("Position: " + commList.getSelectedIndex());
            if(serialPort.openPort())
                System.out.println("Port opened successfully.");
            else {
                System.out.println("Unable to open the port.");
                s.close();
                return;
            }   
            serialPort.setBaudRate(9600);
            serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
            Scanner data = new Scanner(serialPort.getInputStream());
            int value = 0;
            //Thread thread = new Thread();
            PrintWriter output = new PrintWriter(serialPort.getOutputStream());
    
                output.print("Hiya"); 
                output.flush();
                System.out.println("printing1");
    
    
    
            while(data.hasNextLine()){
                System.out.println(value);
                try{value = Integer.parseInt(data.nextLine());}catch(Exception e){}
                output.print("Received"); 
                output.flush();
            }
            System.out.println("Done.");
            data.close();
            s.close();
    
        }
    
    };
    
    //-here is the window1 class
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.UIManager;
    
    public class Window1 extends JFrame{
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        JButton BigButton;
    
    
    public Window1() {
        super("Programmer");
        setLookAndFeel();
        this.setPreferredSize(new Dimension(400, 300));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        FlowLayout flo = new FlowLayout();
        setLayout(flo);
    
        setVisible(true);  
    }
    
    
    private void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel(
                "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
            );
        } catch (Exception exc) {
            // ignore error
        }
    }
    
    
    }  
    
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class MyPortExample extends JPanel {
        private JTextArea fromPortArea = new JTextArea(20, 40);
        private Action sendAction = new SendAction("Send");
        private Action setUpPortAction = new SetUpPortAction("Set Up Port", this);
        private JTextField toPortField = new JTextField(35);
        private JTextField portNameField = new JTextField(15);
        private JButton sendTextBtn = new JButton(sendAction);
        private PrintStream outFromPort = null;
        private MockSerialPort serialPort = null;
    
        public MyPortExample() {
            portNameField.setFocusable(false);
            JPanel topPanel = new JPanel();
            topPanel.add(new JButton(setUpPortAction));
            topPanel.add(portNameField);
    
            JScrollPane scrollPane = new JScrollPane(fromPortArea);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    
            sendAction.setEnabled(false);
            toPortField.setAction(sendAction);
            fromPortArea.setFocusable(false);
    
            JPanel sendPanel = new JPanel();
            sendPanel.add(toPortField);
            sendPanel.add(sendTextBtn);
    
            setLayout(new BorderLayout());
            add(topPanel, BorderLayout.PAGE_START);
            add(scrollPane);
            add(sendPanel, BorderLayout.PAGE_END);
        }
    
        public void setSerialPort(MockSerialPort port) {
            this.serialPort = port;
            outFromPort = (PrintStream) port.getOutputStream();
            InputStream in = port.getInputStream();
            new PortWorker(in, fromPortArea).execute();
            portNameField.setText(port.getSystemPortName());
            sendAction.setEnabled(true);
        }
    
        public MockSerialPort getSerialPort() {
            return serialPort;
        }
    
        private class PortWorker extends SwingWorker<Void, String> {
            private Scanner portScanner;
            private JTextArea textArea;
    
            public PortWorker(InputStream in, JTextArea fromPortArea) {
                this.textArea = fromPortArea;
                portScanner = new Scanner(in);
            }
    
            @Override
            protected Void doInBackground() throws Exception {
                while (portScanner.hasNextLine()) {
                    publish(portScanner.nextLine());
                }
                return null;
            }
    
            @Override
            protected void process(List<String> chunks) {
                for (String text : chunks) {
                    textArea.append(text + "\n");
                }
            }
        }
    
        private class SendAction extends AbstractAction {
            public SendAction(String name) {
                super(name);
                putValue(MNEMONIC_KEY, KeyEvent.VK_S);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                if (outFromPort != null) {
                    String text = toPortField.getText();
                    outFromPort.println(text);
                    toPortField.selectAll();
                    toPortField.requestFocusInWindow();
                } else {
                    System.err.println("No output stream available");
                }
            }
    
        }
    
        private static class SetUpPortAction extends AbstractAction {
            private MyPortExample myPortExample;
    
            public SetUpPortAction(String name, MyPortExample myPortExample) {
                super(name);
                putValue(MNEMONIC_KEY, KeyEvent.VK_P);
                this.myPortExample = myPortExample;
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
                int messageType = JOptionPane.PLAIN_MESSAGE;
                MockSerialPort port = (MockSerialPort) JOptionPane.showInputDialog(myPortExample, "Please select a port",
                        "Port Selection", messageType, null, MockSerialPort.getCommPorts(), null);
                if (port != null) {
                    myPortExample.setSerialPort(port);
                }
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    
        private static void createAndShowGui() {
            MyPortExample mainPanel = new MyPortExample();
            JFrame frame = new JFrame("MyPortExample");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        private static class MockSerialPort {
    
            public static final String TIMEOUT_READ_SEMI_BLOCKING = "timeout read semi blocking";
            private String portName;
            private int baudRate;
    
            public MockSerialPort(String name) {
                this.portName = name;
            }
    
            public String getSystemPortName() {
                return portName;
            }
    
            public OutputStream getOutputStream() {
                return System.out;
            }
    
            public InputStream getInputStream() {
                return System.in;
            }
    
            public void setComPortTimeouts(String timeoutReadSemiBlocking, int i, int j) {
                // TODO ??? not sure what goes here
            }
    
            public void setBaudRate(int baudRate) {
                this.baudRate = baudRate;
            }
    
            public boolean openPort() {
                return true;
            }
    
            @Override
            public String toString() {
                return portName;
            }
    
            public static MockSerialPort[] getCommPorts() {
                List<MockSerialPort> ports = new ArrayList<>();
                for (int i = 0; i < 20; i++) {
                    ports.add(new MockSerialPort("Port " + (i + 1)));
                }
                return ports.toArray(new MockSerialPort[] {});
            }
        }
    }