mycomm.java

来自「基于SUN的javacomm20-win32 API中的例子SerialDemo」· Java 代码 · 共 532 行

JAVA
532
字号
package org.rien.rs;

import gnu.io.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Properties;
import java.util.Enumeration;

public class MyComm extends Frame implements ActionListener {

	final int HEIGHT = 420;
	final int WIDTH = 600;

	private MenuBar mb;
	private Menu fileMenu;
	private MenuItem openItem;
	private MenuItem saveItem;
	private MenuItem exitItem;

	private Button openButton;
	private Button closeButton;
	private Button configButton;
	private Button clrButton;
	private Button exitButton;
	private Panel buttonPanel;

	// private Panel messagePanel;
	private TextField messageAreaOut;
	private TextArea messageAreaIn;

	private ConfigurationDialog configurationDialog;
	private ConfigurationPanel configurationPanel;
	private SerialParameters parameters;
	private SerialConnection connection;

	private Properties props = null;

	public static void main(String[] args) {
		if ((args.length > 0)
				&& (args[0].equals("-h") || args[0].equals("-help"))) {
			System.out.println("usage: java SerialDemo [configuration File]");
			System.exit(1);
		}
		MyComm mycomm = new MyComm(args);
		mycomm.setVisible(true);
		mycomm.repaint();
	}

	public MyComm(String[] args) {
		super("串口通信");

		parameters = new SerialParameters();

		addWindowListener(new CloseHandler(this));

		mb = new MenuBar();

		fileMenu = new Menu("文件");

		openItem = new MenuItem("载入配置文件");
		openItem.addActionListener(this);
		fileMenu.add(openItem);

		saveItem = new MenuItem("保存配置文件");
		saveItem.addActionListener(this);
		fileMenu.add(saveItem);

		exitItem = new MenuItem("退出");
		exitItem.addActionListener(this);
		fileMenu.add(exitItem);

		mb.add(fileMenu);

		setMenuBar(mb);

		// messagePanel = new Panel();
		// messagePanel.setLayout(new GridLayout(2, 1));

		messageAreaIn = new TextArea();
		messageAreaIn.setEditable(false);
		// messagePanel.add(messageAreaIn);

		messageAreaOut = new TextField();
		messageAreaOut.setEditable(false);
		// messagePanel.add(messageAreaOut);

		add(messageAreaOut, "North");
		add(messageAreaIn, "Center");

		buttonPanel = new Panel();

		openButton = new Button("打开端口");
		openButton.addActionListener(this);
		buttonPanel.add(openButton);

		closeButton = new Button("关闭端口");
		closeButton.addActionListener(this);
		closeButton.setEnabled(false);
		buttonPanel.add(closeButton);

		configButton = new Button("设置");
		configButton.addActionListener(this);
		buttonPanel.add(configButton);

		clrButton = new Button("清屏");
		clrButton.addActionListener(this);
		buttonPanel.add(clrButton);

		exitButton = new Button("退出");
		exitButton.addActionListener(this);
		buttonPanel.add(exitButton);

		Panel southPanel = new Panel();

		GridBagLayout gridBag = new GridBagLayout();
		GridBagConstraints cons = new GridBagConstraints();

		southPanel.setLayout(gridBag);

		cons.gridwidth = GridBagConstraints.REMAINDER;
		// gridBag.setConstraints(configurationPanel, cons);
		cons.weightx = 1.0;
		// southPanel.add(configurationPanel);
		gridBag.setConstraints(buttonPanel, cons);
		southPanel.add(buttonPanel);

		add(southPanel, "South");

		configurationPanel = new ConfigurationPanel(this);

		configurationDialog = new ConfigurationDialog(this, "设置",
				configurationPanel);

		parseArgs(args);

		connection = new SerialConnection(this, parameters, messageAreaOut,
				messageAreaIn);
		setConfigurationPanel();

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

		setLocation(screenSize.width / 2 - WIDTH / 2, screenSize.height / 2
				- HEIGHT / 2);

		setSize(WIDTH, HEIGHT);
	}

	public void setConfigurationPanel() {
		configurationPanel.setConfigurationPanel();
	}

	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();

		// Loads a configuration file.
		if (cmd.equals("载入配置文件")) {
			if (connection.isOpen()) {
				AlertDialog ad = new AlertDialog(this, "端口已打开!", "当端口已打开时",
						"不能载入配置文件!", "");
			} else {
				FileDialog fd = new FileDialog(this, "载入端口配置", FileDialog.LOAD);
				fd.setVisible(true);
				String file = fd.getFile();
				if (file != null) {
					String dir = fd.getDirectory();
					File f = new File(dir + file);
					try {
						FileInputStream fis = new FileInputStream(f);
						props = new Properties();
						props.load(fis);
						fis.close();
					} catch (FileNotFoundException e1) {
						System.err.println(e1);
					} catch (IOException e2) {
						System.err.println(e2);
					}
					loadParams();
				}
			}
		}

		// Saves a configuration file.
		if (cmd.equals("保存配置文件")) {
			configurationPanel.setParameters();
			FileDialog fd = new FileDialog(this, "保存端口配置", FileDialog.SAVE);
			fd.setFile("mycomm.properties");
			fd.setVisible(true);
			String fileName = fd.getFile();
			String directory = fd.getDirectory();
			if ((fileName != null) && (directory != null)) {
				writeFile(directory + fileName);
			}
		}

		// Calls shutdown, which exits the program.
		if (cmd.equals("退出")) {
			shutdown();
		}

		if (cmd.equals("设置")) {
			configurationDialog.setVisible(true);
		}

		// Opens a port.
		if (cmd.equals("打开端口")) {
			openButton.setEnabled(false);
			Cursor previousCursor = getCursor();
			setNewCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			configurationPanel.setParameters();
			try {
				connection.openConnection();
			} catch (SerialConnectionException e2) {
				AlertDialog ad = new AlertDialog(this, "打开端口错误!", "打开端口错误,", e2
						.getMessage()
						+ ".", "请重新设置后再试。");
				openButton.setEnabled(true);
				setNewCursor(previousCursor);
				return;
			}
			portOpened();
			setNewCursor(previousCursor);
			messageAreaOut.setEditable(true);
		}

		// Closes a port.
		if (cmd.equals("关闭端口")) {
			portClosed();
			messageAreaOut.setEditable(false);
		}

		// Sends a break signal to the port.
		
		if (cmd.equals("清屏")) { 
			messageAreaIn.setText(""); 
		}
		
	}

	public void portOpened() {
		openButton.setEnabled(false);
		closeButton.setEnabled(true);
		// breakButton.setEnabled(true);
	}

	public void portClosed() {
		connection.closeConnection();
		openButton.setEnabled(true);
		closeButton.setEnabled(false);
		// breakButton.setEnabled(false);
	}

	private void setNewCursor(Cursor c) {
		setCursor(c);
		messageAreaIn.setCursor(c);
		messageAreaOut.setCursor(c);
	}

	private void writeFile(String path) {

		Properties newProps;
		FileOutputStream fileOut = null;

		newProps = new Properties();

		newProps.put("portName", parameters.getPortName());
		newProps.put("baudRate", parameters.getBaudRateString());
		newProps.put("flowControlIn", parameters.getFlowControlInString());
		newProps.put("flowControlOut", parameters.getFlowControlOutString());
		newProps.put("parity", parameters.getParityString());
		newProps.put("databits", parameters.getDatabitsString());
		newProps.put("stopbits", parameters.getStopbitsString());

		try {
			fileOut = new FileOutputStream(path);
		} catch (IOException e) {
			System.out.println("无法保存!");
		}

		try {
			newProps.store(fileOut, "MyComm poperties");
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		try {
			fileOut.close();
		} catch (IOException e) {
			System.out.println("无法保存!");
		}
	}

	private void shutdown() {
		connection.closeConnection();
		System.exit(1);
	}

	private void parseArgs(String[] args) {
		if (args.length < 1) {
			return;
		}

		File f = new File(args[0]);

		if (!f.exists()) {
			f = new File(System.getProperty("user.dir")
					+ System.getProperty("path.separator") + args[0]);
		}

		if (f.exists()) {
			try {
				FileInputStream fis = new FileInputStream(f);
				props = new Properties();
				props.load(fis);
				fis.close();
				loadParams();
			} catch (IOException e) {
			}
		}
	}

	private void loadParams() {
		parameters.setPortName(props.getProperty("portName"));
		parameters.setBaudRate(props.getProperty("baudRate"));
		parameters.setFlowControlIn(props.getProperty("flowControlIn"));
		parameters.setFlowControlOut(props.getProperty("flowControlOut"));
		parameters.setParity(props.getProperty("parity"));
		parameters.setDatabits(props.getProperty("databits"));
		parameters.setStopbits(props.getProperty("stopbits"));

		setConfigurationPanel();
	}

	class ConfigurationPanel extends Panel implements ItemListener {

		private Frame parent;

		private Label portNameLabel;
		private Choice portChoice;

		private Label baudLabel;
		private Choice baudChoice;

		private Label flowControlInLabel;
		private Choice flowChoiceIn;

		private Label flowControlOutLabel;
		private Choice flowChoiceOut;

		private Label databitsLabel;
		private Choice databitsChoice;

		private Label stopbitsLabel;
		private Choice stopbitsChoice;

		private Label parityLabel;
		private Choice parityChoice;

		public ConfigurationPanel(Frame parent) {
			this.parent = parent;

			setLayout(new GridLayout(7, 1));

			portNameLabel = new Label("端口:", Label.LEFT);
			add(portNameLabel);

			portChoice = new Choice();
			portChoice.addItemListener(this);
			add(portChoice);
			listPortChoices();
			portChoice.select(parameters.getPortName());

			baudLabel = new Label("比特率:", Label.LEFT);
			add(baudLabel);

			baudChoice = new Choice();
			baudChoice.addItem("300");
			baudChoice.addItem("2400");
			baudChoice.addItem("9600");
			baudChoice.addItem("14400");
			baudChoice.addItem("28800");
			baudChoice.addItem("38400");
			baudChoice.addItem("57600");
			baudChoice.addItem("152000");
			baudChoice.select(Integer.toString(parameters.getBaudRate()));
			baudChoice.addItemListener(this);
			add(baudChoice);

			flowControlInLabel = new Label("输入流:", Label.LEFT);
			add(flowControlInLabel);

			flowChoiceIn = new Choice();
			flowChoiceIn.addItem("None");
			flowChoiceIn.addItem("Xon/Xoff In");
			flowChoiceIn.addItem("RTS/CTS In");
			flowChoiceIn.select(parameters.getFlowControlInString());
			flowChoiceIn.addItemListener(this);
			add(flowChoiceIn);

			flowControlOutLabel = new Label("输出流:", Label.LEFT);
			add(flowControlOutLabel);

			flowChoiceOut = new Choice();
			flowChoiceOut.addItem("None");
			flowChoiceOut.addItem("Xon/Xoff Out");
			flowChoiceOut.addItem("RTS/CTS Out");
			flowChoiceOut.select(parameters.getFlowControlOutString());
			flowChoiceOut.addItemListener(this);
			add(flowChoiceOut);

			databitsLabel = new Label("位长:", Label.LEFT);
			add(databitsLabel);

			databitsChoice = new Choice();
			databitsChoice.addItem("5");
			databitsChoice.addItem("6");
			databitsChoice.addItem("7");
			databitsChoice.addItem("8");
			databitsChoice.select(parameters.getDatabitsString());
			databitsChoice.addItemListener(this);
			add(databitsChoice);

			stopbitsLabel = new Label("停止位:", Label.LEFT);
			add(stopbitsLabel);

			stopbitsChoice = new Choice();
			stopbitsChoice.addItem("1");
			stopbitsChoice.addItem("1.5");
			stopbitsChoice.addItem("2");
			stopbitsChoice.select(parameters.getStopbitsString());
			stopbitsChoice.addItemListener(this);
			add(stopbitsChoice);

			parityLabel = new Label("校验方式:", Label.LEFT);
			add(parityLabel);

			parityChoice = new Choice();
			parityChoice.addItem("None");
			parityChoice.addItem("Even");
			parityChoice.addItem("Odd");
			parityChoice.select("None");
			parityChoice.select(parameters.getParityString());
			parityChoice.addItemListener(this);
			add(parityChoice);
		}

		public void setConfigurationPanel() {
			portChoice.select(parameters.getPortName());
			baudChoice.select(parameters.getBaudRateString());
			flowChoiceIn.select(parameters.getFlowControlInString());
			flowChoiceOut.select(parameters.getFlowControlOutString());
			databitsChoice.select(parameters.getDatabitsString());
			stopbitsChoice.select(parameters.getStopbitsString());
			parityChoice.select(parameters.getParityString());
		}

		public void setParameters() {
			parameters.setPortName(portChoice.getSelectedItem());
			parameters.setBaudRate(baudChoice.getSelectedItem());
			parameters.setFlowControlIn(flowChoiceIn.getSelectedItem());
			parameters.setFlowControlOut(flowChoiceOut.getSelectedItem());
			parameters.setDatabits(databitsChoice.getSelectedItem());
			parameters.setStopbits(stopbitsChoice.getSelectedItem());
			parameters.setParity(parityChoice.getSelectedItem());
		}

		void listPortChoices() {
			CommPortIdentifier portId;

			Enumeration en = CommPortIdentifier.getPortIdentifiers();

			// iterate through the ports.
			while (en.hasMoreElements()) {
				portId = (CommPortIdentifier) en.nextElement();
				if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
					portChoice.addItem(portId.getName());
				}
			}
			portChoice.select(parameters.getPortName());
		}

		public void itemStateChanged(ItemEvent e) {
			// Check if port is open.
			if (connection.isOpen()) {
				// If port is open do not allow port to change.
				if (e.getItemSelectable() == portChoice) {
					// Alert user.
					AlertDialog ad = new AlertDialog(parent, "端口已打开!",
							"当端口已经打开时,", "端口不能改变。", "");

					// Return configurationPanel to pre-choice settings.
					setConfigurationPanel();
					return;
				}
				// Set the parameters from the choice panel.
				setParameters();
				try {
					// Attempt to change the settings on an open port.
					connection.setConnectionParameters();
				} catch (SerialConnectionException ex) {
					// If setting can not be changed, alert user, return to
					// pre-choice settings.
					AlertDialog ad = new AlertDialog(parent, "不支持的配置!",
							"配置的参数不支持,", "请选择新的值。", "返回先前的配置。");
					setConfigurationPanel();
				}
			} else {
				// Since port is not open just set the parameter object.
				setParameters();
			}
		}
	}

	class CloseHandler extends WindowAdapter {

		MyComm sd;

		public CloseHandler(MyComm sd) {
			this.sd = sd;
		}

		public void windowClosing(WindowEvent e) {
			sd.shutdown();
		}
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?