如何使用箭头键绘制线条(线段)?

时间:2014-01-15 23:43:59

标签: java swing user-interface

我正在尝试使用箭头键解决有关绘制线条的练习。当按下其中一个箭头键时,该线从中心开始向东,西,北或南方向拉。该代码仅在东方或西方方向工作,而不在北方或南方,这是我的问题!!

有人可以就此事给我一个想法吗?感谢。

以下是代码:

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

public class DrawingLinesUsingTheArrowKeys extends JFrame {

    // Create a panel
    private LinesUsingTheArrowKeys LinesUsingTheArrowKeys = new LinesUsingTheArrowKeys();

    public DrawingLinesUsingTheArrowKeys() {

        add(LinesUsingTheArrowKeys);

        /*
         * A component (keyboard) must be focused for its can receive the
         * KeyEvent To make a component focusable , set its focusable property
         * to true
         */
        LinesUsingTheArrowKeys.setFocusable(true);
    }

    public static void main(String[] args) {
        JFrame frame = new DrawingLinesUsingTheArrowKeys();
        frame.setTitle("Drawing Lines Using The Arrow Keys");
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200);
        frame.setVisible(true);
    }

    // Inner class: LinesUsingTheArrowKeys (keyboardPanel) for receiving key
    // input
    static class LinesUsingTheArrowKeys extends JPanel {
        private int x = 200;
        private int y = 100;
        private int x1 = x + 10;
        private int y1 = y;

        // register listener
        public LinesUsingTheArrowKeys() {
            addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                        // x1 += y1;
                        y1 += 10;

                        repaint();
                    } else if (e.getKeyCode() == KeyEvent.VK_UP) {
                        y1 -= 10;
                        repaint();
                    } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                        x1 += 10;
                        repaint();
                    } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                        x1 -= 10;
                        repaint();
                    }

                }
            });
        }

        // Draw the line(s)
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.drawLine(x, y, x1, y1);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的第一个错误是使用KeyListenerKeyListener只会在注册组件时对关键事件作出响应,并且具有焦点。

您的第二个错误是没有为您的LinesUsingTheArrowKeys课程提供大小提示,因此布局管理员可以了解您的组件应该有多大。

你的第三个错误是假设Swing中的绘画是准确的,而事实并非如此。 Swing中的绘画具有破坏性。也就是说,每次调用paintComponent时,期望Graphics上下文将被清除,并且需要绘制的内容将被完全重新生成。

看看:

基本上,更好的解决方案是拥有List PointpaintComponent只会在它们之间生成Line,甚至可能某种类型的Polygon ShapePoint。然后,您只需根据需要向此List添加新的{{1}},然后重新绘制组件