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");
}
}
}
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.
367 To Limit Column Values to Strings in a String List Using sqlalchemy
342 Memory layouts learned in theory don't work out as expected when actually printed as addresses.
356 I want to create an array of sequences from "1" to a specified number.
346 Who developed the "avformat-59.dll" that comes with FFmpeg?
354 I have saved several codes written in python to a visual studio file.
© 2023 OneMinuteCode. All rights reserved.