使用键盘在J按钮之间移动



我想使用FlowLayout或任何其他布局在JPanel中添加JButtons,并使用UpDown键在JButtons之间移动。。上下移动有问题,因为我不知道JButton的行和列。

public class abc{
List<ControlCenterButton>  buttons=getButtons();     
JPanel buttonPanel= new JPanel();
buttonPanel.setLayout(new FlowLayout)
for (int i = 0; i < buttons.size(); i++) {
            ControlCenterButton  button = buttons.get(i);
            if (button.getLayarID().equals(id)) {
                flag = true;
                button.addActionListener(this);
               button.setPosition(i);
                button.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mousePressed(MouseEvent mouseEvent) {
                        buttonPanel.requestFocusInWindow();
                    }
                });
                buttonPanel.add(button);
}
   buttonPanel.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent keyEvent) {
                final ControlCenterButton selectedControlCenterButton =       (ControlCenterButton) Session.getSession().getAttribute("controlcenter.selectedbutton");
                int position = selectedControlCenterButton.getPosition();
                int keycode = keyEvent.getKeyCode();
                switch (keycode) {
                    case KeyEvent.VK_RIGHT: {
                        if (position + 1 >= buttons.size()) {
                            ControlCenterButton.selectButton(buttons.get(0));
                        } else
                            ControlCenterButton.selectButton(buttons.get(position + ));
                        break;
                    }
             case KeyEvent.VK_UP: {
                            break;
                        }
                        case KeyEvent.VK_DOWN: {
                        }             
       case KeyEvent.VK_ENTER: {
                        selectedControlCenterButton.requestFocusInWindow();
                        new   ControlCenterButton().openApplication(selectedControlCenterButton);
                        break;
                    }
                }
 }
 public class ControlCenterButton extends JButton implements ActionListener {
 private int position;
 public int getPosition() {
      return position;
}
public void setPosition(int position) {
    this.position = position;
}
}
  1. 向上向下按键上侦听的所有按钮中添加一个按键侦听器

  2. 将x,y坐标添加到按钮。也就是说,你可以扩展JButton,或者有一种将坐标与JButton关联起来的映射。

  3. 当按下上下键时,计算焦点应该落在哪里,然后在确定它应该是什么按钮后,调用按钮上的requestFocusInWindow()。

相关内容

  • 没有找到相关文章

最新更新