Friday, 6 September 2013

ActionListener not working in Java

ActionListener not working in Java

I have created a JPanel over JFrame and added a JButon and JLabel to the
JPanel. But the ActionlListener does not seems work. When i click on
JButton, Nothing Happens. Please someone Help me. Thanks in Advance. Here
is my code
public class Trials implements ActionListener {
JButton scoreButton;
JLabel score;
JPanel MyPanel;
int ScoreAmount=0;
public JPanel createPanel()
{
JPanel MyPanel =new JPanel();
MyPanel.setLayout(null);
MyPanel.setSize(50, 50);
MyPanel.setBackground(Color.cyan);
JLabel score =new JLabel(""+ScoreAmount);
score.setSize(50, 50);
score.setLocation(250,50);
score.setForeground(Color.red);
MyPanel.add(score);
JButton scoreButton =new JButton("add");
scoreButton.setSize(100, 50);
scoreButton.setLocation(100,50);
scoreButton.setBackground(Color.red);
scoreButton.addActionListener(this);
MyPanel.add(scoreButton);
MyPanel.setOpaque(true);
MyPanel.setVisible(true);
return MyPanel;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==scoreButton)
{
ScoreAmount = ScoreAmount+1;
score.setText(""+ScoreAmount);
}
}
public static void display()
{
JFrame MyFrame = new JFrame();
Trials tr =new Trials();
MyFrame.setContentPane(tr.createPanel());
MyFrame.setSize(500, 500);
MyFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
display();
}
});
}
}

No comments:

Post a Comment