수다닷컴

  • 해외여행
    • 괌
    • 태국
    • 유럽
    • 일본
    • 필리핀
    • 미국
    • 중국
    • 기타여행
    • 싱가폴
  • 건강
    • 다이어트
    • 당뇨
    • 헬스
    • 건강음식
    • 건강기타
  • 컴퓨터
    • 프로그램 개발일반
    • C언어
    • 비주얼베이직
  • 결혼생활
    • 출산/육아
    • 결혼준비
    • 엄마이야기방
  • 일상생활
    • 면접
    • 취업
    • 진로선택
  • 교육
    • 교육일반
    • 아이교육
    • 토익
    • 해외연수
    • 영어
  • 취미생활
    • 음악
    • 자전거
    • 수영
    • 바이크
    • 축구
  • 기타
    • 강아지
    • 제주도여행
    • 국내여행
    • 기타일상
    • 애플
    • 휴대폰관련
  • 프로그램 개발일반
  • C언어
  • 비주얼베이직

자바 시리얼 통신 질문입니다.

키다리

2023.04.01

javacomm20-win32.zip을 사용하여 시리얼 연결은 했습니다.
위의 파일 안에 들어있는 serialdemo파일을 열어서 사용해 보니 제가 입력한 것이 그대로 출력되더군요

여기서 질문입니다. 제가 입력하는 부분을 txt 파일에서 불러와서 자동으로 보내는 것을 하고 싶은데요

어디가 시리얼로 내보내는 곳인지 알려주세요import javax.comm.*;
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;
/**
Main file for SerialDemo program. This program illustrates many of the
abilities of the javax.comm api. This file contains the GUI framework that
the program runs in.
*/
public class SerialDemo extends Frame implements ActionListener {
final int HEIGHT = 450;
final int WIDTH = 410;

private Button openButton;
private Button closeButton;
private Button breakButton;
private Panel buttonPanel;
private Panel messagePanel;
private TextArea messageAreaOut;
private TextArea messageAreaIn;
private ConfigurationPanel configurationPanel;
private SerialParameters parameters;
private SerialConnection connection;
private Properties props = null;
/**
Main method. Checks to see if the command line agrument is requesting
usage informaition (-h, -help), if it is, display a usage message and
exit, otherwise create a new codeSerialDemo/code and set it visible.
*/
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);
}
SerialDemo serialDemo = new SerialDemo(args);
serialDemo.setVisible(true);
serialDemo.repaint();
}
/**
Create new codeSerialDemo/code and initilizes it. Parses args to
find configuration file. If found, initial state it set to parameters
in configuration file.
@param args command line arguments used when program was invoked.
*/
public SerialDemo(String[] args){
super(Serial Demo);
parameters = new SerialParameters();
// Set up the GUI for the program
addWindowListener(new CloseHandler(this));
messagePanel = new Panel();
messagePanel.setLayout(new GridLayout(2, 1));
messageAreaOut = new TextArea();
messagePanel.add(messageAreaOut);
messageAreaIn = new TextArea();
messageAreaIn.setEditable(false);
messagePanel.add(messageAreaIn);
add(messagePanel, Center);
configurationPanel = new ConfigurationPanel(this);

buttonPanel = new Panel();
openButton = new Button(Open Port);
openButton.addActionListener(this);
buttonPanel.add(openButton);
closeButton = new Button(Close Port);
closeButton.addActionListener(this);
closeButton.setEnabled(false);
buttonPanel.add(closeButton);
breakButton = new Button(Send Break);
breakButton.addActionListener(this);
breakButton.setEnabled(false);
buttonPanel.add(breakButton);

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);
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);
}
/**
Sets the GUI elements on the configurationPanel.
*/
public void setConfigurationPanel() {
configurationPanel.setConfigurationPanel();
}
/**
Responds to the menu items and buttons.
*/
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
// Opens a port.
if (cmd.equals(Open Port)) {
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,
Error Opening Port!,
Error opening port,,
e2.getMessage() + .,
Select new settings, try again.);
openButton.setEnabled(true);
setNewCursorewCursor(previousCursor);
return;
}
portOpened();
setNewCursor(previousCursor);
}
// Closes a port.
if (cmd.equals(Close Port)) {
portClosed();
}
// Sends a break signal to the port.
if (cmd.equals(Send Break)) {
connection.sendBreak();
}
}
/**
Toggles the buttons to an open port state.
*/
public void portOpened() {
openButton.setEnabled(false);
closeButton.setEnabled(true);
breakButton.setEnabled(true);
}
/**
Calls closeConnection on the SerialConnection and toggles the buttons
to a closed port state.
*/
public void portClosed() {
connection.closeConnection();
openButton.setEnabled(true);
closeButton.setEnabled(false);
breakButton.setEnabled(false);
}
/**
Sets the codeCursor/code for the application.
@param c New codeCursor/code
*/
private void setNewCursor(Cursor c) {
setCursor(c);
messageAreaIn.setCursor(c);
messageAreaOut.setCursor(c);
}
/**
Cleanly shuts down the applicaion. first closes any open ports and
cleans up, then exits.
*/
private void shutdown() {
connection.closeConnection();
System.exit(1);
}
/**
Finds configuration file in arguments and creates a properties object from
that file.
*/
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) {
}
}
}
/**
Set the parameters object to the settings in the properties object.
*/
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();
}

/**
GUI element that holds the user changable elements for connection
configuration.
*/
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;
/**
Creates and initilizes the configuration panel. The initial settings
are from the parameters object.
*/
public ConfigurationPanel(Frame parent) {
this.parent = parent;
setLayout(new GridLayout(4, 4));
portNameLabel = new Label(Port Name:, Label.LEFT);
add(portNameLabel);
portChoice = new Choice();
portChoice.addItemListener(this);
add(portChoice);
listPortChoices();
portChoice.select(parameters.getPortName());

baudLabel = new Label(Baud Rate:, Label.LEFT);
add(baudLabel);
baudChoice = new Choice();
baudChoice.addItem(115200);
baudChoice.select(Integer.toString(parameters.getBaudRate()));
baudChoice.addItemListener(this);
add(baudChoice);
flowControlInLabel = new Label(Flow Control In:, Label.LEFT);
add(flowControlInLabel);
flowChoiceIn = new Choice();
flowChoiceIn.addItem(None);
flowChoiceIn.select(parameters.getFlowControlInString());
flowChoiceIn.addItemListener(this);
add(flowChoiceIn);
flowControlOutLabel = new Label(Flow Control Out:, Label.LEFT);
add(flowControlOutLabel);
flowChoiceOut = new Choice();
flowChoiceOut.addItem(None);
flowChoiceOut.select(parameters.getFlowControlOutString());
flowChoiceOut.addItemListener(this);
add(flowChoiceOut);
databitsLabel = new Label(Data Bits:, Label.LEFT);
add(databitsLabel);
databitsChoice = new Choice();
databitsChoice.addItem(8);
databitsChoice.select(parameters.getDatabitsString());
databitsChoice.addItemListener(this);
add(databitsChoice);
stopbitsLabel = new Label(Stop Bits:, Label.LEFT);
add(stopbitsLabel);
stopbitsChoice = new Choice();
stopbitsChoice.addItem(1);
stopbitsChoice.select(parameters.getStopbitsString());
stopbitsChoice.addItemListener(this);
add(stopbitsChoice);
parityLabel = new Label(Parity:, Label.LEFT);
add(parityLabel);

parityChoice = new Choice();
parityChoice.addItem(None);
parityChoice.select(parameters.getParityString());
parityChoice.addItemListener(this);
add(parityChoice);
}
/**
Sets the configuration panel to the settings in the parameters object.
*/
public void setConfigurationPanel() {
portChoice.select(parameters.getPortName());
baudChoice.select(parameters.getBaudRateString());
flowChoiceIn.select(parameters.getFlowContFlowControlInString());
flowChoiceOut.select(parameters.getFlowControlOutString());
databitsChoice.select(parameters.getDatabitsString());
stopbitsChoice.select(parameters.getStopbitsString());
parityChoice.select(parameters.getParityString());
}
/**
Sets the parameters object to the settings in the configuration panel.
*/
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());
}
/**
Sets the elements for the portChoice from the ports available on the
system. Uses an emuneration of comm ports returned by
CommPortIdentifier.getPortIdentifiers(), then sets the current
choice to a mathing element in the parameters object.
*/
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());
}
/**
Event handler for changes in the current selection of the Choices.
If a port is open the port can not be changed.
If the choice is unsupported on the platform then the user will
be notified and the settings will revert to their pre-selection
state.
*/
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, Port Open!,
Port can not,
be changed,
while a port is open.);
// 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,
Unsupported Configuration!,
Configuration Parameter unsupported,,
select new value.,
Returning to previous configuration.);
setConfigurationPanel();
}
} else {
// Since port is not open just set the parameter object.
setParameters();
}
}
}
/**
Handles closing down system. Allows application to be closed with window
close box.
*/
class CloseHandler extends WindowAdapter {
SerialDemo sd;

public CloseHandler(SerialDemo sd) {
this.sd = sd;
}
public void windowClosing(WindowEvent e) {
sd.shutdown();
}
}
}

신청하기





COMMENT

댓글을 입력해주세요. 비속어와 욕설은 삼가해주세요.

번호 제 목 글쓴이 날짜
2702317 ie6메뉴 보더문제 (3) VanilLa 2025-07-22
2702287 c++ 변수 중간값 뽑아내서 비교하는 법 헛장사 2025-07-21
2702258 AS2,0 함수에서 매개변수의 타입이 각각 다를때는? (5) 하림 2025-07-21
2702228 이 표현은 무엇인지... 몰라서요. (2) 도란도란 2025-07-21
2702197 dll 인젝션 사용법좀 알려주세요 새밝 2025-07-21
2702147 dd 안에 div들어가도 되나요? (8) 꿈 2025-07-20
2702086 [질문]세션 박스 질문입니다. (1) 하연 2025-07-20
2702057 씨언어 숙재좀 풀어주실분 ㅜ.ㅜ (3) 난슬 2025-07-19
2702000 select 사용시 label 문제 질문드립니다. 김예쁨 2025-07-19
2701970 실행파일의 이름은 어디서 변경하는지요???? 호빵녀 2025-07-19
2701856 다시 한번 대체텍스트 관련 질문입니다.. (1) 한샘가온 2025-07-18
2701803 저에게 지식의 자비를~ 베푸소서~!! (4) 봄바람 2025-07-17
2701773 메모장 파일을 읽고 출력하는 내용에 관한 질문입니다. 한국드립 2025-07-17
2701748 아이피 변경 부분이요... 날애 2025-07-17
2701665 자바스크립트 // 왜 if 두개를 쓰면 오류가 나죠? (2) 글리슨 2025-07-16
2701636 모바일웹 게시판 만들기 조언좀 부탁드려요 ㅜㅜ (2) 정훈 2025-07-16
2701610 [질문] AS3 액션으로 스테이지 사이즈를 조절할 수 있는 방법이 있을까요? (1) 앵겨쪼 2025-07-15
2701556 input text에 한글을 default 하려면.. (3) 히나 2025-07-15
2701528 apmsetup 접속이.... (5) 곰돌이 2025-07-15
2701506 암호를 *로 (6) 도도한 2025-07-14
<<  이전  1 2 3 4 5 6 7 8 9 10  다음  >>

수다닷컴 | 여러분과 함께하는 수다토크 커뮤니티 수다닷컴에 오신것을 환영합니다.
사업자등록번호 : 117-07-92748 상호 : 진달래여행사 대표자 : 명현재 서울시 강서구 방화동 890번지 푸르지오 107동 306호
copyright 2011 게시글 삭제 및 기타 문의 : clairacademy@naver.com