我正在嘗試為 Java 中的一個類撰寫 GUI 代碼,并且出現了一些組件,但有些沒有。準確地說,JTextBoxes 和 JButton 出現了,但 JLabels 和 JComboBoxes 沒有出現。另一個問題是我試圖洗掉 JComboBox 并放入 JTextBox,但是當我嘗試鍵入血型(例如 O-)并將其注冊到物件 Donor d1 中時,它給了我 NumberFormatException。我檢查了 Donor 類,屬性 bloodType 是一個字串,所以我不明白為什么它會給我這個錯誤
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DonationForm {
DonorTableImpl donorDB;
public DonationForm(DonorTableImpl donorDB){
this.donorDB=donorDB;
JFrame formFrame=new JFrame("Complete the form");
//TextBox Fields
JTextField id=new JTextField(10);
id.setBounds(140,190,150,30);
JTextField firstName=new JTextField(10);
firstName.setBounds(140,160,150,30);
JTextField lastName=new JTextField(10);
lastName.setBounds(140,130,150,30);
JTextField password=new JTextField(10);
password.setBounds(140,100,150,30);
JTextField address=new JTextField(10);
address.setBounds(140,70,150,30);
//Labels for TextBoxes
JLabel idLabel=new JLabel("Id");
JLabel firstNameLabel=new JLabel("First Name");
JLabel lastNameLabel=new JLabel("Last Name");
JLabel passwordLabel=new JLabel("Password");
JLabel addressLabel=new JLabel("Address");
JLabel bloodTypeLabel=new JLabel("Blood Type");
//ComboBox
String[] blood={"A ","A-","B ","B-","AB ","AB-","O ","O-"};
JComboBox bloodType=new JComboBox(blood);
bloodType.setSelectedIndex(0);
//Submit button
JButton submit=new JButton("SUBMIT");
submit.setBounds(190,300,100,30);
//Add all components on frame
formFrame.add(idLabel);
formFrame.add(id);
formFrame.add(firstNameLabel);
formFrame.add(firstName);
formFrame.add(lastNameLabel);
formFrame.add(lastName);
formFrame.add(passwordLabel);
formFrame.add(password);
formFrame.add(addressLabel);
formFrame.add(address);
formFrame.add(bloodTypeLabel);
formFrame.add(bloodType);
formFrame.add(submit);
formFrame.setSize(500,500);
bloodType.setVisible(true);
bloodType.setLayout(null);
formFrame.setLayout(null);
formFrame.setVisible(true);
//Create an Object with data gotten from TextBoxes when SUBMIT button is clicked
submit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Donor d1=new Donor(Integer.parseInt(id.getText()),firstName.getText(),
lastName.getText(),password.getText(),
address.getText(), blood[bloodType.getSelectedIndex()]);
donorDB.save(d1);
}
});
}
}
uj5u.com熱心網友回復:
您需要將框架的布局設定為 null 之外的其他內容,以便渲染所有組件。
代替
formFrame.setLayout(null);
用這個:
formFrame.setLayout(new FlowLayout(FlowLayout.CENTER, 1000, 10));
uj5u.com熱心網友回復:
通過使用formFrame.setLayout(null);
您選擇不
我建議更多地了解如何在 Swing 中布局組件。例如,請參閱本教程。有了那里的技能,您甚至可能想進一步改善您的JFrame.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482329.html
