【发布时间】:2018-04-09 02:11:33
【问题描述】:
我正在尝试实现从我的红板串行端口读取的代码,并根据它读取的内容重新绘制一个圆圈。这样做的最终目标是使用 Robot 类来实现实际的光标控制,但我首先想了解更多关于 Java 的知识,所以我试图先用一些基本的图形来实现它。
总结一下我的问题,我不知道如何将 JFrame 与来自静态方法的不断变化的输入一起使用。
串口访问JAR可以在http://fazecast.github.io/jSerialComm/找到
Arduino 以“UpLeft”、“Up”、“UpRight”、“Left”、“Center”、“Right”、“DownLeft”、“Down”的形式连续写入基于 FPGA 加速度计系统的串行", "右下角"。然后 Java 程序应该抓取它并相应地重新绘制一个圆圈。
我能够打开 COMM3 并打印从我的硬件接收到的正确方向,但是每当我尝试应用 JFrame 时,我都会迷路。我找到了很多 ActionListener 教程,但是这个实现应该是连续的,并且不依赖于鼠标或键盘事件。因此,我不知道如何使用paintComponent() 和painter() 方法,因为main 方法是静态的。
非常感谢您的宝贵时间!
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) {};
}
}
}
【问题讨论】:
标签: java swing concurrency arduino actionlistener