我只是試圖製作員工時鐘。我有一個數字鍵盤0-9和一個文本字段。我希望能夠點擊數字,數字將出現在文本字段中。這似乎很容易,但我找不到任何答案。jbutton更改文本字段的文本
我正在使用netbeans,並在設計中創建了Jframe的設計。
我向所有按鈕添加了動作事件。
我打電話像Btn0(0就可以了按鈕,BTN1,等等等等,每一個按鈕
我只是試圖製作員工時鐘。我有一個數字鍵盤0-9和一個文本字段。我希望能夠點擊數字,數字將出現在文本字段中。這似乎很容易,但我找不到任何答案。jbutton更改文本字段的文本
我正在使用netbeans,並在設計中創建了Jframe的設計。
我向所有按鈕添加了動作事件。
我打電話像Btn0(0就可以了按鈕,BTN1,等等等等,每一個按鈕
在您的按鈕上的按鈕添加動作監聽器第一個(雙擊在GUI Designer :)):
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Set text by calling setText() method for your textfield
textfield.setText("Desired text");
}
});
問候。
創建一個可以被所有按鈕共享的動作。喜歡的東西:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ButtonCalculator extends JFrame implements ActionListener
{
private JButton[] buttons;
private JTextField display;
public ButtonCalculator()
{
display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 5));
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++)
{
String text = String.valueOf(i);
JButton button = new JButton(text);
button.addActionListener(this);
button.setMnemonic(text.charAt(0));
button.setBorder(new LineBorder(Color.BLACK));
buttons[i] = button;
buttonPanel.add(button);
}
getContentPane().add(display, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
display.replaceSelection(source.getActionCommand());
}
public static void main(String[] args)
{
ButtonCalculator frame = new ButtonCalculator();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
你需要找回上動作事件被觸發將JButton,然後從追加將JButton到JTextField中檢索的文本。這裏是短演示:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class EClock extends JFrame
{
JTextField tf;
public void createAndShowGUI()
{
setTitle("Eclock");
Container c = getContentPane();
tf = new JTextField(10);
JPanel cPanel = new JPanel();
JPanel nPanel = new JPanel();
nPanel.setLayout(new BorderLayout());
nPanel.add(tf);
cPanel.setLayout(new GridLayout(4,4));
for (int i =0 ; i < 10 ; i++)
{
JButton button = new JButton(String.valueOf(i));
cPanel.add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
String val = ((JButton)evt.getSource()).getText();
tf.setText(tf.getText()+val);
}
});
}
c.add(cPanel);
c.add(nPanel,BorderLayout.NORTH);
setSize(200,250);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
EClock ec = new EClock();
ec.createAndShowGUI();
}
});
}
}
什麼你嘗試這麼遠嗎?向我們展示一些代碼 – jamp 2013-04-30 16:03:31