I want to display the history of the button pressed by swing.

Asked 2 years ago, Updated 2 years ago, 122 views

If I add "Botton5" to the code below, how do I add a history of what buttons I have pressed when I press Botton5?

import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;

public class SwingTest extensions JFrame implements ActionListener {
  JLabel label;

  public static void main(String[]args) {
    SwingTest test = new SwingTest ("SwingTest");

    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.setVisible(true);
  }

  SwingTest (String title) {
    setTitle(title);
    setBounds(10,10,300,200);

    label = new JLabel("");
    label.setHorizontalAlignment (JLabel.CENTER);

    JButton btn1 = new JButton("Button1");
    btn1.addActionListener(this);
    btn1.setActionCommand("Button1");

    JButton btn2 = new JButton("Button2");
    btn2.addActionListener(this);
    btn2.setActionCommand("Button2");

    JButton btn3 = new JButton("Button3");
    btn3.addActionListener(this);
    btn3.setActionCommand("Button3");

    JButton btn4 = new JButton("Button4");
    btn4.addActionListener(this);
    btn4.setActionCommand("Button4");

    JPanelp = new JPanel();
    p.add(btn1);
    p.add(btn2);
    p.add(btn3);
    p.add(btn4);

    getContentPane().add(p, BorderLayout.CENTER);
    getContentPane().add(label, BorderLayout.PAGE_END);
  }

  public void actionPerformed (ActionEvent) {
    String cmd = e.getActionCommand();

    if(cmd.equals("Button1"){
      label.setText("open");
    } else if(cmd.equals("Button2")}
      label.setText("print");
    } else if(cmd.equals("Button3")}
      label.setText("rename");
    } else if(cmd.equals("Button4")}
      label.setText("move");
    }
  }
}

java swing

2022-09-30 11:21

1 Answers

Prepare fields such as ArrayList to keep the history.

private static list<String>history=new ArrayList<>();;

Once the button is clicked, you can add a label to it and display it.

public void actionPerformed (ActionEvent) {
    String cmd = e.getActionCommand();
    history.add(cmd);
    if(cmd.equals("Button1"){
        label.setText("open");
    } else if(cmd.equals("Button2"){
        label.setText("print");
    } else if(cmd.equals("Button3")){
        label.setText("rename");
    } else if(cmd.equals("Button4")){
        label.setText("move");
    } else if(cmd.equals("Button 5")}
        label.setText(history.toString());
    }
}

I think it's better to think about how to display it.


2022-09-30 11:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.