有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:发送和接收KeyEvent。VK_返回_空间结果到/来自串行

我的目标有点复杂,我不确定这是否可能。但我正在为我工作的一家公司制作终端程序

所以程序是这样构建的(至少是重要部分)。 我有一个JTextArea正在使用JSSC库接收从序列读取的字节。这个JTextArea有一个键侦听器,它侦听一个按键,并使用SerialPort.writeInt(event.getKeyCode());.getKeyChar();将每个按键作为int发送到序列。我不记得了,但我想它是getKeyChar();。当我在JTextArea上按Backspace时,假设我输入了reset halt以将控制模块重置为出厂默认值并停止它。如果我按Backspace2次,在实际的控制模块中,它会“退格”2个字符,但在JTextArea上,每次按Backspace时,它仍会显示reset halt加上(我想主要修复的部分)[K。所以

  1. 我输入reset halt
  2. 我按了两次Backspace
  3. 我的JTextArea上的结果是reset halt[K[K
  4. 实际控制模块上的结果(我看不到结果)是reset ha

我认为这可能是我正在使用的键码,所以当我按下Backspace时,我做了一个if语句来更改通过串行发送的内容

if(event.getKeyCode() == KeyEvent.VK_BACK_SPACE){
    SerialPort.writeInt(127); //Decimal for Delete
    //And (not at the same time)
    SerialPort.writeInt(8); //Decimal for Backspace (from ASCII code)
}

当然,我错了,问题依然存在

因此,我的问题是:

  1. 是否可以通过读取序列来“更新”正在“退格”到myJTextArea的内容
  2. 如何防止讨厌的[K出现在我的控制台(JTextArea)上

我不需要你为我做这项工作,只是简单地把我推向正确的方向

我很抱歉没有在这个问题上添加太多代码。出于“安全原因”,我在家和我的工作区没有互联网(令人震惊)。如果你需要更多的代码,请让我知道,我会尝试添加它,如果我可以

我还有一个附带问题,关于我想在控制台中添加/更改的内容(JTextArea)。我不知道它的技术术语,但我想增加控制台上键入光标的宽度,使其更可见,而不是鼠标光标,而是当您单击文本字段时显示的闪烁光标。那个光标叫什么


共 (1) 个答案

  1. # 1 楼答案

    这里有一个例子

    字符串是使用MyTestPanel的图形对象绘制的。绘图是在MyTestPanel的paintComponent()内部完成的

    此面板也会检测到KeyEvents。因为这没有任何默认行为,所以您可以自由地对给定的输入执行您想要的操作

    我还没有处理水平滚动和面板动态宽度

    TestFrame2

    import java.awt.Dimension;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    import javax.swing.SwingUtilities;
    
    public class TestFrame2 {
        public static void main(String[] args) throws Exception {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    createAndShow();
                }
            });
        }
    
        public static void createAndShow() {
            JFrame frame = new JFrame("Test Frame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final MyTestPanel panel = new MyTestPanel();
    
            //add any other components like buttons, labels to panel
    
            JScrollPane scrollPane = new JScrollPane(panel);
            scrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
            panel.setParentPane(scrollPane);
            scrollPane.setPreferredSize(new Dimension(700, 300));
            frame.add(scrollPane);
    
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    super.windowClosing(e);
                    //panel.stopCursorThread();
                }
            });
            //frame.setSize(300, 300);
            frame.pack();
            //frame.setSize(frame.getWidth(), frame.getHeight());
            frame.setLocationRelativeTo(null);
            System.out.println(frame.getWidth() + " : " + frame.getHeight());
            frame.setVisible(true);
            //panel.startCursorThread();
        }
    }
    

    MyTestPanel

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.JPanel;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    
    public class MyTestPanel extends JPanel {
        final int LINE_HEIGHT = 20;
        final int START_X = 20;
        final int START_Y = 20;
        //private int lastLineY;
    
        final List<String> lines = new ArrayList<String>();
        final StringBuilder lastLine = new StringBuilder();
        private JScrollPane parentPane;
        //Thread cursorThread;
        //private AtomicBoolean keepRunningCursor = new AtomicBoolean(true);
    
        String validCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,.\\/:;<=>?@[] ^_`{|}~-]*$";
    
        /*public static void main(String[] args) throws Exception {
            TestFrame2.main(null);
        }*/
    
        public MyTestPanel() {
            //setPreferredSize(new Dimension(700, 300));
            this.setFocusable(true);
            this.setBackground(Color.WHITE);
    
            addKeyListener(new KeyListener() {
                @Override
                public void keyTyped(KeyEvent e) {
                    char ch = e.getKeyChar();
                    if (isPrintableChar(ch)) {
                        lastLine.append(ch);
                        repaint();
                    } else if (ch == '\b') {
                        if (lastLine.length() > 0) {
                            lastLine.deleteCharAt(lastLine.length() - 1);
                            repaint();
                        }
                    } else if (ch == '\n') {
                        lines.add(lastLine.toString());
                        lastLine.delete(0, lastLine.length());
                        repaintAndUpdate();
                    }
                    updateScrollbar();
                    System.out.println("textContent " + lastLine);
                }
    
                @Override
                public void keyReleased(KeyEvent e) {
    
                }
    
                @Override
                public void keyPressed(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                        System.out.println("BackSpace pressed");
                    }
                }
            });
        }
    
        public void updateScrollbar() {
            if (parentPane != null) {
                JScrollBar vertical = parentPane.getVerticalScrollBar();
                System.out.println(vertical.getMaximum() + " : " + parentPane.getHeight() + " : " + (vertical.getMaximum() - parentPane.getHeight()) + " : " + vertical.getHeight());
                vertical.setValue(vertical.getMaximum() - parentPane.getHeight() + parentPane.getHorizontalScrollBar().getHeight());
            }
        }
        private void repaintAndUpdate() {
            int linesHeight = START_Y + lines.size() * LINE_HEIGHT + LINE_HEIGHT;//+LINE_HEIGHT just trial and error
            if(linesHeight > parentPane.getHeight()) {
                System.out.println(getHeight() + " : " + (getHeight() + LINE_HEIGHT));
                super.setPreferredSize(new Dimension(getWidth(), getHeight() + LINE_HEIGHT) );
                parentPane.updateUI();
                super.revalidate();
                System.out.println(getHeight());
    
                repaint();
            }
        }
    
        private boolean isPrintableChar(char ch) {
            boolean result = false;
            if (validCharacters.indexOf(ch) != -1) {
                result = true;
            }
            return result;
        }
    
        /*public void startCursorThread() {
            final Graphics g = this.getGraphics();
            final int blinkInterval = 500;//miliseconds
            final int cursorWidth = 5;
            final int cursorHeight = LINE_HEIGHT;
    
            cursorThread = new Thread () {
                public void run () {
                    boolean showCursor = true;
                    while(keepRunningCursor.get()) {
                        localSleep(blinkInterval);
                        int x = START_X + g.getFontMetrics().stringWidth(lastLine.toString());
                        //int y = START_Y + lines.size() * LINE_HEIGHT - LINE_HEIGHT + LINE_HEIGHT/3;
                        int y = lastLineY - (int)(2/3.0 * LINE_HEIGHT);
                        if(showCursor) {
                            g.fillRect(x, y, cursorWidth, cursorHeight);
                            g.drawRect(x - 50, y - 50, 100, 100);
                        } else {
                            g.setColor(Color.WHITE);
                            g.fillRect(x, y, cursorWidth, cursorHeight);
                            g.drawRect(x - 50, y - 50, 100, 100);
                            g.setColor(Color.BLACK);
                        }
                        showCursor = !showCursor;
    
                        System.out.printf("%d %d %d %d\n", x, y, cursorWidth, cursorHeight);
                        //MyTestPanel.this.repaint(x, y, cursorWidth, cursorHeight);
                    }
    
                }
    
                public void localSleep(long sleepTime) {
                    try {
                        sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
    
            };
    
            cursorThread.start(); 
        }*/
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int y = START_Y;
            for (int i = 0; i < lines.size(); i++, y += LINE_HEIGHT) {
                g.drawString(lines.get(i), START_X, y);
            }
            if (lastLine.length() > 0) {
                g.drawString(lastLine.toString(), START_X, y);
            }
            int x = START_X + g.getFontMetrics().stringWidth(lastLine.toString());
            //cursor
            g.fillRect(x + 2, y - (int)(2/3.0 * LINE_HEIGHT), 5, 20);
            //lastLineY = y;
        }
    
        public void setParentPane(JScrollPane parentPane) {
            this.parentPane = parentPane;
            setPreferredSize(new Dimension(parentPane.getWidth(), parentPane.getHeight()));
        }
    
        /*public void stopCursorThread() {
            this.keepRunningCursor.set(false);
            System.out.println("Stopped cursor thread");
        }*/
    }
    

    输出屏幕截图

    enter image description here