简体   繁体   English

从另一个类更改Java卡布局中的活动“卡”

[英]Changing the active “card” in a Java card layout, from another class

I'm trying to build a small inventory application in Java, that switches views (or pages) based on the card layout. 我正在尝试用Java构建一个小型清单应用程序,该应用程序会根据卡片布局来切换视图(或页面)。 For the standard change the user will use the menu at the top of the app, and that works fine. 对于标准更改,用户将使用应用程序顶部的菜单,并且效果很好。

But, one one of my screens the user will enter an item ID number to check. 但是,我的一个屏幕中,用户将输入要检查的项目ID号。 If that ID number is not found in the database, the app should switch to the New Item page. 如果在数据库中找不到该ID号,则应用程序应切换到“新建项目”页面。 This is where I'm at a loss. 这是我不知所措的地方。 I've tried to change the currently viewed card but nothing seems to be getting it. 我试图更改当前查看的卡,但似乎什么也没得到。

Forgive me if this is a basic question (as well as poorly written Java :) ), I'm teaching myself Java as I write this app. 如果这是一个基本问题,请原谅我(以及Java的文字不好:)),我在编写此应用程序时正在自学Java。 Attached I'm adding part of the main class (InventoryTrackingSystem) and the GUI class (the one that is trying to change the view). 附带的是,我添加了主类(InventoryTrackingSystem)和GUI类(试图更改视图的类)的一部分。

/ * ** * * The MAIN class * ** * ** * *** / / * ** * * MAIN类* ** * ** * *** /

package inventorytrackingsystem;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.rmi.*;

public class InventoryTrackingSystem implements ItemListener {
  JPanel mainPanel;
  JFrame frame;

  JPanel cards = new JPanel(new CardLayout());; //a panel that uses CardLayout

  final static String MAINPANEL = "Main";
  final static String CHECKITEMSPANEL = "Check Items";
  final static String NEWITEMPANEL = "New Item";
  final static String CHECKOUTITEMPANEL = "Check Out Item";
  final static String ITEMINFOPANEL = "Item Information";
  final static String LISTALLITEMSPANEL = "List All Items";
  JPanel comboBoxPane;
  private JComboBox cb;
  static String comboBoxItems[] = {MAINPANEL,CHECKITEMSPANEL,NEWITEMPANEL,CHECKOUTITEMPANEL,ITEMINFOPANEL,LISTALLITEMSPANEL};

  public static void main(String[] args) {
    InventoryTrackingSystem ITS = new InventoryTrackingSystem();
    /* Use an appropriate Look and Feel */
    try {
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
      ex.printStackTrace();
    } catch (IllegalAccessException ex) {
      ex.printStackTrace();
    } catch (InstantiationException ex) {
      ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
    /* Turn off metal's use of bold fonts */
    UIManager.put("swing.boldMetal", Boolean.FALSE);

    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
//    javax.swing.SwingUtilities.invokeLater(new Runnable() {
//      public void run() {
        ITS.createAndShowGUI();
//      }
//    });

  }

  public void addComponentToPane(Container pane){
    //Put the JComboBox in a JPanel to get a nicer look.
    comboBoxPane = new JPanel(); //use FlowLayout
    cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);
    cb.setVisible(false);

    //Create the "cards".
    JPanel main = new guiBuilder().buildGui("main");
    JPanel checkItems = new guiBuilder().buildGui("checkItems");
    JPanel newItems = new guiBuilder().buildGui("newItems");
    JPanel checkOutItems = new guiBuilder().buildGui("checkOutItems");
    JPanel itemInfo = new guiBuilder().buildGui("itemInfo");
    JPanel listAllItems = new guiBuilder().buildGui("listAllItems");

    //Create the panel that contains the "cards".
    cards = new JPanel(new CardLayout());
    cards.add(main, MAINPANEL);
    cards.add(checkItems, CHECKITEMSPANEL);
    cards.add(newItems, NEWITEMPANEL);
    cards.add(checkOutItems, CHECKOUTITEMPANEL);
    cards.add(itemInfo, ITEMINFOPANEL);
    cards.add(listAllItems, LISTALLITEMSPANEL);

    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(cards, BorderLayout.CENTER);
  }

  public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
  }

  /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private void createAndShowGUI() {
      //Create and set up the window.
      frame = new JFrame("Inventory Tracking System");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.setLayout(new BorderLayout());
      Menu m1 = new Menu("Options");

      MenuItem mi1_0 = new MenuItem("Main Page");
        mi1_0.setActionCommand("main");
        mi1_0.addActionListener(new menuListener());

      MenuItem mi1_1 = new MenuItem("Check Item");
        mi1_1.setActionCommand("checkItem");
        mi1_1.addActionListener(new menuListener());
      MenuItem mi1_2 = new MenuItem("Add New Item");
        mi1_2.setActionCommand("addItem");
        mi1_2.addActionListener(new menuListener());
      MenuItem mi1_3 = new MenuItem("List All Items");
        mi1_3.setActionCommand("listAllItems");
        mi1_3.addActionListener(new menuListener());
      MenuItem mi1_4 = new MenuItem("Check Out Item");
        mi1_4.setActionCommand("checkOutItem");
        mi1_4.addActionListener(new menuListener());
      MenuItem mi1_5 = new MenuItem("Exit");
        mi1_5.setActionCommand("exit");
        mi1_5.addActionListener(new menuListener());

      Menu m2 = new Menu("Help");
      MenuItem mi2_0 = new MenuItem("About");
        mi2_0.setActionCommand("about");
        mi2_0.addActionListener(new menuListener());

      m1.add(mi1_0);
      m1.add(mi1_1);
      m1.add(mi1_2);
      m1.add(mi1_3);
      m1.add(mi1_4);
      m1.add(mi1_5);

      m2.add(mi2_0);

      MenuBar mb = new MenuBar();
      frame.setMenuBar(mb);
      mb.add(m1);
      mb.add(m2);

      //Create and set up the content pane.
      //InventoryTrackingSystem setGUI = new InventoryTrackingSystem();
      addComponentToPane(frame.getContentPane());

      //Display the window.
      frame.pack();
      frame.setVisible(true);

      frame.setSize(780, 830);

      frame.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent we){
          System.exit(0);
        }
        public void windowClosed(WindowEvent we){
          System.exit(0);
        }
      });

    }

    class menuListener implements ActionListener{
      public void actionPerformed(ActionEvent ev){
        String thisAction=ev.getActionCommand();

        if(thisAction.equals("main")){
          cb.setSelectedItem(MAINPANEL);
        }else if(thisAction.equals("checkItem")){
          //change GUI
          cb.setSelectedItem(CHECKITEMSPANEL);
        }else if(thisAction.equals("addItem")){
          //change GUI
          cb.setSelectedItem(NEWITEMPANEL);
        }else if(thisAction.equals("checkOutItem")){
          //change GUI
          cb.setSelectedItem(CHECKOUTITEMPANEL);
        }else if(thisAction.equals("listAllItems")){
          //change GUI
          cb.setSelectedItem(LISTALLITEMSPANEL);
        }else if(thisAction.equals("exit")){
          System.exit(0);
        }else if(thisAction.equals("about")){
          JOptionPane.showMessageDialog(frame, "About This App");
        }
      }
    }

  public void swapView(String s){
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, s);
  }
}

/ * ** * * The GUI class * ** * ** * *** / / * ** * * GUI类* ** * ** * *** /

package inventorytrackingsystem;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Image.*;
import java.awt.image.BufferedImage.*;
import javax.imageio.*;
import com.sun.jimi.core.*;


public class guiBuilder {
  JLabel itemIdLabel;
  JTextField itemID;
  JButton checkIt;
  JButton getSignature;
  mySqlStuff sql=new mySqlStuff();

  public JPanel buildGui(String guiType){
    JPanel thisGUI;
    if(guiType.equals("main")){
      thisGUI=mainGUI();
    }else if(guiType.equals("checkItems")){
      thisGUI=checkItemsGUI();
    }else if(guiType.equals("newItems")){
      thisGUI=newItemsGUI();
    }else if(guiType.equals("checkOutItems")){
      thisGUI=checkOutItemsGUI();
    }else if(guiType.equals("itemInfo")){
      thisGUI=itemInfoGUI();
    }else if(guiType.equals("listAllItems")){
      thisGUI=listAllItemsGUI();
    }else{
      thisGUI=mainGUI();
    }

    return thisGUI;
  } /* close buildGui() Method */

  private JPanel mainGUI(){
    JPanel thisPanel = new JPanel();

    return thisPanel;
  }

  private JPanel checkItemsGUI(){
    JPanel thisPanel = new JPanel();

    JPanel itemSection=new JPanel();
    JPanel exitSection=new JPanel();

    itemIdLabel=new JLabel("Enter/Scan Item ID");
    itemID=new JTextField(4);
    itemID.addKeyListener(new myItemIdListener());

    checkIt=new JButton("Check Item");
    checkIt.addActionListener(new myItemCheckListener());

    itemSection.add(itemIdLabel);
    itemSection.add(itemID);
    itemSection.add(checkIt);

    JButton exitButton=new JButton("Exit");
    exitButton.addActionListener(new exitButtonListener());

    exitSection.add(exitButton);

    thisPanel.add(itemSection);
    thisPanel.add(exitSection);

    return thisPanel;
  }

  private JPanel newItemsGUI(){
    JPanel thisPanel = new JPanel();

    return thisPanel;
  }

  private JPanel checkOutItemsGUI(){
    JPanel thisPanel = new JPanel();

    return thisPanel;
  }

  private JPanel itemInfoGUI(){
    JPanel thisPanel = new JPanel();

    return thisPanel;
  }

  private JPanel listAllItemsGUI(){
    JPanel thisPanel = new JPanel();

    return thisPanel;
  }

  class myItemIdListener implements KeyListener{
    boolean keyGood=false;
    public void keyPressed(KeyEvent keyEvent){
      int keyCode=keyEvent.getKeyCode();
      if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
        keyGood=true;
      }
    }
    public void keyReleased(KeyEvent keyEvent){
      int keyCode=keyEvent.getKeyCode();
      if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
        printIt("Released",keyEvent);
      }else if(keyCode==10){
        checkIt.doClick();
      }
    }
    public void keyTyped(KeyEvent keyEvent){
      int keyCode=keyEvent.getKeyCode();
      if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
        printIt("Typed",keyEvent);
      }
    }
    private void printIt(String title,KeyEvent keyEvent){
      int keyCode=keyEvent.getKeyCode();
      String keyText=KeyEvent.getKeyText(keyCode);
      String currentData;

      if(title.equals("Pressed")){
        keyGood=true;
      }else if(title.equals("Released")){
        System.out.println(title+ " -> "+keyCode+" / "+keyText);
      }else if(title.equals("Typed")){
        System.out.println(title+ " -> "+keyCode+" / "+keyText);
      }

      try{
        String text=itemID.getText();
        if(text.length()==4){
          checkIt.doClick();
        }else{
          System.out.println("currentlLength: "+itemID.getText().length());
        }
      }catch(Exception ex){
        ex.printStackTrace();
      }
    }
  }

/****  THIS IS WHERE THE SWAP VIEW IS CALLED  ****/
  class myItemCheckListener implements ActionListener{
    public void actionPerformed(ActionEvent ev){
      String itemNum=itemID.getText();
      itemID.setText("");
      System.out.println("Checking ID#: "+itemNum);
      ArrayList checkData=new ArrayList(sql.checkInventoryData(itemNum));
      if(checkData.get(0).toString().equals("[NULL]")){
        System.out.println("New Item -> "+checkData.get(0).toString());
        InventoryTrackingSystem ITS = new InventoryTrackingSystem();
        ITS.swapView("NEWITEMPANEL");
      }else{
        System.out.println("Item Exists -> "+checkData.get(0).toString());

      }
      System.out.println(checkData);
    }
  }
  class signaturePadButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent ev){
      signaturePadStuff signature = new signaturePadStuff();
      while(signature.imageFileMoved==false){
        // wait for the signature to be collected and the image moved to the server.
      }
      System.out.println(signature.newFileName);
    }
  }

  class exitButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent ev){
      System.exit(0);
    }
  }

  /** Returns an ImageIcon, or null if the path was invalid. */
  protected ImageIcon createImageIcon(String path, String description) {
    java.net.URL imgURL = getClass().getResource(path);
    if(imgURL != null){
      return new ImageIcon(imgURL, description);
    }else{
      System.err.println("Couldn't find file: " + path);
      return null;
    }
  }

  class submitItemButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent ev){
      String errorMsg = "";
      String[] formResults = new String[25];

    }
  }

  class clearFormButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent ev){
      return;
    }
  }

}

With this code in your actionPerformed method... 在您的actionPerformed方法中使用此代码...

InventoryTrackingSystem ITS = new InventoryTrackingSystem();
ITS.swapView("NEWITEMPANEL");

...you are calling swapView on a new instance of InventoryTrackingSystem (which is not the one you created in main and for which the UI is showing on the screen). ...您正在InventoryTrackingSystem的新实例上调用swapView(这不是您在main中创建的实例,并且UI会显示在屏幕上)。

-edited- -编辑-

you need an instance of InventoryTrackingSystem in your action listener you can for example store it in a member variable of myItemCheckListener like this: 您需要在动作侦听器中使用InventoryTrackingSystem的实例,例如,可以将其存储在myItemCheckListener的成员变量中,如下所示:

class myItemCheckListener implements ActionListener{

    private InventoryTrackingSystem its;

    // constructor takes its instance as argument
    public myItemCheckListener(InventoryTrackingSystem its){
        // ...assigns it to the member variable
        this.its = its;
    }

    public void actionPerformed(ActionEvent ev){
        // call swapView on the correct instance of InventoryTrackingSystem
        its.swapView()
    }
}

Of course, since your action listener is created in guiBuilder.buildGui() / checkItemsGUI() you will need the ITS instance there, too. 当然,由于您的动作侦听器是在guiBuilder.buildGui()/ checkItemsGUI()中创建的,因此您也将需要ITS实例。

BTW: It is not really necessary to create new guiBuilder instances like this: 顺便说一句:创建这样的新guiBuilder实例并不是真正必要的:

JPanel main = new guiBuilder().buildGui("main");
...
JPanel listAllItems = new guiBuilder().buildGui("listAllItems");

instead you could: 相反,您可以:

guiBuilder builder = new guiBuilder();
builder.buildGui("main");
builder.build("whatever");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM