当前位置: 首页 > 知识库问答 >
问题:

更新图形

养焱
2023-03-14

我投降。几周来,我一直试图找出是什么阻止了我的代码的图形部分更新收到的串行数据。第一次用Java编程。我有大约15年的编程经验,我习惯于解决自己的问题,但这超出了这种策略的有效性。我的申请由两个文件组成。

一个文件来自RXTX项目,每秒捕获两次以多个数据包形式发送的串行数据。这就像一个魅力(花了一些时间),我可以看到捕获的数据是正确和稳定的。

另一个文件是图形文件,由大约80个菜单组成,最终用户可以在其中读取或有时写入值。使用鼠标按钮导航到目前为止,滚动条上的事件已完成。这一部分也能正常工作。可以读取、更改和保存值等。

我被卡住的地方是,从串行文件更新的值永远不会更新图形屏幕。我尝试了数百个例子和教程(很多来自这个网站),但都没有成功。

对象相关语言的概念对我来说是新的,仍然很混乱。我很确定我的问题涉及继承和类。线程是另一个候选对象......已经将代码削减到最小的大小,仍然可以运行并呈现我的问题,希望有人能看到哪里出了问题。

package components;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.SwingUtilities;

public class SerialComm extends ScreenBuilder implements java.util.EventListener {

InputStream in;

public SerialComm() {
    super();
}

public interface SerialPortEventListener
        extends java.util.EventListener {
}

void connect(String portName) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1");
    if (portIdentifier.isCurrentlyOwned()) {
        System.out.println("Error: Port is currently in use");
    } else {
        CommPortIdentifier.getPortIdentifier("COM1");
        System.out.println("" + portName);
        CommPort commPort = portIdentifier.open("COM1", 2000);
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
            InputStream in = serialPort.getInputStream();
            OutputStream out = serialPort.getOutputStream();
            serialPort.addEventListener(new SerialComm.SerialReader(in));
            serialPort.notifyOnDataAvailable(true);

            (new Thread(new SerialComm.SerialReader(in))).start();
            // TX functionality commented for now
            //               (new Thread(new SerialWriter(out))).start();

        } else {
            System.out.println("Error: Only serial ports are handled by this     example.");
        }
    }
}

public class SerialReader extends SerialComm implements Runnable,
        gnu.io.SerialPortEventListener {

    public SerialReader(InputStream in) {
        this.in = in;
    }

    @Override
    public void run() {
    count=11; // just for test. run is normally empty
    count2=count; // and real code runs within serialEvent()
    System.out.println("SerialReader " + count);
    dspUpdate(); // do some desperate stuff in graphics file
    System.out.println("Post Update " + count);
    }

    @Override
    public void serialEvent(SerialPortEvent event) {
    System.out.println("SerialEvent");
        switch (event.getEventType()) {
            case SerialPortEvent.DATA_AVAILABLE:
                try {
                    synchronized (in) {
                        while (in.available() < 0) {
                            in.wait(1, 800000);
                        } //in real code RX data is captured here twice a sec
                    } //and stored into buffers defined in ScreenBuilder
    //dspUpdate() is called from here to make ScreenBuilder update its screen
    //That never happens despite all my attempts               
                } catch (IOException e) {
                    System.out.println("IO Exception");
                } catch (InterruptedException e) {
                    System.out.println("InterruptedException caught");
                }
        }
    }
}

/* "main" connect PC serial port and start graphic part of application
 * To demonstrate problem with no serial data stream present
 * order of init between serial port and graphics are switched
 */

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            ScreenBuilder screen = new ScreenBuilder();
            screen.createAndShowGUI();
            System.out.println("Created GUI");
        }
    });
    try {
        (new SerialComm()).connect("COM1");
    } catch (Exception e) {
        System.out.println("Error");
        e.printStackTrace();
    }
  }
}

还有图形文件

package components;

import java.awt.*;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.*;

public class ScreenBuilder extends JPanel implements ActionListener {

public Font smallFont = new Font("Dialog", Font.PLAIN, 12);
Color screenColor;
Color lineColor;
short btn=0;
short count;
short count2;
Button helpButton;

public static void createAndShowGUI() {
    System.out.println("Created GUI on EDT? "
            + SwingUtilities.isEventDispatchThread());
    JFrame f = new JFrame("JUST A TEST");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new ScreenBuilder());
    f.pack();
    f.setVisible(true);
}

public void dspButton() {
    setLayout(null);// 
    helpButton = new Button("?");
    helpButton.setLocation(217, 8); // set X, Y
    helpButton.setSize(16, 14); //Set Size X, Y //
    helpButton.addActionListener(this);
    add(helpButton);
    setBackground(Color.black);
    helpButton.setBackground(Color.black);
    screenColor = Color.black;
    helpButton.setForeground(Color.white);
    lineColor = Color.white;
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == helpButton) {
        count2++;
        System.out.println("Pressed Button ");
        repaint();
    }
}

public ScreenBuilder() {
    setBorder(BorderFactory.createLineBorder(Color.black));
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(240, 180);
}

public void dspUpdate() {
    /*
     * This function is called from SerialComm
     * Should be called when serial packets have arrived (twice a second)
     * and update screen with values from serial stream
     * For now just a test var to validate that values from SerialComm
     * get to here (they do)
     */
count++;
System.out.println("Update Count " + count);
System.out.println("Update Count2 " + count2);
//    revalidate(); // another futile attempt to update screen
//    repaint();
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(lineColor);
    g.setFont(smallFont);
    count++;
    g.drawString("" + count, 130, 20);
    g.drawString("" + count2, 150, 20);
    if (btn == 0) {
      dspButton();
      btn = 1;
    }
  }
}

共有1个答案

甘西岭
2023-03-14

你遇到的最大问题是把所有东西都放进图形用户界面类中。试着把你的模型(后端串行通信的东西)和你的前端(漂亮的图形用户界面的东西)分开,你会省去很多头痛。在我试着为你做的例子中——它在一个文件中,但是你可能应该把它分成3个部分:模型、视图和控制(控制是模型和视图之间的通信)。

如果您将串行通信代码(您说它正在工作)添加到模型,而不是示例线程,那么您应该能够在视图和模型之间进行通信,而不会有太多麻烦。我尽量保存你的代码。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TranslucentWindow {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    View screen = new View();
                    System.out.println("Created GUI");
                    Model model = new Model();

                    Control c = new Control(screen, model);
                } catch (Exception e) {
                    System.out.println("Error");
                    e.printStackTrace();
                }
            }
        });
    }

    //Only cares about the backend.  Simplified because you said all the backend code was working right.
    public static class Model{

        //Data that was updated - you can change this to whatever you want.
        public String count;
        //Listener that notifies anyone interested that data changed
        public ActionListener refreshListener;

        public void run() {
            //As a sample, we're updating info every 1/2 sec.  But you'd have your Serial Listener stuff here
            Thread t = new Thread(new Runnable(){
                @Override
                public void run() {
                    int i = 0;
                    while(true){
                        dspUpdate(i++);
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }});
            t.start();
        }

        //Update data and notify your listeners
        public void dspUpdate(int input) {
            count = String.valueOf(input);
            System.out.println("Update Count " + count);
            refreshListener.actionPerformed(new ActionEvent(this, input, "Update"));
        }

    }


    //Only cares about the display of the screen
    public static class View extends JPanel {

        public Font smallFont = new Font("Dialog", Font.PLAIN, 12);
        Color screenColor;
        Color lineColor;
        short btn=0;
        String modelRefreshInfo;
        int buttonPressCount;
        Button helpButton;

        public View(){
            //Build Panel
            dspButton();

            //Create and show window
            System.out.println("Created GUI on EDT? "+ SwingUtilities.isEventDispatchThread());
            JFrame f = new JFrame("JUST A TEST");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(this);
            f.pack();
            f.setVisible(true);
        }

        public void dspButton() {
            setLayout(null);// 
            helpButton = new Button("?");
            helpButton.setLocation(217, 8); // set X, Y
            helpButton.setSize(16, 14); //Set Size X, Y //
            add(helpButton);
            setBackground(Color.black);
            helpButton.setBackground(Color.black);
            screenColor = Color.black;
            helpButton.setForeground(Color.white);
            lineColor = Color.white;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(240, 180);
        }   

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(lineColor);
            g.setFont(smallFont);
            g.drawString("ModelUpdates: " + modelRefreshInfo, 10, 20);
            g.drawString("RefreshCount: " + buttonPressCount, 10, 40);
            if (btn == 0) {
                dspButton();
                btn = 1;
            }
        }
    }

    //Links up the view and the model
    public static class Control{
        View screen;
        Model model;

        public Control(View screen, Model model){
            this.screen = screen;
            //Tells the screen what to do when the button is pressed
            this.screen.helpButton.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    //Update the screen with the model's info
                    Control.this.screen.buttonPressCount++;
                    System.out.println("Pressed Button ");
                    Control.this.screen.repaint();
                }
            });

            this.model = model;
            //Hands new data in the model to the screen
            this.model.refreshListener = new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    //Update the screen with the model's info
                    Control.this.screen.modelRefreshInfo = Control.this.model.count;
                    System.out.println("Model Refreshed");
                    Control.this.screen.repaint();
                }
            };

            //Starts up the model
            this.model.run();
        }       
    }
}
 类似资料:
  •        LSV会不定期对图源进行更新,这时只需点击“图源更新”即可自动更新图源。对于已有图源的更新需要将已加载的图源移除后重新加载才可以看见更新后的效果。

  • 我已经搜索了这个问题,但是每个人似乎都有图形更新太慢的问题。 来介绍我的情况: 我有一个JFrame,我设置为全屏,通过使用兼容的显示模式。在JFrame中,我有几个JPanels和JButton...在一个JPanels上,我正在绘制需要更新的移动对象。 我正在像这样更新图形:验证并重新绘制JFrame,然后重新验证并重新绘制相应的JPanel。图形更新得太快了。(我需要提到的是,在JPanel

  • 我使用chart.js在我的网页上有一个BarChart。 我在其中添加了两个数据点 现在我想要更新那些条A和B,而不是删除它们并再次添加它们(我已经想好了如何做到这一点)。我想让它们垂直移动以适应它们的新值,但我无法找到如何访问图表中已经存在的数据。 没有什么比得上 其中第一个值将是存储数据的索引(F.E.)。 我该怎么做呢?

  • 我有一个有大约200张幻灯片的PowerPoint演示文稿。每张幻灯片都有一个图表,其中的数据通过到主xlsx文件的链接每月更新一次。 为了不在图表中显示空值(未来月份),我打开数据编辑器(图表右键单击>Edit data...)并选择直到当前月份的范围。 我在PowerPoint中为它写了一个宏:

  • 我想在android中从mysql数据库中检索数据,并在textview中显示 这是后台asynctask代码 }

  • Many web-developers forget to write width and height attributes for <img> tags which leads to poor UX. This action helps you to automate this process: simply place caret inside <img> tag and run this