当用户点击主面板时,我想失去对JTextField的关注。
setFocusable(true)
对我不起作用。
如果我点击主面板,JTextField仍然是焦点,你可以输入内容。
注意:我的JFrame设置为可聚焦(true)。
答案 0 :(得分:5)
我认为既然您希望专注于点击主面板,那么您应该实现一个简单的MouseListener
来为您完成工作。再次,因为面板(主面板)被添加到JFrame
或者更确切地说它被设置为内容窗格,这就是应该调用setFocusable(true);
的地方。下面的代码应该解决问题:
mainPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseReleased(e);
Focus.this.grabFocus();
}
});
请注意,Focus
是我的班级名称,并且在将JPanel
添加到JFrame
之前会延长{{1}}。
答案 1 :(得分:3)
注意:我的JFrame设置为可聚焦(true)。
例如
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JPanelAndFocus {
private JFrame frm = new JFrame("JPanel_And_Focus");
private JPanel panel = new JPanel();
private JTextField one = new JTextField(10);
private JTextField two = new JTextField(10);
private JTextField three = new JTextField(10);
public JPanelAndFocus() {
//panel.setLayout(new FlowLayout());
panel.add(one);
panel.add(two);
panel.add(three);
panel.setFocusable(true);
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
//delayed should be important for events from DocumentListener / InputMask
@Override
public void run() {
//panel.requestFocus();
panel.requestFocusInWindow();
}
});
}
});
panel.setPreferredSize(new Dimension(400, 100));
frm.add(panel);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLocation(400, 300);
frm.pack();
frm.setVisible(true);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//one.requestFocus();
one.requestFocusInWindow();
}
});
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JPanelAndFocus jpaf = new JPanelAndFocus();
}
});
}
}
答案 2 :(得分:2)
虽然上面提到的不同方法对我没有用,意味着重点仍然放在JButton上,我发现e.getSource()可以正确设置组件焦点
YourContainerPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JComponent clicked = (JComponent)e.getSource();
clicked.requestFocusInWindow();
}
});
答案 3 :(得分:0)
试试这个
this.getParent().requestFocus()