Чтение текста из одной переменной multiy JButtons - PullRequest
1 голос
/ 25 августа 2011

У меня есть одна переменная JButton, которую я использовал для создания разных кнопок с разным номером

JButton numb;
numb = new JButton("7");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.ipadx = 30;
    c.ipady = 30;
    c.gridx = 0;
    c.gridy = 3;
    c.gridwidth = 1;
    displayPanel.add(numb, c);
    numb.setFont(new Font("arial",Font.BOLD,20));
    numb.addActionListener(this);

    numb = new JButton("8");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.ipadx = 30;
    c.ipady = 30;
    c.gridx = 1;
    c.gridy = 3;
    c.gridwidth = 1;
    displayPanel.add(numb, c);
    numb.setFont(new Font("arial",Font.BOLD,20));
     numb.addActionListener(this);

    numb = new JButton("9");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.ipadx = 30;
    c.ipady = 30;
    c.gridx = 2;
    c.gridy = 3;
    c.gridwidth = 1;
    displayPanel.add(numb, c);
    numb.setFont(new Font("arial",Font.BOLD,20));
    numb.addActionListener(this);

Как и так

когда мои кнопки нажимаются, я читаю текст с кнопкивот нажали

Мое действие выполнено выглядит так

public void actionPerformed(ActionEvent e) {
    // add your event handling code here
    if (e.getSource()==numb){

        String button = (String)e.getActionCommand();

        display.setText(button); 

        System.out.println(button);

    }else if (e.getSource()==opButton){

        System.out.println(button);
    }

}

1 Ответ

2 голосов
/ 25 августа 2011

Ну, вы можете напечатать текст любой кнопки, на которую вы нажали:

JButton button = (JButton) e.getSource();
String text = button.getText();
display.setText(text);
System.out.println(text);

... но не совсем понятно, что вы пытаетесь сделать.В частности, вы переназначали значение numb несколько раз - оно не может ссылаться на все этих кнопок.Возможно, вы захотите дать всем кнопкам общую команду действия, например, «цифра».Тогда вы можете использовать:

private static final String DIGIT_COMMAND = "digit";

// Assign the action command of each button as DIGIT_COMMAND...

...

public void actionPerformed(ActionEvent e) {
    if (DIGIT_COMMAND.equals(e.getActionCommand()) {
        JButton button = (JButton) e.getSource();
        String text = button.getText();
        display.setText(text);
        System.out.println(text);
    } else {
        // Handle other commands
    }
}
...