3

JOptionPane に似たものを作成しようとしていますが、入力から複数の変数を取得します。そこで、3 つの textFields を持つ別の JFrame を使用することにしました。Get や Set などのアクセス メソッドを使用して、あるクラスから別のクラスに変数を取得しましたが、null ポインターの例外が発生しています。私は変数を間違った方法で取得しようとしていると考えており、実行可能な解決策を見つけるのに苦労しています。

public class Instructor()
{
public void Insert(JPanel panel)
{
panel.removeAll();
panel.updateUI();
//ResultSet resultSet = null;
    String bNum = "";
String fName = "";  
String lName = "";


    InsertFrame insert = new InsertFrame();
    insert.setVisible(true);
    bNum = insert.getBNumber();
fName = insert.getFirstName();  
lName = insert.getLastName();

    /*
    String bNum = JOptionPane.showInputDialog("Enter BNumber");
    String fName = JOptionPane.showInputDialog("Enter First Name");
    String lName = JOptionPane.showInputDialog("Enter Last Name");*/
try
{
    connection = DriverManager.getConnection(URL);
    insertNewInstructor = connection.prepareStatement(
    "INSERT INTO Instructor" + "(BNumber, FirstName, LastName)" + "VALUES           (?,?,?)");
}catch(SQLException sqlException){
    sqlException.printStackTrace();
    System.exit(1);
}//end catch


try
{
    insertNewInstructor.setString(1, bNum);
    insertNewInstructor.setString(2, fName);
    insertNewInstructor.setString(3, lName);
    insertNewInstructor.executeUpdate();
}catch(SQLException sqlException){
        sqlException.printStackTrace();
}//end of catch
finally
{
    close();
}//end 

Display(panel);

 }//end of insert method
 }//end of class Instructor

class InsertFrame extends JFrame implements ActionListener
{

private JTextField bNumber;
private JLabel bNum;
private JTextField firstName;
private JLabel fName;
private JTextField lastName;
private JLabel lName;
private JButton ok;
private JPanel fieldPanel;
    private JPanel buttonPanel;
    private String bNumr = "";
    private String frName = "";
    private String lsName = "";

public InsertFrame()
{
bNumber = new JTextField(10);
bNum = new JLabel();
firstName = new JTextField(10);
fName = new JLabel();
lastName = new JTextField(10);
lName = new JLabel();

fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(3,2,4,4));
bNum.setText("B-Number:");
fieldPanel.add(bNum);
fieldPanel.add(bNumber);
fName.setText("First Name:");
fieldPanel.add(fName);
fieldPanel.add(firstName);
lName.setText("Last Name:");
fieldPanel.add(lName);
fieldPanel.add(lastName);
    ok = new JButton("Ok");
    ok.addActionListener(this);

this.add(fieldPanel, BorderLayout.CENTER);
this.add(buttonPanel,BorderLayout.SOUTH);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(310,300);
this.setResizable(false);
this.setVisible(false);
}//end of constructor
public void actionPerformed(ActionEvent e)
{
bNumr = bNumber.getText();
frName = firstName.getText();
lsName = lastName.getText();
}//end of method actionPerformed

public void setBNumber(String number)
{
bNumr = number;
}//end of setBNumber
public String getBNumber()
{
return bNumr;
}//end of getBNumber method
public void setFirstName(String firstN)
{
frName = firstN;
}//end of setFirstName
public String getFirstName()
{
return frName;
}//end of getFirstName method
public void setLastName(String lastN)
{
lsName = lastN;
}//end of setLastName method
public String getLastName()
{
return lsName;
}//end of getLastName method
}//end of InsertFrame
4

1 に答える 1

8

繰り返しますが、JOptionPane を使用してみませんか? 多くの人は、これらの便利な構文を誤解しており、真実からかけ離れたものがない場合にのみ、最も単純な GUI にしか使用できないと考えています。これらを最大限に活用するための鍵は、ほとんどの JOptionPane メソッドの 2 番目のパラメーターが であるObjectこと、およびこのオブジェクトが非常に複雑であり、他の JPanel、JTable、JComboBox などを含む他のコンポーネントを保持する大規模な JPanel である可能性があることを理解することです。これを使用して、あなたがやろうとしているのと同じように、複雑なモーダル入力ダイアログをユーザーに提示しました。次に、JOptionPane が処理され、プログラム フローがプログラムに戻ったら、JOptionPane に表示された複雑な GUI のプロパティをクエリし、その情報を抽出します。繰り返しますが、ここで私のリンクをチェックしてください、私の言いたいことを正確に理解するために。

たとえば、あなたの状況で、3 つの JTextField を保持する JPanel で b 番号、名、姓の情報を取得したい場合は、JTextField とそれに対応する JLabel を保持する JPanel を作成するだけです。

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

class PlayerEditorPanel extends JPanel {
   enum FieldTitle {
      B_NUMBER("B Number"), FIRST_NAME("First Name"), LAST_NAME("Last Name");
      private String title;

      private FieldTitle(String title) {
         this.title = title;
      }

      public String getTitle() {
         return title;
      }
   };

   private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
   private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
   private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();

   public PlayerEditorPanel() {
      setLayout(new GridBagLayout());
      setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Player Editor"),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));
      GridBagConstraints gbc;
      for (int i = 0; i < FieldTitle.values().length; i++) {
         FieldTitle fieldTitle = FieldTitle.values()[i];
         gbc = createGbc(0, i);
         add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
         gbc = createGbc(1, i);
         JTextField textField = new JTextField(10);
         add(textField, gbc);

         fieldMap.put(fieldTitle, textField);
      }
   }

   private GridBagConstraints createGbc(int x, int y) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;

      gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
      gbc.fill = (x == 0) ? GridBagConstraints.BOTH
            : GridBagConstraints.HORIZONTAL;

      gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
      gbc.weightx = (x == 0) ? 0.1 : 1.0;
      gbc.weighty = 1.0;
      return gbc;
   }

   public String getFieldText(FieldTitle fieldTitle) {
      return fieldMap.get(fieldTitle).getText();
   }

}

次に、次のように JOptionPane に表示します。

PlayerEditorPanel playerEditorPanel = new PlayerEditorPanel();


int result = JOptionPane.showConfirmDialog(null, playerEditorPanel,
    "Edit Player JOptionPane", JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.PLAIN_MESSAGE);

次に、JPanel から必要な情報を抽出します。

        if (result == JOptionPane.OK_OPTION) {
           for (PlayerEditorPanel.FieldTitle fieldTitle : PlayerEditorPanel.FieldTitle
                 .values()) {
              textArea.append(String.format("%10s: %s%n",
                    fieldTitle.getTitle(),
                    playerEditorPanel.getFieldText(fieldTitle)));
           }
        }

メインクラスは次のようになります。

import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;

@SuppressWarnings("serial")
public class ComplexOptionPane extends JPanel {
   private PlayerEditorPanel playerEditorPanel = new PlayerEditorPanel();
   private JTextArea textArea = new JTextArea(12, 30);

   public ComplexOptionPane() {
      textArea.setEditable(false);
      textArea.setFocusable(false);
      textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
      JPanel bottomPanel = new JPanel();
      bottomPanel.add(new JButton(new AbstractAction("Get Player Information") {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            int result = JOptionPane.showConfirmDialog(null, playerEditorPanel,
                  "Edit Player JOptionPane", JOptionPane.OK_CANCEL_OPTION,
                  JOptionPane.PLAIN_MESSAGE);
            if (result == JOptionPane.OK_OPTION) {
               for (PlayerEditorPanel.FieldTitle fieldTitle : PlayerEditorPanel.FieldTitle
                     .values()) {
                  textArea.append(String.format("%10s: %s%n",
                        fieldTitle.getTitle(),
                        playerEditorPanel.getFieldText(fieldTitle)));
               }
            }
         }
      }));
      setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      setLayout(new BorderLayout(5, 5));
      add(new JScrollPane(textArea), BorderLayout.CENTER);
      add(bottomPanel, BorderLayout.PAGE_END);
   }

   private static void createAndShowGui() {
      ComplexOptionPane mainPanel = new ComplexOptionPane();

      JFrame frame = new JFrame("ComplexOptionPane");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
于 2012-04-14T01:42:46.220 に答える