Pages

Get JLabel text

Source code below will show you how to get text from JLabel.

*****************************************************************
COMPLETE SOURCE CODE FOR : GetJLabelText.java
*****************************************************************


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;

import java.awt.BorderLayout;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class GetJLabelText implements ActionListener
{
//Create button with text ( Click me to get JLabel text )
JButton button=new JButton("Click me to get JLabel text");

//Create JLabel with text ( I LOVE YOU )
JLabel label=new JLabel("I LOVE YOU");

//Create a window with title ( Get JLabel text )
JFrame frame=new JFrame("Get JLabel text");

public GetJLabelText()
{
//Add action listener to button
button.addActionListener(this);

//Set JFrame layout to BorderLayout
frame.setLayout(new BorderLayout());

//Add created label into JFrame
frame.add(label,BorderLayout.CENTER);

//Add created button into JFrame
frame.add(button,BorderLayout.SOUTH);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(400,500);

//Make JFrame visible
frame.setVisible(true);
}

public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
//Method getText will get text from label
JOptionPane.showMessageDialog(frame,"JLabel text is : "+label.getText());
}
}

public static void main(String[]args)
{
GetJLabelText gjbt=new GetJLabelText();
}
}


*****************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************
Related Posts Plugin for WordPress, Blogger...