【问题标题】:Add Keylistener to full-screen JWindow将 Keylistener 添加到全屏 JWindow
【发布时间】:2011-05-26 11:20:25
【问题描述】:

我已经制作了一个全屏 JWindow,我想添加一个简单的 KeyListener,以便在按下箭头键的情况下执行某些操作
但我不知道为什么它不起作用。我已将 keylistener 添加到所有组件中。但是还是不行
谁知道是什么问题?

【问题讨论】:

  • @jzd:+1 - 击败我。我忙于随机猜测。 ;)
  • 你为什么回滚我的修订版?

标签: java swing keylistener jwindow


【解决方案1】:

默认情况下,JWindow 不会接收键事件,除非您在创建窗口时指定 JFrame 作为所有者。下面的代码演示了这一点:

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

public class WindowTest
{
    public static void main(String[] args)
    {

        JFrame frame = new JFrame();
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//      frame.setLocation(-200, 0); // uncomment this line to hide the dummy frame
        frame.setVisible( true );

        JWindow window = new JWindow(); // this doesn't work
//      JWindow window = new JWindow(frame); // this works

        window.getContentPane().add( new JTextField(10), BorderLayout.NORTH );
        window.getContentPane().add( new JButton("Button") );
        String[] items = { "Select Item", "Color", "Shape", "Fruit" };
        JComboBox mainComboBox = new JComboBox( items );
        window.getContentPane().add( mainComboBox, BorderLayout.SOUTH );

        window.setBounds(50, 50, 200, 200);
        window.setVisible(true);
        window.getRootPane().setBorder(new javax.swing.border.MatteBorder(4, 4, 4, 4, Color.BLUE));
     }
}

更简单的解决方案是使用未装饰的 JFrame:

JFrame frame = new JFrame();
frame.setUndecorated(true);

我想添加一个简单的 KeyListener,以便在按下箭头键的情况下执行某些操作

此外,您不应该为此使用 KeyListener。你应该使用Key Bindings

【讨论】:

    【解决方案2】:

    这可能只是将相关组件设置为可聚焦的问题。例如

    myContentPane.setFocusable(true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-24
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多