武装只有一个JPopupMenu的JMenuItem

时间:2018-01-23 11:09:09

标签: java swing jmenuitem jpopupmenu

我有一个JPopupMenu,每次我写它都会更新。默认情况下,第一个元素是武装的。我希望能够使用向上和向下键来选择不同的JMenuItem。

public void colocar(Component e, int x, int y, ArrayList<Ocurrencia> predicciones) {
    this.Pmenu.setVisible(false);
    this.Pmenu.removeAll();

    JMenuItem menuItem;
    for (int i = 0; i < predicciones.size(); i++) {
        menuItem = new JMenuItem(predicciones.get(i).getPrediccion());
        Pmenu.add(menuItem);
        if (i == 0) {
            menuItem.setArmed(true);
        }
        menuItem.addActionListener(new ActionListenerImpl(jt));
    }

    this.Pmenu.show(e, x, y);
    this.jt.requestFocus();
}

通过监听器,我控制按下的keyCode以知道它是38还是40,(键向上或向下)。我保存数组中的所有组件,然后我尝试使用.setArmed(true),但它不会更改。我想询问是否武装JMenuItem除了删除所有JMenuItem之外还有其他方法,并将其重新插入我想要武装的那个。

这是完整的课程:

公共类PopUpMenu {

private final JPopupMenu Pmenu;
private final javax.swing.JTextArea jTextArea;

public PopUpMenu(javax.swing.JTextArea jt, JPopupMenu Pm) {
    this.jTextArea = jt;
    Pmenu = Pm;
}

public void colocar(Component e, int x, int y, ArrayList<Ocurrencia> predicciones) {
    this.Pmenu.setVisible(false);
    this.Pmenu.removeAll();

    JMenuItem menuItem;
    for (int i = 0; i < predicciones.size(); i++) {
        Pmenu.add(menuItem = new JMenuItem(predicciones.get(i).getPrediccion()));
        menuItem.setHorizontalTextPosition(JMenuItem.RIGHT);
        menuItem.addActionListener(new ActionListenerImpl(jTextArea));
    }

    this.Pmenu.show(e, x, y);
    this.jTextArea.requestFocus();
}

private static class ActionListenerImpl implements ActionListener {

    private final javax.swing.JTextArea jt;

    public ActionListenerImpl(javax.swing.JTextArea jt) {
        this.jt = jt;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        StringBuilder sb = new StringBuilder(jt.getText());

        String semilla = jt.getText().substring(0, jt.getCaretPosition());

        String[] palabras = semilla.split("\\s+");
        String palabraInacabada = palabras[palabras.length - 1];
        String prediccionRecortada = e.getActionCommand().substring(palabraInacabada.length(), e.getActionCommand().length());

        sb.insert(jt.getCaretPosition(), prediccionRecortada + " ");

        jt.setText(sb.toString());
    }
}

}

0 个答案:

没有答案