Create an object of JButton in action performed method and cast event.getSource to JButton.
e.g.
JButton button = (JButton) event.getSource();
String str = button.getText();
System.out.println(str);
문제
My program is supposed to output the the text of the selected JButton to the console. The problem I am running into is that I don't understand how to get the source object to recognize the getText() method so that I can do the above.
Here is the Error Code:
Error: cannot find symbol
symbol: method getText()
location: variable source of type java.lang.Object
Here is the Program Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelExample extends JFrame implements ActionListener{
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;
JButton b6;
String response;
public void makePanels() {
Container c = getContentPane();
b1 = new JButton("Item 1");
b2 = new JButton("Item 2");
b3 = new JButton("Item 3");
b4 = new JButton("Item 4");
b5 = new JButton("Item 5");
b6 = new JButton("Item 6");
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(new JButton("Ok"));
p1.add(new JButton("Cancel"));
p1.add(new JLabel(response));
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(new JLabel("Make a Selection"));
JPanel p3 = new JPanel();
p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS));
p3.add(b1);
p3.add(b2);
p3.add(b3);
JPanel p4 = new JPanel();
p4.setLayout(new BoxLayout(p4, BoxLayout.Y_AXIS));
p4.add(b4);
p4.add(b5);
p4.add(b6);
c.setLayout(new BorderLayout());
c.add(p1, BorderLayout.SOUTH);
c.add(p2, BorderLayout.NORTH);
c.add(p3, BorderLayout.WEST);
c.add(p4,BorderLayout.EAST);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
String text = source.getText();
System.out.println(text);
}
public static void main(String[] args) {
PanelExample frame = new PanelExample();
frame.makePanels();
frame.setSize(200, 250);
}
}
Throughout all the posts I have searched I have not found one that will help me with my specific problem. Thanks for the Help.
해결책
Create an object of JButton in action performed method and cast event.getSource to JButton.
e.g.
JButton button = (JButton) event.getSource();
String str = button.getText();
System.out.println(str);