我希望能够在我的框架带来前景时输入文本字段。程序设置为在5秒后将我的帧置于前景并将焦点设置在文本字段上。我启动程序然后单击另一个窗口。光标闪烁后,我的画面在5秒后显示。但是当我输入某些东西时,它实际上并没有被textfield作为输入。我还实现了FocusListener,以确认当帧到达前景时焦点设置为textfield。我的操作系统是Windows 10。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestMain implements FocusListener {
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
public JFrame frame = null;
private void createAndShowGUI() {
// Create and set up the window.
frame = new JFrame();
frame.addFocusListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label1 = new JLabel("Label");
panel.add(label1);
JTextField textField1 = new JTextField();
textField1.setPreferredSize(new Dimension(300, 40));
panel.add(textField1);
textField1.addFocusListener(this);
label1.addFocusListener(this);
frame.addWindowListener(new WindowAdapter() {
// Program Closing Alert
public void windowActivated(WindowEvent e) {
System.out.println("window activated");
textField1.requestFocusInWindow();
}
});
frame.getContentPane().add(panel, BorderLayout.CENTER);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
TestMain mn = null;
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
mn = new TestMain();
mn.createAndShowGUI();
System.out.println("START");
try {
Thread.sleep(5000);
mn.frame.setAlwaysOnTop(true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("Focus Gained by " + e.getComponent().getClass().getName());
}
@Override
public void focusLost(FocusEvent e) {
System.out.println("Focus Lost by " + e.getComponent().getClass().getName());
}
}
更新:当我添加
时frame.setLocationByPlatform( true );
之后
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
它仅适用于第一次。如果我改变主要功能
try {
Thread.sleep(5000);
mn.frame.setAlwaysOnTop(true);
mn.frame.setAlwaysOnTop(false);
Thread.sleep(5000);
mn.frame.setAlwaysOnTop(true);
mn.frame.setAlwaysOnTop(false);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
它第二次不起作用
答案 0 :(得分:0)
您确实将焦点带到了JTextField,但是您不会将焦点对准帧本身。将框架放在前面并将焦点带到框架上是不同的。可以在此处找到类似的解决方案:How to set focus the already running application?
答案 1 :(得分:0)
移动框架不会聚焦文本字段。您应该在始终设置在顶部之后添加toFront()
,这样如果窗口可见,则将窗口置于前面并使其成为焦点窗口。
try {
Thread.sleep(5000);
mn.frame.setVisible ( true );
mn.frame.toFront ( );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}