本文介绍了在正在运行的应用程序上Swing JLabel文本更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Swing窗口,其中包含一个文本框按钮和一个名为flag的 JLabel
。根据我点击按钮后的输入,标签应该从标志变为某个值。
I have a Swing window which contains a button a text box and a JLabel
named as flag. According to the input after I click the button, the label should change from flag to some value.
如何在同一窗口中实现这一目标?
How to achieve this in the same window?
推荐答案
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}
这篇关于在正在运行的应用程序上Swing JLabel文本更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!