焦点在哪儿 本帖最后由 yaojianquansb 于 2010-08-16 11:23:06 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 焦点肯定在窗体可用控件的第一个上面,根据你上面的代码,焦点应该在button1上,当你打开窗体,你可以通过tab键进行焦点迁移。 是的, public ActionPanel(){ JButton b1 = new JButton("button1"); JButton b2 = new JButton("button2"); add(b1); add(b2); System.out.println(b1.isFocusOwner()); //在构造方法里检测一下b1按钮,就是第一个按钮是否有焦点,为啥输出false? } 你这样frame还没有渲染完,frame不确定将焦点定义在哪个组件上,所以你直接在添加过程中获取是不行的。其次isFocusOwner()这个方法的源码是调用返回的是hasFocus,是返回的是键盘事件的焦点。所以我们需要有个键盘或者鼠标的触发事件,才能得到这个值。import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;public class Test{ static JButton b1 = new JButton("button1"); static JButton b2 = new JButton("button2"); public static void main(String args[]){ Test test=new Test(); ActionFrame frame = test.new ActionFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); System.out.println(frame.isFocusOwner()); System.out.println(b1.isFocusOwner()); System.out.println(b2.isFocusOwner()); } class ActionPanel extends JPanel{ public ActionPanel(){ add(b1); add(b2); } } class ActionFrame extends JFrame{ public ActionFrame(){ setTitle("ActionTest"); setSize(450,300);setLocation(550,350); ActionPanel panel = new ActionPanel(); getContentPane().add(panel); } }}我给你稍微改了下,试试看! 上面的代码应该也是输出false。是因为没有触发键盘或者鼠标事件。在System.out.println(frame.isFocusOwner()); System.out.println(b1.isFocusOwner()); System.out.println(b2.isFocusOwner());代码前加入b1.doClick(); 这个问题怎么办? 求助~关于子集合的问题 菜鳥急問~~.關於jlabel與jpanel~ 大侠 observer模式的例子,谢谢 tomcat7的问题,求助 关于Java查询DB2数据库数据时出的问题???? 怎样在applet程序中显示一幅jpeg图片?该图片存在于c:\image\下。 请问:在一个jb6的工程里两个自建包的互相引用问题 用java读取位图 编了一段很小的程序,报了一个很低级的错误(编译通过) java线程问题 List 泛型报错,哪写错了?
JButton b1 = new JButton("button1");
JButton b2 = new JButton("button2");
add(b1);
add(b2);
System.out.println(b1.isFocusOwner());
//在构造方法里检测一下b1按钮,就是第一个按钮是否有焦点,为啥输出false?
}
其次isFocusOwner()这个方法的源码是调用返回的是hasFocus,是返回的是键盘事件的焦点。
所以我们需要有个键盘或者鼠标的触发事件,才能得到这个值。import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test{
static JButton b1 = new JButton("button1");
static JButton b2 = new JButton("button2");
public static void main(String args[]){
Test test=new Test();
ActionFrame frame = test.new ActionFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
System.out.println(frame.isFocusOwner());
System.out.println(b1.isFocusOwner());
System.out.println(b2.isFocusOwner());
}
class ActionPanel extends JPanel{
public ActionPanel(){
add(b1);
add(b2);
}
}
class ActionFrame extends JFrame{
public ActionFrame(){
setTitle("ActionTest");
setSize(450,300);setLocation(550,350);
ActionPanel panel = new ActionPanel();
getContentPane().add(panel);
}
}
}我给你稍微改了下,试试看!
是因为没有触发键盘或者鼠标事件。
在System.out.println(frame.isFocusOwner());
System.out.println(b1.isFocusOwner());
System.out.println(b2.isFocusOwner());
代码前加入b1.doClick();