如何有效地添加 Java 成员按钮



我对java很陌生,正在创建一个电话簿应用程序,允许用户按姓名或电话进行搜索。您可以按名称搜索并获取用户电话号码,反之亦然。我已经使用 2D 数组对用户进行了硬编码,我知道这不是很有效。我想创建一个按钮,弹出打开一个JDialog,让用户输入姓名和电话号码,然后自动将用户名和号码放入数组中。我知道为了做到这一点,我可能需要使用集合,比如 arrayList 或其他东西,但我想看看是否有人可以引导我朝着正确的最有效的方向前进。这是我到目前为止的代码

public class PhoneBookGUI implements ActionListener{
JLabel name; 
JLabel number;
JLabel searchOptions;
JButton addButton; 
JTextField nameField;
JTextField numberField; 
JCheckBox ignoreCase; 
JRadioButton exactMatch; 
JRadioButton startsWithButton; 
JRadioButton endsWithButton;
String[][] phonelist = {
{"Connor Littleton", "707-799-0194"},
{"Justin Littleton", "707-799-0182"},
{"Zia Thach", "707-123-4567"},
{"Mike Hawk", "707-123-1234"},
{"Sal Hal", "707-111-1111"}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new PhoneBookGUI(); 
}
});
}
PhoneBookGUI(){
JFrame frame = new JFrame("Phone-Book GUI"); 
frame.setSize(300, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new GridLayout(0,1));
frame.setLocationRelativeTo(null);
name = new JLabel("Name:");
number = new JLabel("Number:");
searchOptions = new JLabel("Search Options:");
nameField = new JTextField(10);
numberField = new JTextField(10);
ignoreCase = new JCheckBox("Ignore Case");
exactMatch = new JRadioButton("Exact Match");
startsWithButton = new JRadioButton("Starts With");
endsWithButton = new JRadioButton("Ends With");
JPanel buttonPane = new JPanel(); 
addButton = new JButton("Add Contact");
buttonPane.add(addButton);
ButtonGroup bg = new ButtonGroup(); 
nameField.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
numberField.setText(lookUpName(nameField.getText()));
}
});
numberField.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
nameField.setText(lookUpNumber(numberField.getText()));
} 
});
addButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonactionPerformed(evt);
}
});
bg.add(exactMatch);
bg.add(startsWithButton);
bg.add(endsWithButton);
frame.add(name);
frame.add(nameField);
frame.add(number);
frame.add(numberField);
frame.add(new JLabel());
frame.add(buttonPane);
frame.add(searchOptions);
frame.add(ignoreCase);
frame.add(new JLabel());
frame.add(exactMatch);
frame.add(startsWithButton);
frame.add(endsWithButton);
}

public void addButtonactionPerformed(java.awt.event.ActionEvent evt){
addButtonMenu menu = new addButtonMenu(new javax.swing.JFrame(), true); 
menu.setVisible(true);
}
public String lookUpNumber(String n){
for (int i = 0; i < phonelist.length; i++) {
if(phonelist[i][1].equals(n)){
return phonelist[i][0];
}
}
return "Not Found"; 
}
public String lookUpName(String n){
for (int i = 0; i < phonelist.length; i++) {
if(startsWithButton.isSelected()){
if(ignoreCase.isSelected()){
if(phonelist[i][0].toLowerCase().startsWith(n.toLowerCase()))
return phonelist [i][1]; 
}else{
if(phonelist[i][0].startsWith(n))
return phonelist[i][1];
}
}
else if(endsWithButton.isSelected()){
if(ignoreCase.isSelected()){
if(phonelist[i][0].toLowerCase().endsWith(n.toLowerCase()))
return phonelist[i][1]; 
} else {
if(phonelist[i][0].endsWith(n))
return phonelist[i][1]; 
}
}
else {
if(ignoreCase.isSelected()) {
if(phonelist[i][0].toLowerCase().equals(n.toLowerCase()))
return phonelist[i][1]; 
} else {
if(phonelist[i][0].equals(n))
return phonelist[i][1]; 
}
}
}
return "not found"; 
}
@Override 
public void actionPerformed(ActionEvent ae){
}

}

这是我为 JDialog 提供的另一页

public class addButtonMenu extends javax.swing.JDialog {
/**
* Creates new form addButtonMenu
*/
public addButtonMenu(java.awt.Frame parent, boolean modal) {
super(parent, modal);
setLocationRelativeTo(parent);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {
addFirstName = new javax.swing.JLabel();
firstNameField = new javax.swing.JTextField();
addLastName = new javax.swing.JLabel();
lastNameField = new javax.swing.JTextField();
addMemberButton = new javax.swing.JButton();
cancelMember = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Add Contact");
setSize(new java.awt.Dimension(500, 200));
getContentPane().setLayout(new java.awt.GridLayout(3, 1, 5, 5));
addFirstName.setText("Full Name:");
getContentPane().add(addFirstName);
getContentPane().add(firstNameField);
addLastName.setText("Phone Number:");
getContentPane().add(addLastName);
lastNameField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lastNameFieldActionPerformed(evt);
}
});
getContentPane().add(lastNameField);
addMemberButton.setText("Submit");
getContentPane().add(addMemberButton);
cancelMember.setText("Cancel");
cancelMember.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelMemberActionPerformed(evt);
}
});
getContentPane().add(cancelMember);
pack();
}// </editor-fold>                        
private void lastNameFieldActionPerformed(java.awt.event.ActionEvent evt) {                                              
// TODO add your handling code here:
}                                             
private void cancelMemberActionPerformed(java.awt.event.ActionEvent evt) {                                             
this.dispose();
}                                            
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(addButtonMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(addButtonMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(addButtonMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(addButtonMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
addButtonMenu dialog = new addButtonMenu(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify                     
private javax.swing.JLabel addFirstName;
private javax.swing.JLabel addLastName;
private javax.swing.JButton addMemberButton;
private javax.swing.JButton cancelMember;
private javax.swing.JTextField firstNameField;
private javax.swing.JTextField lastNameField;
// End of variables declaration                   

}

使用哈希表的概念,它将键/值对存储在哈希表中。使用哈希表时,可以指定用作键的对象(电话号码(以及要链接到该键的值(名称(。然后对键进行哈希处理,并将生成的哈希代码用作将值存储在表中的索引。 使用以下链接使用集合的想法,以便轻松为您排序和搜索值,

JOptionPane - 输入对话框程序

您可以使用数组,但处理它会很痛苦,因为 2D 数组以相同的数据类型存储值,而电话号码应解析为int(通过正则表达式验证(,名称用作字符串。无论如何,使用给定的链接来探索 2D 数组在 JDialog 中的工作原理。

http://forums.devshed.com/java-help/958183-form-data-2d-array-output-text-post2924712.html

最新更新