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.
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
581 PHP ssh2_scp_send fails to send files as intended
611 GDB gets version error when attempting to debug with the Presense SDK (IDE)
578 Understanding How to Configure Google API Key
915 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.