java - 无法添加 JFrame 和 JTextField

标签 java swing paintcomponent rect border-layout

这是我可以在框架上移动矩形的简单代码的一部分。当我尝试在框架上添加按钮和文本字段时,这些组件不可见或我看不到矩形。我还尝试先在 JPanel 上添加它们,然后在框架上添加面板。组件是可见的,但矩形不是。有什么建议么?

public class Buffer extends JPanel implements KeyListener,ActionListener{
public static JFrame frame;
public static JButton button;
public static JTextField field;
public int x;
public int y;

    public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setColor(Color.red);
    g.fillRect(x,y,20,20);
}

public static void main(String args[]){
    Buffer z=new Buffer();
    frame=new JFrame();
    button=new JButton();
    field=new JTextField(); 
    frame.setLayout(new BorderLayout());

    button.setPreferredSize(new Dimension(20,20));
    button.setText("XY");
    button.addActionListener(z);

    field.setPreferredSize(new Dimension(100,20));
    field.setEditable(false);

    frame.setSize(500,500);
    frame.setVisible(true);
    frame.setFocusable(true);
    frame.addKeyListener(z);
    frame.setTitle("TEST");
}
@Override
public void keyPressed(KeyEvent e) {
    if(e.getKeyCode()==KeyEvent.VK_RIGHT){
        x=x+10;
        repaint();
    }
    }
    public void actionPerformed(ActionEvent e){
    field.setText("X- "+x+"       Y- "+y);
    frame.requestFocusInWindow();
}
    }
    }

最佳答案

  • JFrame 默认情况下永远不会对 KeyEvent 使用react,这意味着 frame.setFocusable(true);

    <
  • 必须为 JPanel setFocusable(true),然后 KeyListenerKeyEvents 会触发一个期望的事件


关于java - 无法添加 JFrame 和 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17649885/

相关文章:

java - 将 xmlUnit 中的元素与空元素进行比较时发现意外差异

java - 运行使用 Cucumber 实现 CommandLineRunner 的 SpringBoot 应用程序,在运行功能测试用例之前运行主应用程序

Java - 是否可以将 JMenuBar 添加到 JFrame 的装饰窗口?

java - 同时初始化多个图像

java - 标签移动时不调用paintComponent

java - PaintComponent 中的 BufferedImage 始终为 null

java - 后退按钮退出应用程序而不是返回到 MainActivity

java - 与查询不服务相关的最佳和最全面的 SOAP 库是什么

java - Maven2 和 Swing 项目 : Build & run swing application

java - PaintComponent 中的 while 语句