0
我有問題,關於如何在單擊按鈕時將jxtfield的值從一幀傳遞到第二幀中的jtextfield。將jtextfield值從一個類傳遞到另一個類
下面的示例中,在nett工資文本字段中輸入值後,單擊添加按鈕後,該值將被傳遞到第二個框架的nett工資文本字段。
框架1.我試圖添加actionlistener到我的按鈕來獲取文本,但我如何設置它在第二幀?感謝任何人都可以提供一些建議和幫助。
public class Frame1 extends JFrame{
public Frame1() {
JPanel guiPanel = new JPanel(new GridBagLayout());
JLabel Nett = new JLabel("Nett Wage: ");
final JTextField nettNameTextField = new JTextField(10);
JButton addButton = new JButton("Add");
JPanel fields = new JPanel(new GridBagLayout());
GridBagConstraints labelGBC = new GridBagConstraints();
labelGBC.insets = new Insets(10, 3, 3, 3);
GridBagConstraints fieldGBC = new GridBagConstraints();
fieldGBC.insets = new Insets(10, 3, 3, 3);
GridBagConstraints titleGBC = new GridBagConstraints();
fieldGBC.gridwidth = GridBagConstraints.REMAINDER;
fields.add(Nett, labelGBC);
fields.add(nettNameTextField, fieldGBC);
JPanel buttons = new JPanel(new GridBagLayout());
GridBagConstraints addButtonGBC = new GridBagConstraints();
addButtonGBC.insets = new Insets(40, 3, 3, 3);
cancelButtonGBC.gridwidth = GridBagConstraints.REMAINDER;
buttons.add(addButton, addButtonGBC);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
guiPanel.add(fields, gbc);
guiPanel.add(buttons, gbc);
add(guiPanel, BorderLayout.CENTER);
/*addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = nettNameTextField.getText();
}
});*/
第2幀如何設置文本框中的值?
public class Frame2 extends JFrame {
public Frame2() {
JPanel guiPanel = new JPanel(new GridBagLayout());
JLabel nett = new JLabel("Nett Wage: ");
JTextField nettNameTextField = new JTextField(10);
JPanel fields = new JPanel(new GridBagLayout());
GridBagConstraints labelGBC = new GridBagConstraints();
labelGBC.insets = new Insets(10, 3, 3, 3);
GridBagConstraints fieldGBC = new GridBagConstraints();
fieldGBC.insets = new Insets(10, 3, 3, 3);
//GridBagConstraints titleGBC = new GridBagConstraints();
fieldGBC.gridwidth = GridBagConstraints.REMAINDER;
JPanel savingspanel = new JPanel(new GridBagLayout());
GridBagConstraints totallabelsGBC = new GridBagConstraints();
totallabelsGBC.insets = new Insets(10, 3, 3, 3);
GridBagConstraints totalfieldGBC = new GridBagConstraints();
totalfieldGBC.insets = new Insets(10, 3, 3, 3);
totalfieldGBC.gridwidth = GridBagConstraints.REMAINDER;
savingspanel.add(nett, labelGBC);
savingspanel.add(nettNameTextField, fieldGBC);
add(guiPanel, BorderLayout.CENTER);
}
}
}
也許他不應該將完整的Frame1引用傳遞給構造函數。我寧願讓實現Frame1的接口使用特殊的get方法,並將此接口傳遞給Frame2構造函數。 – sk2212
如果你只是傳遞接口,你仍然傳遞對象。這是一個很好的觀點,但在我看來,這是一個不必要的擴展,只會使代碼更加複雜,以至於程序員可以在幾秒鐘內使用一種方法。 – christopher