我有一个Swing窗口,其中包含一个按钮,一个文本框和一个JLabel命名为flag的窗口。根据我单击按钮后的输入,标签应从标志更改为某个值。
JLabel
如何在同一个窗口中实现这一目标?
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(); } }