Forum Stats

  • 3,826,102 Users
  • 2,260,598 Discussions
  • 7,896,788 Comments

Discussions

Button Text into Label Text

866915
866915 Member Posts: 3
edited Jun 6, 2011 11:25AM in Java Programming
Write a program that has three buttons, each displaying a different text that when pressed will display the text on the button in a text box. That was my task, and here is my code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.String;

public class MouseClick
{
Label objLabel1;
Label objLabel2;
Label objLabel3;
public static void main(String[] args)
{
MouseClick MC= new MouseClick();
}

public MouseClick()
{
JFrame f = new JFrame("JFrame");
final JPanel p1 = new JPanel();
Button a = new Button("A");
a.setBounds(20,30,40,40);
JButton b = new JButton("B");
b.setBounds(85,75, 40, 40);
JButton c = new JButton("C");
c.setBounds(130, 120, 40, 40);
p1.add(a);
p1.add(b);
p1.add(c);
f.getContentPane().add(p1);

objLabel1 = new Label("A");
objLabel1.setBounds(20,75,40,40);
objLabel2 = new Label("B");
objLabel2.setBounds(85,120,40,40);
objLabel3 = new Label("C");
objLabel3.setBounds(130,185,40,40);
p1.add(objLabel1);
objLabel1.setVisible(false);
p1.add(objLabel2);
objLabel2.setVisible(false);
p1.add(objLabel3);
objLabel3.setVisible(false);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
f.setSize(400,400);
f.setVisible(true);
}

public class MyMouseListener extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
//String stra = me.getActionCommand ("A");
//objLabel1.setText (stra);
//String strb = me.getActionCommand ("B");
//objLabel1.setText (strb);
//String strc = me.getActionCommand ("C");
//objLabel1.setText (strc);
Label objLabel1;
Label objLabel2;
Label objLabel3;
objLabel1.setVisible(true);
objLabel2.setVisible(true);
objLabel3.setVisible(true);
}
}
}


I originally used Strings, but it wasn't working. right now the error i'm getting is that the objLabels havent been initialized. Help? thanks!
Tagged:

Answers

  • 823824
    823824 Member Posts: 18
    edited Jun 6, 2011 11:02AM
    see the three labels objLabel1 and other two.

    you haven't did

    objLabel1 = new Label("");

    thats why not initialized error. Instantiating.........

    Edited by: Vinayjgeorge on Jun 6, 2011 8:32 PM
  • 823824
    823824 Member Posts: 18
    edited Jun 6, 2011 11:25AM
    Hi

    I just went through the complete code.

    * You can use one label and set its text on each press.
    * I didn't see action listener with your code.

    * use this for buttons to add action listener so that it can detect the button press.

    b.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent arg0)
    {
    objLabel1 = new Label("B"); // this will set the text to label.
    }
    });

    Edited by: Vinayjgeorge on Jun 6, 2011 8:55 PM
This discussion has been closed.