draw two line by KeyTyped event in java

情到浓时终转凉″ 提交于 2019-12-02 22:34:02

问题


hi I want to draw horizontal and vertical axis in a panel by pressing h and v on keyboard . I don't know how ... this is my code . how can I control the Keytyped event

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import java.awt.geom.Line2D;

@SuppressWarnings("serial")
public class DrawAxis extends JPanel implements KeyListener
{   
private Graphics2D g2;
private float x1;
private float y1;
private float x2;
private float y2;

public void DrawingAxis(float X1,float Y1,float X2,float Y2)
{
    x1=X1;
    y1=Y1;
    x2=X2;
    y2=Y2;
}

public void paint(Graphics g)
{
    super.paintComponent(g);
    g2=(Graphics2D) g;
    g2.setColor(Color.GRAY);
    g2.setStroke(new BasicStroke(1));
    g2.draw(new Line2D.Float(x1,y1,x2,y2));
}

@Override
public void keyPressed(KeyEvent event) {

}

@Override
public void keyReleased(KeyEvent event) {

}

@Override
public void keyTyped(KeyEvent event) {
    char ch=event.getKeyChar();
    switch(ch) 
    {
    case 'h':
        //????????
    case 'v':
        //????????
    }
}
}

and this is the main code :

import javax.swing.JFrame;

public class Example1
{
public static void main(String[] args) {
    JFrame frame=new JFrame("Drawing line");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1000,1000);
    DrawAxis dshape=new DrawAxis();
    dshape.DrawingAxis(500,0,500,1000);
    dshape.DrawingAxis(0,500,1000,500);
    dshape.setFocusable(true);
    dshape.addKeyListener(dshape);
    frame.add(dshape);
    frame.setVisible(true);

}

}

how can I complete this code?


回答1:


Start by using the key bindings API over KeyListener, it will solve some key issues associated with KeyListener. See How to Use Key Bindings for more details.

You could simply store a series of points in a array or List and use Graphics#drawLine to draw lines between them, or you could take advantage of Graphics 2D's shape API. See 2D Graphics for more details

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.Path2D;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DrawLine {

    public static void main(String[] args) {
        new DrawLine();
    }

    public DrawLine() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Point currentPoint;
        private Path2D shape;

        public TestPane() {
            currentPoint = new Point(0, 0);
            shape = new Path2D.Double();
            shape.moveTo(0, 0);

            bindKey(KeyEvent.VK_H, "draw.horizontally", new AddPointAction(4, 0));
            bindKey(KeyEvent.VK_V, "draw.vertically", new AddPointAction(0, 4));
        }

        protected void bindKey(int vkKey, String name, Action action) {
            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(vkKey, 0), name);
            am.put(name, action);
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.draw(shape);
            g2d.dispose();
        }

        public class AddPointAction extends AbstractAction {

            private int xDelta;
            private int yDelta;

            public AddPointAction(int xDelta, int yDelta) {
                this.xDelta = xDelta;
                this.yDelta = yDelta;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                int x = currentPoint.x + xDelta;
                int y = currentPoint.y + yDelta;
                shape.lineTo(x, y);
                currentPoint.x = x;
                currentPoint.y = y;
                repaint();
            }

        }

    }

}


来源:https://stackoverflow.com/questions/33664601/draw-two-line-by-keytyped-event-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!