首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java GUI:如何在JFrame上的JPanel中设置对JButton的关注?

Java GUI:如何在JFrame上的JPanel中设置对JButton的关注?
EN

Stack Overflow用户
提问于 2011-12-23 20:14:53
回答 5查看 60.3K关注 0票数 19

我已经进行了实验和搜索,但我似乎想不出什么是我认为简单的事情,那就是当我的小GUI应用程序启动时,让我的开始按钮具有焦点,所以用户所要做的就是按下他们的Enter/Return键,这将具有与他们用鼠标点击开始按钮相同的效果。这是我的代码。感谢您的帮助:)

代码语言:javascript
复制
private void initialize() {

   // Launch the frame:
   frame = new JFrame();
   frame.setTitle("Welcome!");
   frame.setSize(520, 480);
   frame.setLocationRelativeTo(null);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   // Add the image:
   ImageIcon heroShotImage = new ImageIcon("heroShot.jpg");
   JPanel heroShotPanel = new JPanel();
   JLabel heroShot = new JLabel(heroShotImage);
   heroShotPanel.add(heroShot);

   // Create a panel to hold the "Start" button:
   JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

   // Create the "Start" button, which launches business logic and dialogs:
   JButton start = new JButton("Start");
   start.setToolTipText("Click to use library");
   start.setFocusable(true); // How do I get focus on button on App launch?
   start.requestFocus(true); // Tried a few things and can't get it to work.

   // Listen for user actions and do some basic validation:
   start.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
      // THE APP's LOGIC GOES HERE...
      }

   // Finish setting up the GUI and its components, listeners, and actions:
   submitPanel.add(start);

   frame.getContentPane().add(heroShotPanel, BorderLayout.NORTH);
       frame.getContentPane().add(submitPanel, BorderLayout.SOUTH);

}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8615958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档