Pregunta

I am trying to to set up a KeyListener to respond to my keystrokes. I have already setup a mouselistener but for some reason I am un-able to get the keylistener to respond to any keystrokes.

I have created a class that implements KeyListener and overridden the functions. I then created an instance of the new class and added the handler to the JPanel and JFrame. Still no dice

public class main_program extends JFrame {

    private int mX_cord, mY_cord,prior_selected_vertex, current_selected_vertex;
    private int verticies_to_edge1, verticies_to_edge2;
    private int radius =10;
    private boolean vertex_selected1 = false, vertex_selected2 = false, edge_ready = false,delete_vertex_ready = false;
    private Edge tempEdge = null;
    private ArrayList<Integer> vertex_xcord = new ArrayList<Integer>();
    private ArrayList<Integer> vertex_ycord = new ArrayList<Integer>();
    private ArrayList<Edge> edge = new ArrayList<Edge>();

    HandlerMouse handler = new HandlerMouse();
    HandlerKey keyhand = new HandlerKey();

    private JPanel masterPanel;
    private JTextArea masterTextArea;
    private JScrollPane masterScrollPane;
    private Point point1, point2;
    Graphics g;

    public main_program(){

        setTitle("Graph");
        setSize(600, 400);
        setDefaultCloseOperation(new JFrame().EXIT_ON_CLOSE);
        //this must be set for custom layout of components
        setLayout(null);

        masterPanel = new JPanel();
        masterPanel.setSize(600,300);
        masterPanel.setLocation(0, 0);
        masterPanel.setBackground(Color.WHITE);
        masterPanel.addMouseListener(handler);
        masterPanel.addMouseMotionListener(handler);
        masterPanel.addKeyListener(keyhand);

        masterTextArea = new JTextArea();
        masterTextArea.setBackground(Color.green);

        masterScrollPane = new JScrollPane();
        masterScrollPane.add(masterTextArea);
        masterScrollPane.setSize(600, 100);
        masterScrollPane.setLocation(0, 300);
        masterScrollPane.addMouseListener(handler);
        masterScrollPane.addMouseListener(handler);
        masterScrollPane.addKeyListener(keyhand);

        add(masterPanel);
        add(masterScrollPane);
        setLocationRelativeTo(null);
        setVisible(true);

    }

    public void paint(Graphics g){  
        super.paint(g);
        for(int i = 0 ; i < vertex_xcord.size(); i++){
            g.fillOval(vertex_xcord.get(i), vertex_ycord.get(i), radius, radius);
        }
        for(int i = 0 ; i<edge.size(); i++){
            tempEdge = edge.get(i);
            g.drawLine(vertex_xcord.get(tempEdge.vertex1), vertex_ycord.get(tempEdge.vertex1), vertex_xcord.get(tempEdge.vertex2), vertex_ycord.get(tempEdge.vertex2));
        }
        //g.fillOval(mX_cord, mY_cord, radius, radius);
        //repaint();
    }

    private class HandlerKey implements KeyListener{
        public void keyPressed(KeyEvent evt){
            System.out.println("key pressed");
            if(evt.getKeyCode() == KeyEvent.VK_ENTER && edge_ready){
                edge.add(new Edge(prior_selected_vertex, current_selected_vertex));
                edge_ready = false;
                repaint();
            }
        }
        public void keyReleased(KeyEvent evt){
            System.out.println("key rel");
        }
        public void keyTyped(KeyEvent evt){
            System.out.println("key type");
        }
    }
    private class HandlerMouse implements MouseListener, MouseMotionListener{

        public void mouseClicked(MouseEvent evt){
            mX_cord = evt.getX()-5;
            mY_cord = evt.getY()+15;
            if( evt.getClickCount() == 1){
                //mX_cord = evt.getX();
                //mY_cord = evt.getY();
                vertex_xcord.add(mX_cord);
                vertex_ycord.add(mY_cord);
                repaint();
            }
            else{
                for(int i = 0 ; i < vertex_xcord.size(); i++){
                    if(Math.abs(vertex_xcord.get(i) - mX_cord ) < 15 && Math.abs(vertex_ycord.get(i) - mY_cord ) < 15 ){
                        if(vertex_selected1 == false){
                            prior_selected_vertex = i;
                            vertex_selected1 = true;
                        }
                        else{
                            current_selected_vertex = i;
                            vertex_selected2 = true;
                        }
                        System.out.println("YOU HAVE SELECTED A VERTEX: " + i);
                        break;
                    }
                }
            }
            if(vertex_selected2 == true){
                edge_ready = true;
                verticies_to_edge1 = prior_selected_vertex;
                verticies_to_edge2 = current_selected_vertex ;
                vertex_selected1 = vertex_selected2 = false;
                System.out.println("Ready for edge!");
            }
            else{
                delete_vertex_ready = true;
            }
        }

        public void mouseEntered(MouseEvent arg0) 
        {   
        }

        public void mouseExited(MouseEvent arg0) 
        {
        }

        public void mousePressed(MouseEvent evt) 
        {
        }

        public void mouseReleased(MouseEvent arg0) 
        {
        }

        public void mouseDragged(MouseEvent e) 
        {
        }

        public void mouseMoved(MouseEvent e) 
        {
        }
    }

    class Edge {
        int vertex1, vertex2;
        public Edge(int v1, int v2){
            vertex1 = v1;
            vertex2 = v2;
        }
    }

    public static void main(String[] args){
        main_program circle = new main_program();
    }
}
¿Fue útil?

Solución

You've got several problems with that program, and it suggests that you'd do well to read many of the Swing Q&A's on this site, because these problems (and your main problem) are quite common, and solutions are often posted.

As to your main problem, the problem again is very common: KeyListeners only work if the listened to component has focus. If it loses focus or is not focusable, then you're out of luck. The best solution is often not to use a KeyListener but rather the higher level and more flexible Key Bindings. Google will find the tutorials for you for this.

As for other problems with your code:

  • You're using null layout, a layout that leads to inflexible GUI's that are very difficult to upgrade and enhance, and that look terrible on all but your current platform and screen resolution. Solution: study and use the layout managers.
  • You're drawing directly into a JFrame's paint(Graphics g) method, which has risks as you risk messing up the painting of any and all of the JFrame's constituents by doing this. Much better to draw in a JPanel's paintComponent(Graphics g) method, and gain the benefit of Swing (rather than AWT) graphics including automatic double buffering.
  • Your class has a Graphics variable, g, which suggests that you're contemplating using a stored Graphics object either from a component or from the JVM. This increases the risk of your program throwing a NullPointerException when that Graphics object no longer exists, either that or drawing with it and but not seeing any effect. Solution: draw inside the painting method (again better with a JComponent's paintComponent method) only, or with the Graphics object from a BufferedImage.
  • You're adding a MouseListener directly to a JPanel but are drawing in a different component, the JFrame, and by doing so without taking insets into account, are placing points in the wrong location. Use the MouseListener on the same component that you're drawing on.

Again, please have a look around here, as I think you'll find a lot of treasures on this site that can be used to enhance your program.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top