how to get the variable name of a JLabel when its clicked

how to get the variable name of a JLabel when its clicked

By : FuzzyTom
Date : November 21 2020, 01:01 AM
it fixes the issue There is no such simple way. Think about it: A single JLabel object could be referenced by many separate variable names:
code :
JLabel label1 = new JLabel("test");
JLabel label2 = label1;
JLabel label3 = label2;
frame.getContentPane().add(new JLabel("test"));
frame.getContentPane().getComponent(0).addMouseListener(new MouseAdapter() { ... });
try {
    for (java.lang.reflect.Field f : yourObject.getClass().getDeclaredFields()) {
        if (f.get(yourObject) == label1) {
} catch (Throwable t) {
    throw new RuntimeException(t);

Share : facebook icon twitter icon
only mouse clicked event of jlabel update jlabel text property properly

only mouse clicked event of jlabel update jlabel text property properly

By : jared mays
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further You must ensure that any changes to Swing UI components are performed on the Event Dispatch Thread. Here are two suggestions for accomplishing this:
code :
  int delay = 1000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
  new Timer(delay, taskPerformer).start();
new SwingWorker<Void, String>() {
  // Called by the background thread.
  public Void doInBackground() {
    for (int i=0; i<100; ++i) {
      // Do work.  Periodically publish String data.
      publish("Job Number: " + i);

  // Called on the Event Dispatch Thread.
  protected void process(List<String> chunks) {
    // Update label text.  May only want to set label to last
    // value in chunks (as process can potentially be called
    // with multiple String values at once).
    for (String text : chunks) {
Timer class moving a JLabel through the JFrame! Why JLabel text can not be variable?

Timer class moving a JLabel through the JFrame! Why JLabel text can not be variable?

By : Chen Eric
Date : March 29 2020, 07:55 AM
I hope this helps . The reason that label.setText("x = "+ x) causes the text to remain still but yet the line label.setText("x = ") causes the label to move across the frame is that revalidate() is called on the JLabel. This will cause the correct behavior applying the current layout manager's rules (namely BorderLayout in this case).
When the text does not change, revalidate() is never called.
code :
label.setText("x = "+ x)
getting JLabel to refresh after button clicked

getting JLabel to refresh after button clicked

By : Nyonyintono David
Date : March 29 2020, 07:55 AM
hop of those help? i think you forgot to add an ActionListener to your newSet Button, below you'll find a working example. I commented the two lines with the icon, so uncomment and try it.
code :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

 * @author ottp
 * @version 1.0
public class CardPanel extends JPanel {

    final private JLabel label;
    private JButton addSetButton;
    private JPanel actives, optionsPanel,cardPanel, flashCardsPanel, bottomPanel;

    public CardPanel() {

        actives = new JPanel();
        actives.setPreferredSize(new Dimension(1000, 50));

        label   = new JLabel();

        optionsPanel = new JPanel();
        optionsPanel.setPreferredSize(new Dimension(200, 350));

        cardPanel = new JPanel();
        cardPanel.setPreferredSize(new Dimension(580, 350));

        flashCardsPanel = new JPanel();
        flashCardsPanel.setPreferredSize(new Dimension(200, 350));

        bottomPanel = new JPanel();
        bottomPanel.setLayout(new FlowLayout());
        bottomPanel.setPreferredSize(new Dimension(1000, 400));

        this.addSetButton = new JButton("Add Set");
        addSetButton.setPreferredSize(new Dimension(150, 30));
        optionsPanel.add(addSetButton, BorderLayout.WEST);
        addSetButton.addActionListener(new ButtonListener());


    public class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            label.setText("Active set: " + e.getActionCommand());

            if(e.getSource().equals(addSetButton)) {


    private void getSetInfo() {
        String newSetName = 
                JOptionPane.showInputDialog(cardPanel, "Enter the name of your set", JOptionPane.INFORMATION_MESSAGE);

        JButton newSet = new JButton(newSetName);
        newSet.addActionListener(new ButtonListener());

Detect which JLabel is clicked

Detect which JLabel is clicked

By : KKhelawy
Date : March 29 2020, 07:55 AM
To fix this issue I have a JLabel[10] and I want to detect which label has been clicked and print which label of the label that has been clicked. , 1
code :
public class JavaLabels extends JFrame {

    private JLabel[] jLabelArr;
    private JPanel jLabelPanel = new JPanel();

    public JavaLabels() {
        setLayout(new FlowLayout());
        jLabelArr = new JLabel[10];
        for (int i = 0; i < 10; i++) {

            jLabelArr[i] = new JLabel(new ImageIcon("resources/image"));

            jLabelArr[i].addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
        setSize(400, 600);

    private void onMouseClicked(MouseEvent e) {
        for (int i = 0; i < 10; i++)
            if (e.getSource() == jLabelArr[i]) {
                System.out.println("Label" + i + "was clicked");

    public static void main(String[] args) {
        new JavaLabels();
which JLabel has been clicked?

which JLabel has been clicked?

By : Mitchell Curtis
Date : March 29 2020, 07:55 AM
Does that help You use getSource to get a refrence to the object which is clicked on:
Related Posts Related Posts :
  • Content autocomplete in spring tool suite 4
  • Super Noob Help ~ MouseEvent/Frame
  • Making one project with dependencies stand-alone in Eclipse (Java)
  • Jsoup- getting certain attributes from website
  • MongoDB, how to make a link between collections with JAVA code
  • Overriding an abstract method means class abstract class or not in java?
  • Bukkit teleport - nullPointerException
  • How to check if a Float variable is negative in java
  • Servlet: Cannot forward after response has been committed
  • sql query to select a specific cell in excel
  • How to make new picture when mouse dragged in java
  • Use Constants interface in GWT Project
  • Setting size of a JPanel in GroupLayout
  • Construct a map from two equal size arrays
  • Implementing Read-Write Locks with Double-Checked Locking
  • Disable NO_BUTTON from JOptionPane Java if a condition is true
  • UDP multiple socket
  • Android Threading: This Handler class should be static or leaks might occur
  • The type org.openqa.selenium.firefox.FirefoxDriver is not accessible
  • Limitations (drawbacks) of java programming language?
  • Error: ')' expected Error: illegal start of expression
  • TableRowSorter use LookAndFeel of TableHeader, but own Comparator
  • Difference between @GeneratedValue and @GenericGenerator
  • Design Scenario: Smartphone class and will have derived classes like IPhone,AndroidPhone,WindowsMobilePhone can be even
  • Java date parsing without separators?
  • how to map an array of custom type from postgres to java using hibernate
  • Why hibernate always call "update" statement after using "select" statement in MySQL?
  • An interview topic: What can go wrong with this code?
  • How do I regex remove whitespace and newlines from a text, except for when they are in a json's string?
  • How to turn off Preferences > Compiles > User External Build?
  • how to convert arraylist to string array with all items in double quote
  • PMD+Maven+JAVA Error:: Can't find resource rulesets/comments.xml. Make sure the resource is a valid file or URL or is on
  • How to extend AbstractScheduledService.Scheduler
  • Primefaces tabview: set Active Index after some counting
  • Need help in Regex to exclude splitting string within "
  • Get header from HttpUrlConnection object
  • encoding xlsx as base64 and send it as an attachment
  • How to acess HttpServletRequest in Jaas login module in Tomcat
  • How to implement a basic pointer
  • Java Swing Exit Icon?
  • Why onNext has no effect
  • IntelliJ Idea 2018.2 no option for importing gradle project
  • Remove a negative element from an array w/o array.copy
  • Could this prevent overflow in Java?
  • In Java Swing, can I receive Caret events in real time?
  • I need help not using brute force when using JFrames and DrawWindows
  • How do I refactor ArrayList<MyClass> into MyClassLIst?
  • My program keeps saying that the method cannot be resolved
  • BubbleSort -my code returns random addresses
  • JavaFX components inside HTML?
  • Character in Java game not responding
  • Working around access denied in a FileWalking Tree in Java7
  • How to avoid if/else when using multple suppliers?
  • How to pass object from table cell editor to Table Model?
  • Paypal Sandbox payment state pending
  • sejda-console.bat passing parameters with spaces
  • Multiple Consumers Spring Kafka
  • Bitbucket pipeline: environmental variables in build.gradle file not recognized
  • Java static enum method to return a default enum value
  • What is the complexity of empty for loop?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org