无法从另一个JFrame获取变量信息 [英] trouble obtaining variable info from another JFrame

查看:98
本文介绍了无法从另一个JFrame获取变量信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建类似于JOptionPane的东西,但是会从输入中获得多个(3)个变量。所以我想我会使用一个单独的JFrame,它有三个textFields。我使用Get和Set之类的访问方法将变量从一个类获取到另一个类,但我得到一个空指针excpetion。我想我会以错误的方式获取变量,并且很难找到可行的解决方案。

I am trying to create something similar to a JOptionPane but will obtain more than one(3) variables from input. So I figured I would use a separate JFrame that had three textFields. I used access methods like Get and Set to get the variables from one class to another, but I am getting a null pointer excpetion. I figure I am going about getting the variables the wrong way, and am having a hard time trying to find a viable solution.

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


推荐答案

再次,为什么不使用JOptionPane?许多人误解了这些有用的结构,认为它们只能用于最简单的gui,当没有任何东西可以离真相更远时。使用它们获得最大功率的关键是要理解大多数JOptionPane方法中的第二个参数是 Object ,并且这个Object可以是一个非常复杂甚至是大的JPanel拥有其他组件,包括其他JPanels,JTables,JComboBoxes等...我用它来向用户呈现复杂的模态输入对话框,就像你想要做的那样。然后,当处理了JOptionPane并且程序流返回到您的程序时,您将查询JOptionPane中显示的复杂GUI的属性并提取其信息。再次,请查看我的链接此处,以确切了解我的意思。

Again, why not use a JOptionPane? Many people misunderstand these useful constructs, thinking that they can only be used for the most simple gui's when nothing could be further from the truth. The key in using these for maximal power is to understand that the second parameter in most JOptionPane methods is Object, and that this Object can be a very complex and even a large JPanel that holds other components including other JPanels, JTables, JComboBoxes, etc... I've used this to present complex modal input dialogs to the user, much like what you're trying to do. Then when the JOptionPane has been dealt with and program flow returns to your program, you query the properties of the complex GUI that was displayed in the JOptionPane and extract its information. Again, please check out my link here, to see exactly what I mean.

例如,对于您的情况,如果您想要一个包含3个JTextField的JPanel来获取您的b-number,名字和姓氏信息,只需创建一个包含JTextField及其相应JLabel的JPanel: / p>

For instance, for your situation, if you wanted a JPanel that held 3 JTextFields to get your b-number, first Name, and last name information, simply create a JPanel that holds the JTextFields and their corresponding JLabels:

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中显示它所以:

Then show it in a JOptionPane like so:

PlayerEditorPanel playerEditorPanel = new PlayerEditorPanel();


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

然后从JPanel中提取必要的信息:

and then extract the necessary information from the 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();
         }
      });
   }
}

这篇关于无法从另一个JFrame获取变量信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆