2011-07-05 112 views

回答

7
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(); 
    } 
} 
+0

從另一個類可以創建'Test'的對象作爲'Test t = new Test(); t.getLabel()。setText(「更改標籤文本」);'。我已經爲標籤創建了getters-setters(getLabel())? –

+1

工作美麗!希望我可以upvote 10倍 –

6

使用setText(str)方法JLabel來動態改變顯示的文字。在按鈕的actionPerform這樣寫:

jLabel.setText("new Value"); 

一個簡單的演示代碼將是:

JFrame frame = new JFrame("Demo"); 
    frame.setLayout(new BorderLayout()); 
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
    frame.setSize(250,100); 

    final JLabel label = new JLabel("flag"); 
    JButton button = new JButton("Change flag"); 
    button.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      label.setText("new value"); 
     } 
    }); 

    frame.add(label, BorderLayout.NORTH); 
    frame.add(button, BorderLayout.CENTER); 
    frame.setVisible(true); 
相關問題