Reading text from One variable multiy JButtons
I Have one JButton variable which i used to create different buttons with different number on it
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);
Like So
when my buttons get clicked i wane read the text from the button thats got pressed
My actionPerformed looks like 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);
}
}
Well you can print the text of whatever button was clicked on like this:
JButton button = (JButton) e.getSource();
String text = button.getText();
display.setText(text);
System.out.println(text);
... but it's not really clear what you're trying to do. In particular, you've reassigned the value of numb
several different times - it can't refer to all of those buttons. You might want to give all of the buttons a common action command, e.g. "digit". Then you can use:
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
}
}
精彩评论