我正在显示我编写的用于在单击按钮时更改文本的代码。现在我试图通过再次单击该按钮来获取默认文本,但无法这样做。请指教。
import javax.swing.*;
import java.awt.event.*;
public class Actions extends JFrame implements ActionListener{
JPanel pnl=new JPanel();
ImageIcon ic1=new ImageIcon("/home/mudit/Downloads/duke.png");
JButton btn1=new JButton("Click",ic1);
JTextArea ta=new JTextArea(5,37);
public static void main(String[]args)
{
Actions gui=new Actions();
}
public Actions()
{
super("Swing Window");
setSize(500,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
btn1.setHorizontalTextPosition(JButton.CENTER);
btn1.setVerticalTextPosition(JButton.BOTTOM);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
pnl.add(btn1);
pnl.add(ta);
btn1.setEnabled(true);
ta.setText("Button is enabled");
btn1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==btn1)
{
ta.setText("Button is Clicked");
}
}
}
最佳答案
您可以使用 if
语句检查按钮的文本:
if (event.getSource() == btn1) {
if (ta.getText().equals("Button is enabled")) {
ta.setText("Button is Clicked");
} else {
ta.setText("Button is enabled");
}
}
关于java - 单击后更改按钮文本,然后使用 JAVA ActionEvent 再次单击后恢复更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718228/