如何通过单击按钮更改标签文本?
Posted
技术标签:
【中文标题】如何通过单击按钮更改标签文本?【英文标题】:How to change a labels text by clicking a button? 【发布时间】:2021-11-16 07:32:32 【问题描述】:如果您回答,请发布示例代码。 我的代码是:
package Program;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Screen extends JFrame
public Screen()
setVisible(true);
setSize(600,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setAlwaysOnTop(true);
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.setLayout(null);
JLabel lbl = new JLabel();
lbl.setForeground(Color.green);
lbl.setBounds(300,100,60,60);
JButton btn1 = new JButton();
btn1.setText("Click");
btn1.setBackground(Color.MAGENTA);
btn1.setBounds(200,200,70,50);
btn1.addActionListener();
panel.add(btn1);
panel.add(lbl);
add(panel);
setContentPane(panel);
ActionListener kk = new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
lbl.setText("blablabla, I know its local, but I don´t know how to fix it");
;
在我的 Main 方法/类中,我创建了这个类的一个对象,请帮助。 我已经说过我知道它是本地的,但我不知道如何解决它。
【问题讨论】:
【参考方案1】:您没有在ActionListener
对象和按钮之间建立链接。
试试这个:
package Program;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Screen extends JFrame
public Screen()
setVisible(true);
setSize(600,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setAlwaysOnTop(true);
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.setLayout(null);
JLabel lbl = new JLabel();
lbl.setForeground(Color.green);
lbl.setBounds(300,100,60,60);
JButton btn1 = new JButton();
btn1.setText("Click");
btn1.setBackground(Color.MAGENTA);
btn1.setBounds(200,200,70,50);
ActionListener kk = new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
lbl.setText("blablabla, I know its local, but I don´t know how
to fix it");
;
btn1.addActionListener(kk);
panel.add(btn1);
panel.add(lbl);
add(panel);
setContentPane(panel);
或者很快:
btn1.addActionListener(new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
lbl.setText("blablabla, I know its local, but I don´t know how
to fix it");
);
【讨论】:
以上是关于如何通过单击按钮更改标签文本?的主要内容,如果未能解决你的问题,请参考以下文章