在Java的Swing庫中,JFrame是一個頂層容器,用于創建圖形用戶界面。要在JFrame中傳遞數據,可以使用以下方法:
public class DataModel {
private String text;
public DataModel(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DataTransferExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Data Transfer Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel label = new JLabel("Enter data:");
label.setBounds(10, 20, 80, 25);
panel.add(label);
JTextField textField = new JTextField(20);
textField.setBounds(100, 20, 165, 25);
panel.add(textField);
JButton button = new JButton("Submit");
button.setBounds(10, 60, 80, 25);
panel.add(button);
JLabel resultLabel = new JLabel();
resultLabel.setBounds(10, 100, 365, 25);
panel.add(resultLabel);
}
}
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String inputText = textField.getText();
DataModel dataModel = new DataModel(inputText);
resultLabel.setText(dataModel.getText());
}
});
現在,當用戶在文本字段中輸入數據并點擊“提交”按鈕時,數據將傳遞到結果標簽并顯示出來。這就是在Java JFrame中傳遞數據的基本方法。根據實際需求,可以對這個示例進行修改和擴展。