runtime error with KeyAdapter, awt, swing on java.

2019-09-14 05:21发布

问题:

hello im wrote some code i though it was going to work but it compiles and it doesnt even throws an exception or anything. it also creates the icon like its openned but i click it and it doesnt do anything please need help to know what am i doing wrong . heres the code of the class:

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

public class ventanatexto {
   public JFrame ventana;
   public String texto;
    ventanatexto(){
    JFrame.setDefaultLookAndFeelDecorated(true);
    texto="";
    ventana= new JFrame("teclado");
    panel1 panel= new panel1();
    ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ventana.add(panel);
     ventana.setVisible(true);
    ventana.addKeyListener(new handler());

    }

    public class panel1 extends JPanel {

        @Override
    public void paint(Graphics g){
        super.paint(g);
    Dimension dim= getSize();
    g.clearRect(0, 0, dim.width, dim.height);
    g.drawString(texto, WIDTH, WIDTH);
    };


}
    class handler extends KeyAdapter{
        @Override
    public void keyPressed(KeyEvent k){
    char tecla= k.getKeyChar();
    switch(tecla){

        case 127:texto="";
    break;
        case 8: if(texto.length()>0){texto=texto.substring(0, texto.length()-1);}
            break;
        default:
            if (texto.length()<15){texto+=tecla;}

    }
    ventana.repaint();
    }

    }}

and here is my main:

package practicagraficos8;

public class Practicagraficos8 {

    public static void main(String[] args) {

        ventanatexto prueba= new ventanatexto();
    }
}

回答1:

As shown here, "drawString() expects the coordinates to represent the baseline of the String."

FontMetrics fm = g.getFontMetrics();
g.drawString(texto, 0, fm.getAscent());

In addition,

  • Use a JTextComponent for editable text.

  • Use Key Bindings, rather than KeyListener.

  • Use pack() on the enclosing Window.

  • "Swing programs should override paintComponent() instead of overriding paint()."—Painting in AWT and Swing: The Paint Methods.

  • Swing GUI objects should be constructed and manipulated only on the event dispatch thread.

  • Use appropriate access control.



回答2:

I've tried running your code. If you ask why your window does not show up, try setting bounds (size and location) on your JFrame:

ventana.setBounds(0, 0, 200, 200);

It seems the window will not show up, when using the decorated look and feel, if no bounds are set.



标签: java swing awt