Usando o JFrame com um fluxo de entrada contínuo
Estou tentando implementar o código que lê da porta serial do meu redboard e, com base no que ele lê, repintar um círculo. O objetivo final disso é usar a classe Robot para obter o controle real do cursor, mas primeiro quero aprender mais sobre Java ao longo do caminho e, portanto, estou tentando obtê-lo com alguns gráficos básicos primeiro.
Para resumir meu problema, não sei como usar o JFrame com uma entrada continuamente alterada de um método estático.
A porta serial que acessa o JAR pode ser encontrada emhttp://fazecast.github.io/jSerialComm/
O Arduino grava continuamente na série com base em um sistema de acelerômetro FPGA nas formas "UpLeft", "Up", "UpRight", "Left", "Center", "Right", "DownLeft", "Down", " DownRight ". O programa Java deve então pegar isso e redesenhar um círculo adequadamente.
Consigo abrir o COMM3 e imprimir a direção correta recebida do meu hardware, mas sempre que tento aplicar o JFrame, perco-me. Encontrei muitos tutoriais do ActionListener, mas essa implementação deve ser contínua e não depende de eventos de mouse ou teclado. Portanto, não sei como usar os métodos paintComponent () e painter (), pois o método principal é estático.
Muito obrigado pelo seu tempo!
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) {};
}
}
}