Java 在连续输入流中使用JFrame
我正在尝试实现一个代码,该代码从我的redboard的串行端口读取,并根据读取的内容重新绘制一个圆圈。本文的最终目标是使用Robot类来实现实际的光标控制,但我首先想了解更多关于Java的知识,因此我尝试先用一些基本的图形来实现它 总结一下我的问题,我不知道如何将JFrame与静态方法中不断变化的输入一起使用 访问JAR的串行端口可在以下位置找到: Arduino基于FPGA加速度计系统,以“UpLeft”、“Up”、“直立”、“Left”、“Center”、“Right”、“downlight”、“downlight”、“downlight”的形式连续写入串行数据。然后Java程序应该抓住这个,并相应地重新绘制一个圆 我能够打开COMM3并打印从硬件接收到的正确方向,但每当我尝试应用JFrame时,我都会迷路。我已经找到了许多ActionListener教程,但是这个实现应该是连续的,不依赖于鼠标或键盘事件。因此,我不知道如何使用paintComponent()和painter()方法,因为主方法是静态的 非常感谢您抽出时间Java 在连续输入流中使用JFrame,java,swing,concurrency,arduino,actionlistener,Java,Swing,Concurrency,Arduino,Actionlistener,我正在尝试实现一个代码,该代码从我的redboard的串行端口读取,并根据读取的内容重新绘制一个圆圈。本文的最终目标是使用Robot类来实现实际的光标控制,但我首先想了解更多关于Java的知识,因此我尝试先用一些基本的图形来实现它 总结一下我的问题,我不知道如何将JFrame与静态方法中不断变化的输入一起使用 访问JAR的串行端口可在以下位置找到: Arduino基于FPGA加速度计系统,以“UpLeft”、“Up”、“直立”、“Left”、“Center”、“Right”、“downlight
import java.awt.Color;
import java.awt.Graphics;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import com.fazecast.jSerialComm.*;
public class Main extends JPanel{
public void paintComponent(Graphics g, int x, int y) {
super.paintComponent(g);
g.setColor(Color.MAGENTA);
g.fillOval(x, y, 20, 20);
}
public void painter(int x, int y, int velx, int vely){
x = x + velx;
y = y + vely;
repaint();
}
public static void main(String[] args) {
int x = 0, y = 0, velx = 0, vely = 0;
SerialPort ports[] = SerialPort.getCommPorts();
System.out.println("Select a Port:");
SerialPort port = ports[1];
Graphics g;
if(port.openPort()){
System.out.println("Successfully opened the port.");
} else {
System.out.println("Unable to open the port.");
}
port.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
JFrame jf = new JFrame();
Main main = new Main();
jf.setTitle("Window");
jf.setSize(600, 400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(main);
Scanner data = new Scanner(port.getInputStream());
while(data.hasNextLine()) {
System.out.println(data.nextLine());
try{String dir = data.nextLine();
if(dir.equals("UpLeft")) {
velx = -1;
vely = -1;
}
if(dir.equals("Up")) {
velx = 0;
vely = -1;
}
if(dir.equals("UpRight")) {
velx = 1;
vely = -1;
}
if(dir.equals("Left")) {
velx = -1;
vely = 0;
}
if(dir.equals("Center")) {
velx = 0;
vely = 0;
}
if(dir.equals("Right")) {
velx = 1;
vely = 0;
}
if(dir.equals("DownLeft")) {
velx = -1;
vely = 1;
}
if(dir.equals("Down")) {
velx = 0;
vely = 1;
}
if(dir.equals("DownRight")) {
velx = 1;
vely = 1;
}
System.out.println(velx);
System.out.println(vely);
}
catch(Exception e) {};
}
}
}
建议:
SwingWorker
。您必须阅读本教程才能完全理解如何使用本课程。它将帮助您在后台线程中执行长时间运行的流读取,然后将获得的数据安全地传递到Swing事件线程上的Swing GUI中李>
doInBackground()
方法中完成。从扫描器/流中获取字符串,并调用worker的publish(…)
方法将字符串传递到此方法中public void getPortText(String text)
受保护的无效进程(列表块)
方法覆盖。使用for循环遍历chunkList
,通过调用GUI的getPortText(…)
方法将数据传递到Swing GUI中repaint()
成功您能否进一步介绍建议步骤4和步骤5?我开发了一个新的类SwingWorker,但不确定如何格式化受保护的void进程(列表块)循环或getPortText GUI方法。@JLag:看到了一个相关示例。