コード例 #1
0
  public CALCView() {
    Toolkit.getDefaultToolkit();

    Constants.Get_Splash().Show_Splash_Not_Valid();

    new CALCViewFrame();
  }
コード例 #2
0
  @Override
  public void initComponent() {
    myMode = Registry.get("ide.tooltip.mode");

    myIsEnabled = Registry.get("ide.tooltip.callout");
    myIsEnabled.addListener(
        new RegistryValueListener.Adapter() {
          @Override
          public void afterValueChanged(RegistryValue value) {
            processEnabled();
          }
        },
        ApplicationManager.getApplication());

    Toolkit.getDefaultToolkit()
        .addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);

    ActionManager.getInstance()
        .addAnActionListener(
            new AnActionListener.Adapter() {
              @Override
              public void beforeActionPerformed(
                  AnAction action, DataContext dataContext, AnActionEvent event) {
                hideCurrent(null, action, event);
              }
            },
            ApplicationManager.getApplication());

    processEnabled();
  }
コード例 #3
0
 // Adds a new keybinding equal to the character provided and the default super key (ctrl/cmd)
 private static void bind(int Character) {
   frame
       .getRootPane()
       .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
       .put(
           KeyStroke.getKeyStroke(Character, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
           "console");
 }
コード例 #4
0
  // Define method to return commands.
  private void buildFrame(int width, int height) {
    // Set JFrame title.
    setTitle("Communicator");

    // Initialize and set policies for JScrollPane(s).
    receiverScrollPane =
        setScrollPaneProperties(new JScrollPane(receiver = new JTextAreaPanel(COL, ROW)));
    senderScrollPane =
        setScrollPaneProperties(new JScrollPane(sender = new JTextAreaPanel(COL, ROW)));

    // Disable editability of receiver JTextAreaPanel.
    receiver.setEditable(false);

    // Initialize JButtonPanel.
    button = new JButtonPanel();

    // Define and initialize JButton(s).
    buildButtons();

    // Set panel size.
    setSize(width, height);

    // Set JPanel Layout.
    getContentPane().setLayout(new BorderLayout());

    // Add a JTextAreaPanel(s).
    getContentPane().add(receiverScrollPane, BorderLayout.NORTH);
    getContentPane().add(button, BorderLayout.CENTER);
    getContentPane().add(senderScrollPane, BorderLayout.SOUTH);

    // Build JMenuBar.
    buildMenu();

    // Build JButton action listeners.
    buildButtonActionListeners();

    // Set the screen and display dialog window in relation to screen size.
    dim = tk.getScreenSize();
    setLocation((dim.width / 100), (dim.height / 100));

    // --------------------- Begin Window ActionListener ---------------------/

    // Add window listener to the frame.
    addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent closingEvent) {
            // Exit on window frame close.
            System.exit(0);
          } // End of windowClosing() method.
        }); // End of addWindowListener() method for JFrame.

    // Set resizeable window off.
    setResizable(false);

    // Display the JFrame to the platform window manager.
    show();
  } // End of buildFrame() method.
コード例 #5
0
 public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
   if ((getLength() + str.length()) <= size) {
     super.insertString(offs, str, a);
   } else {
     System.err.println(
         "Tried to make field "
             + (getLength() + str.length())
             + " characters long when max length is "
             + size);
     Toolkit.getDefaultToolkit().beep();
   }
 }
コード例 #6
0
  /**
   * Added this guy to make sure an image is loaded - ie no broken images. So far its used only for
   * images loaded off the disk (non-URL). It seems to work marvelously. By the way, it does the
   * same thing as MediaTracker, but you dont need to know the component its being rendered on. Rob
   */
  private void waitForImage() throws InterruptedException {
    int w = fImage.getWidth(this);
    int h = fImage.getHeight(this);

    while (true) {
      int flags = Toolkit.getDefaultToolkit().checkImage(fImage, w, h, this);

      if (((flags & ERROR) != 0) || ((flags & ABORT) != 0)) throw new InterruptedException();
      else if ((flags & (ALLBITS | FRAMEBITS)) != 0) return;
      Thread.sleep(10);
      // System.out.println("rise and shine...");
    }
  }
コード例 #7
0
 private void readInFile(String fileName) {
   try {
     FileReader r = new FileReader(fileName);
     area.read(r, null);
     r.close();
     currentFile = fileName;
     setTitle(currentFile + " - CoreyTextEditor");
     changed = false;
   } catch (IOException e) {
     Toolkit.getDefaultToolkit().beep();
     JOptionPane.showMessageDialog(this, "Editor can't find the file called " + fileName);
   }
 }
コード例 #8
0
  public boolean canDoClipBoardAction(Action action) {
    if (action == GUIPrism.getClipboardPlugin().getPasteAction()) {
      Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
      return (clipboard.getContents(null) != null);
    } else if (action == GUIPrism.getClipboardPlugin().getCutAction()
        || action == GUIPrism.getClipboardPlugin().getCopyAction()
        || action == GUIPrism.getClipboardPlugin().getDeleteAction()) {
      return (editor.getSelectedText() != null);
    } else if (action == GUIPrism.getClipboardPlugin().getSelectAllAction()) {
      return true;
    }

    return handler.canDoClipBoardAction(action);
  }
コード例 #9
0
  @Override
  public void insertString(
      FilterBypass filterBypass, int offset, String text, AttributeSet attributeSet)
      throws BadLocationException {
    text = trimHexadecimal(text);
    Document document = filterBypass.getDocument();
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(document.getText(0, document.getLength()));
    stringBuilder.insert(offset, text);

    if (isValidInput(stringBuilder.toString(), 0)) {
      super.insertString(filterBypass, offset, text, attributeSet);
    } else {
      Toolkit.getDefaultToolkit().beep();
    }
  }
コード例 #10
0
  /**
   * sets the number of characters per tab.
   *
   * @param charactersPerTab the characters per tab
   */
  public void setTabs(int charactersPerTab) {
    Font f = new Font(m_FontName, Font.PLAIN, m_FontSize);

    FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(f);
    int charWidth = fm.charWidth('w');
    int tabWidth = charWidth * charactersPerTab;

    TabStop[] tabs = new TabStop[MAX_TABS];

    for (int j = 0; j < tabs.length; j++) tabs[j] = new TabStop((j + 1) * tabWidth);

    TabSet tabSet = new TabSet(tabs);
    SimpleAttributeSet attributes = new SimpleAttributeSet();
    StyleConstants.setTabSet(attributes, tabSet);
    int length = getLength();
    setParagraphAttributes(0, length, attributes, false);
  }
コード例 #11
0
ファイル: NumbrixGUI.java プロジェクト: rainerlg90/Numbrix
    @Override
    public void replace(
        DocumentFilter.FilterBypass fp, int offset, int length, String string, AttributeSet aset)
        throws BadLocationException {
      Document doc = fp.getDocument();
      String oldText = doc.getText(0, doc.getLength());
      StringBuilder sb = new StringBuilder(oldText);
      sb.replace(offset, offset + length, oldText);

      int len = string.length();
      boolean isValidInteger = true;

      for (int i = 0; i < len; i++) {
        if (!Character.isDigit(string.charAt(i))) {
          isValidInteger = false;
          break;
        }
      }
      if (isValidInteger && verifyText(sb.toString())) {
        super.replace(fp, offset, length, string, aset);
      } else Toolkit.getDefaultToolkit().beep();
    }
コード例 #12
0
ファイル: Decipher.java プロジェクト: johnperry/MIRC1
 void centerFrame() {
   Toolkit t = getToolkit();
   Dimension scr = t.getScreenSize();
   setSize(scr.width / 2, scr.height / 2);
   setLocation(new Point((scr.width - getSize().width) / 2, (scr.height - getSize().height) / 2));
 }
コード例 #13
0
 /**
  * Sets the font for this component. This is overridden to update the cached font metrics and to
  * recalculate which lines are visible.
  *
  * @param font The font
  */
 public void setFont(Font font) {
   super.setFont(font);
   fm = Toolkit.getDefaultToolkit().getFontMetrics(font);
   textArea.recalculateVisibleLines();
 }
コード例 #14
0
// Define class.
public class StackTraceDialog extends JDialog implements ActionListener {
  // Define and initialize a default Toolkit.
  private Toolkit tk = Toolkit.getDefaultToolkit();

  // Define and initialize screen Dimension(s).
  private Dimension dim = tk.getScreenSize();

  // Define and initialize Container(s).
  private Container c = getContentPane();

  // Define and intialize phsyical size dimensions.
  int left = 0;
  int top = 0;
  int buttonWidth = 50;
  int buttonHeight = 25;
  int displayAreaWidth = dim.width - 400;
  int displayAreaHeight = dim.height - 400;
  int offsetMargin = 20;

  // The dialog width and height are derived from base objects.
  int dialogWidth = displayAreaWidth + offsetMargin;
  int dialogHeight = displayAreaHeight + buttonHeight + (3 * offsetMargin);

  // Define String(s).
  private String eStackTrace;

  // ---------------------------------/
  // Define AWT and Swing objects.
  // ---------------------------------/

  // Define and initialize JButton(s).
  private JButton okButton = new JButton("OK");

  // Define and initialize JTextArea(s).
  private JTextArea displayArea = new JTextArea();

  // Define Box(s).
  private Box displayBox;

  // ---------------------------- Constructor --------------------------------/

  // The class requires an owning frame and cannot be called from a default
  // constructor because none is defined in the JDialog class.
  public StackTraceDialog(Frame owner, String title, boolean modal) {
    // Call the constructor for JDialog.
    super(owner, modal);

    // The title argument is treated as overloaded because the stack trace
    // String is passed into an instance of this class by using it.  Then,
    // the String is assigned to a class level variable.
    eStackTrace = new String(title);

    // Call the buildDialogBox() method.
    buildDialogBox();
  } // End of StackTraceDialog constructor.

  // --------------------------- Begin Methods -------------------------------/

  // Method to build the dialog box for help.
  private void buildDialogBox() {
    // Set the JDialog window properties.
    setTitle("Stack Trace Detail");
    setResizable(false);
    setSize(dialogWidth, dialogHeight);

    // Append the stack trace output to the display area.
    displayArea.append(eStackTrace);

    // Create horizontal and vertical scrollbars for box.
    displayBox = Box.createHorizontalBox();
    displayBox = Box.createVerticalBox();

    // Add a JScrollPane to the Box.
    displayBox.add(new JScrollPane(displayArea));

    // Define behaviors of container.
    c.setLayout(null);
    c.add(displayBox);
    c.add(okButton);

    // Set scroll pane bounds.
    displayBox.setBounds(
        (dialogWidth / 2) - ((displayAreaWidth / 2) + 2),
        (top + (offsetMargin / 2)),
        displayAreaWidth,
        displayAreaHeight);

    // Set the behaviors, bounds and action listener for the button.
    okButton.setBounds(
        (dialogWidth / 2) - (buttonWidth / 2),
        (displayAreaHeight + offsetMargin),
        buttonWidth,
        buttonHeight);

    // Set the font to the platform default Font for the object with the
    // properties of bold and font size of 11.
    okButton.setFont(new Font(okButton.getFont().getName(), Font.BOLD, 11));

    // The class implements the ActionListener interface and therefore
    // provides an implementation of the actionPerformed() method.  When a
    // class implements ActionListener, the instance handler returns an
    // ActionListener.  The ActionListener then performs actionPerformed()
    // method on an ActionEvent.
    okButton.addActionListener(this);

    // Set the screen and display dialog window in relation to screen size.
    setLocation((dim.width / 2) - (dialogWidth / 2), (dim.height / 2) - (dialogHeight / 2));

    // Display JDialog.
    show();
  } // End of buildDialogBox method.

  // Class listener based on implementing ActionListener.
  public void actionPerformed(ActionEvent e) {

    this.setVisible(false);
    this.dispose();
  } // End of actionPerformed method.

  // ---------------------------- End Methods --------------------------------/

} // End of StackTraceDialog class.
コード例 #15
0
// Class definition.
public class JMessagingFrame extends JFrame {
  // -------------------------- Class Variables ------------------------------/

  // Define and initialize boolean(s).
  private boolean debugEnabled = false;
  private boolean fileOpen = false;

  // Define and initialize int JFrame constants.
  private final int END_X = 530;
  private final int END_Y = 460;

  // Define and initialize default column and row constants.
  private final int COL = 30;
  private final int ROW = 10;

  // Define and initialize a default Dimension for window frame sizing.
  private Dimension dim;

  // Define String(s).
  private String messageString;
  private String eString;

  // Toolkit is used in the sizing of the window.
  private Toolkit tk = Toolkit.getDefaultToolkit();

  // Define Java IO object(s).
  private File fileName = new File("");
  private File[] fileNames = new File[0];

  // Define Java streams.
  private BufferedReader input;
  private BufferedWriter output;
  private PrintWriter ePrintWriter;
  private StringWriter eStringWriter;

  // ---------------------------------/
  // Define AWT and Swing objects.
  // ---------------------------------/

  // Define JButton(s).
  private JButton sendButton;
  private JButton receiveButton;
  private JButton JDBCButton;
  private JButton fileButton;
  private JButton rSendButton;
  private JButton rReceiveButton;

  // Menu bar.
  private JMenuBar menuBar = new JMenuBar();

  // Menus.
  private JMenu file = new JMenu("File");
  private JMenu comm = new JMenu("Communicate");
  private JMenu data = new JMenu("Database");
  private JMenu help = new JMenu("Help");

  // Menu items.
  private JMenuItem menuItemNew = new JMenuItem("New");
  private JMenuItem menuItemOpen = new JMenuItem("Open");
  private JMenuItem menuItemClose = new JMenuItem("Close");
  private JMenuItem menuItemSave = new JMenuItem("Save");
  private JMenuItem menuItemSaveAs = new JMenuItem("Save As");
  private JMenuItem menuItemSend = new JMenuItem("Send");
  private JMenuItem menuItemReceive = new JMenuItem("Receive");
  private JMenuItem menuItemConnect = new JMenuItem("Connect");
  private JMenuItem menuItemSubmit = new JMenuItem("Run SQL");
  private JMenuItem menuItemExit = new JMenuItem("Exit");
  private JMenuItem menuItemHelp = new JMenuItem("About");

  // Checkbox menu items.
  private JCheckBoxMenuItem menuCheckBoxItemDebug = new JCheckBoxMenuItem("Debug");

  // Define JScrollPane(s).
  private JScrollPane senderScrollPane;
  private JScrollPane receiverScrollPane;

  // Define a JTextAreaPanel(s).
  private JTextAreaPanel receiver;
  private JButtonPanel button;
  private JTextAreaPanel sender;

  // ------------------------- Begin Constructor -----------------------------/

  /*
  || The constructors of the class are:
  || =========================================================================
  ||  Access     Constructor Type  Constructor
  ||  ---------  ----------------  -------------------------------------------
  ||  protected  Default          JMessagingFrame()
  ||  protected  Override         JMessagingFrame(int width,int height)
  */

  // -------------------------------------------------------------------------/

  // Define default constructor.
  protected JMessagingFrame() {
    // Initiate set methods.
    buildFrame(END_X, END_Y);
  } // End of default constructor.

  // -------------------------------------------------------------------------/

  // Define default constructor.
  protected JMessagingFrame(int width, int height) {
    // Initiate set methods.
    buildFrame(setMinimumWidth(width), setMinimumHeight(height));
  } // End of default constructor.

  // -------------------------- End Constructor ------------------------------/

  // --------------------------- Begin Methods -------------------------------/

  /*
  || The static main instantiates a test instance of the class:
  || =========================================================================
  ||  Return Type  Method Name                    Access     Parameter List
  ||  -----------  -----------------------------  ---------  -----------------
  ||  void         buildButtons()                 private
  ||  void         buildButtonActionListeners()   private
  ||  void         buildFrame()                   private    int width
  ||                                                         int height
  ||  JMenuBar     buildMenu()                    private
  ||  void         buildMenuActionListeners()     private
  ||  boolean      getDebugEnabled()              private
  ||  void         getMessage()                   private    JScrollPane in
  ||  void         getStackTraceDialog()          private
  ||  void         openFile()                     private
  ||  void         resetExceptionString()         private
  ||  void         setDebugEnabled()              private    boolean state
  ||  void         setExceptionPane()             private    String msg
  ||  void         setExceptionString()           private    Throwable eThrow
  ||  void         setMessage()                   private    JScrollPane out
  ||                                                         JScrollPane in
  ||  void         setMinimumHeight()             protected  int height
  ||  void         setMinimumWidth()              protected  int width
  ||  JScrollPane  setScrollPaneProperties()      private    JScrollPane pane
  */

  // ------------------- API Component Accessor Methods ----------------------/

  // Build JButtons.
  protected void buildButtons() {
    // Define and initialize JButton(s).
    sendButton = button.getButton("Send");
    receiveButton = button.getButton("Receive");
    JDBCButton = button.getButton("Connect");
    fileButton = button.getButton("Query");
    rSendButton = button.getButton("rSend");
    rReceiveButton = button.getButton("rReceive");
  } // End of setMessage() method.

  // -------------------------------------------------------------------------/

  // Method builds button action listeners.
  private void buildButtonActionListeners() {
    /*
    || Section adds action listeners for buttons:
    || ==========================================
    ||  - sendButton
    ||  - receiveButton
    ||  - JDBCButton
    ||  - fileButton
    ||  - rSendButton
    ||  - rReceiveButton
    */

    // Send button.
    sendButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Send message.
            setMessage(sender, receiver);
          } // End of actionPerformed() method.
        }); // End of sendButton action listener.

    // Receive button.
    receiveButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Receive message.
            getMessage(receiver);
          } // End of actionPerformed() method.
        }); // End of receiveButton action listener.

    // JDBC button.
    JDBCButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Print message until implemented.
            System.out.println("Database Connection .... ");
          } // End of actionPerformed() method.
        }); // End of JDBCButton action listener.

    // File button.
    fileButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Print message until implemented.
            System.out.println("SQL Submission .... ");
          } // End of actionPerformed() method.
        }); // End of fileButton action listener.

    // Send button.
    rSendButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Print message until implemented.
            System.out.println("Remote Sending .... ");
          } // End of actionPerformed() method.
        }); // End of rSendButton action listener.

    // Receive button.
    rReceiveButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Print message until implemented.
            System.out.println("Remote Receiving .... ");
          } // End of actionPerformed() method.
        }); // End of rReceiveButton action listener.
  } // End of buildButtonActionListeners() method.

  // -------------------------------------------------------------------------/

  // Define method to return commands.
  private void buildFrame(int width, int height) {
    // Set JFrame title.
    setTitle("Communicator");

    // Initialize and set policies for JScrollPane(s).
    receiverScrollPane =
        setScrollPaneProperties(new JScrollPane(receiver = new JTextAreaPanel(COL, ROW)));
    senderScrollPane =
        setScrollPaneProperties(new JScrollPane(sender = new JTextAreaPanel(COL, ROW)));

    // Disable editability of receiver JTextAreaPanel.
    receiver.setEditable(false);

    // Initialize JButtonPanel.
    button = new JButtonPanel();

    // Define and initialize JButton(s).
    buildButtons();

    // Set panel size.
    setSize(width, height);

    // Set JPanel Layout.
    getContentPane().setLayout(new BorderLayout());

    // Add a JTextAreaPanel(s).
    getContentPane().add(receiverScrollPane, BorderLayout.NORTH);
    getContentPane().add(button, BorderLayout.CENTER);
    getContentPane().add(senderScrollPane, BorderLayout.SOUTH);

    // Build JMenuBar.
    buildMenu();

    // Build JButton action listeners.
    buildButtonActionListeners();

    // Set the screen and display dialog window in relation to screen size.
    dim = tk.getScreenSize();
    setLocation((dim.width / 100), (dim.height / 100));

    // --------------------- Begin Window ActionListener ---------------------/

    // Add window listener to the frame.
    addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent closingEvent) {
            // Exit on window frame close.
            System.exit(0);
          } // End of windowClosing() method.
        }); // End of addWindowListener() method for JFrame.

    // Set resizeable window off.
    setResizable(false);

    // Display the JFrame to the platform window manager.
    show();
  } // End of buildFrame() method.

  // -------------------------------------------------------------------------/

  // Method builds menu components.
  private JMenuBar buildMenu() {
    // Add menus to the menu bar.
    menuBar.add(file);
    menuBar.add(comm);
    menuBar.add(data);
    menuBar.add(help);

    // Set mnemonics for menu selections.
    file.setMnemonic('F');
    comm.setMnemonic('C');
    data.setMnemonic('D');
    help.setMnemonic('H');

    // Menu items for file menu.
    file.add(menuItemNew);
    file.addSeparator();
    file.add(menuItemOpen);
    file.add(menuItemClose);
    file.addSeparator();
    file.add(menuItemSave);
    file.add(menuItemSaveAs);
    file.addSeparator();
    file.add(menuItemExit);

    // Menu items for comm menu.
    comm.add(menuItemSend);
    comm.add(menuItemReceive);

    // Menu items for comm menu.
    data.add(menuItemConnect);
    data.add(menuItemSubmit);

    // Set mnemonics for menu item selections for file menu.
    menuItemNew.setMnemonic('N');
    menuItemOpen.setMnemonic('O');
    menuItemClose.setMnemonic('C');
    menuItemSave.setMnemonic('S');
    menuItemSaveAs.setMnemonic('A');
    menuItemExit.setMnemonic('X');

    // Set mnemonics for comm item selections for file menu.
    menuItemSend.setMnemonic('S');
    menuItemReceive.setMnemonic('R');

    // Set mnemonics for data item selections for file menu.
    menuItemConnect.setMnemonic('C');
    menuItemSubmit.setMnemonic('R');

    // Menu items to help menu.
    help.add(menuCheckBoxItemDebug);
    help.addSeparator();
    help.add(menuItemHelp);

    // Set mnemonics for menu item selections for edit menu.
    menuCheckBoxItemDebug.setMnemonic('D');
    menuItemHelp.setMnemonic('A');

    // Build menu action listeners.
    buildMenuActionListeners();

    // Set the menu bar in the frame and return menu bar.
    setJMenuBar(menuBar);

    // Return JMenuBar
    return menuBar;
  } // End of buildMenu() method.

  // -------------------------------------------------------------------------/

  // Method builds menu action listeners.
  private void buildMenuActionListeners() {
    /*
    || Section adds action listeners to window frame menus:
    || ===================================================
    ||  - Menu file:
    ||    ---------
    ||    - menuItemSend
    ||    - menuItemReceive
    ||    - menuItemExit
    ||
    ||  - Menu edit:
    ||    ---------
    ||    - menuItemHelp
    */

    // ---------------------------------/
    // Menu item listeners to file menu.
    // ---------------------------------/

    menuItemNew.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // New file.
            newFile();
          } // End of actionPerformed method.
        }); // End of menuItemNew action listener.

    menuItemOpen.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Open file.
            openFile();
          } // End of actionPerformed method.
        }); // End of menuItemOpen action listener.

    menuItemClose.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Close file.
            closeFile();
          } // End of actionPerformed method.
        }); // End of menuItemClose action listener.

    menuItemSave.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Save current sender JTextAreaPanel String as current file.
            saveFile();
          } // End of actionPerformed method.
        }); // End of menuItemSave action listener.

    menuItemSaveAs.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Save current sender JTextAreaPanel String as new file.
            saveAsFile();
          } // End of actionPerformed method.
        }); // End of menuItemSaveAs action listener.

    menuItemExit.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Exit the system on menu exit.
            System.exit(0);
          } // End of actionPerformed() method.
        }); // End of menuItemExit action listener.

    menuItemSend.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Send message.
            setMessage(sender, receiver);
          } // End of actionPerformed() method.
        }); // End of menuItemSend action listener.

    menuItemReceive.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Receive message.
            getMessage(receiver);
          } // End of actionPerformed() method.
        }); // End of menuItemReceive action listener.

    menuItemConnect.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Functionality to be implemented.
            System.out.println("This is future functionality to Connect to DB.");
          } // End of actionPerformed() method.
        }); // End of menuItemConnect action listener.

    menuItemSubmit.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Functionality to be implemented.
            System.out.println("This is future functionality to Submit SQL.");
          } // End of actionPerformed() method.
        }); // End of menuItemSubmit action listener.

    // ---------------------------------/
    // Menu item listeners to help menu.
    // ---------------------------------/

    // Add menu item listeners for debug check box menu item.
    menuCheckBoxItemDebug.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            // Set stack trace enablement to opposite state.
            setDebugEnabled(!getDebugEnabled());
          } // End of actionPerformed method.
        }); // End of menuCheckBoxItemDebug item listener.

    // Add menu item action listener for help menu.
    menuItemHelp.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Call inner class help handler.
            new HelpHandler(JMessagingFrame.this, true);
          } // End of actionPerformed() method.
        }); // End of menuItemHelp action listener.
  } // End of buildMenuActionListeners() method.

  // -------------------------------------------------------------------------/

  // Method to closeFile().
  private void closeFile() {
    // Dismiss file reference.
    fileName = new File("");

    // If JTextAreaPanel contains text.
    if (!sender.isTextAreaEmpty()) {
      // Clear display area.
      sender.replaceRange(null, 0, sender.getText().length());
    } // End of if check if JTextAreaPanel contains text.
  } // End of closeFile() method.

  // -------------------------------------------------------------------------/

  // Method to get the debug state.
  private boolean getDebugEnabled() {
    // Return current debug state.
    return debugEnabled;
  } // End of setDebugEnabled() method.

  // -------------------------------------------------------------------------/

  // Define a getExceptionString() method.
  private String getExceptionString() {
    // Return the current exception String.
    return eString;
  } // End of getExceptionString() method.

  // -------------------------------------------------------------------------/

  // Define a getMessage() method.
  private void getMessage(JTextAreaPanel in) {
    // Try to get incoming message.
    try {
      // Receive message text.
      in.getMessage();

    } // End of try to get message.
    catch (BufferEmptyException e) // Catch BufferEmptyException.
    {
      // Capture the stack trace into a String.
      setExceptionString(e.fillInStackTrace());

      // Pass message to the JOptionPane manager.
      setExceptionPane(
          "There is nothing in the buffer to receive.\n\n" + "Do you want to see the stack trace?");
    } // End of catch on BufferEmptyException.
  } // End of getMessage() method.

  // -------------------------------------------------------------------------/

  // Get the stack trace dialog event.
  private void getStackTraceDialog() {
    // Create an instance of StackTraceDialog.
    new StackTraceDialog(JMessagingFrame.this, getExceptionString(), true);

    // Disposing of the JDialog will leave a value in the class instance
    // exception String.  This resets the value to a zero length String.
    resetExceptionString();
  } // End of getStackTraceDialog() method.

  // -------------------------------------------------------------------------/

  // Method to newFile().
  private void newFile() {
    // Close any open file(s).
    closeFile();
  } // End of newFile() method.

  // -------------------------------------------------------------------------/

  // Method to open a file for sequential read-only.
  private void openFile() {
    // Define local primitive(s).
    String contents = new String();

    // If a file is open, prompt to save the file before dismissing content
    // and reference.
    if (!file.toString().equals("")) {
      // Close the existing file.
      closeFile();
    } // End of if file not null or not equal to a zero String.

    // Open a file.
    fileName = FileIO.findFile(this);

    // If a file name is returned.
    if (fileName != null) {
      // Read file.
      contents = FileIO.openFile(this, fileName);

      // Verify that the JTextAreaPanel is empty.
      if (sender.isTextAreaEmpty()) {
        // Set JTextAreaPanel.
        sender.setText(contents);

      } // End of if JTextAreaPanel is empty.
      else {
        // Reset JTextAreaPanel by replacing the range.
        sender.replaceRange(contents, 0, sender.getText().length());
      } // End of else JTextAreaPanel is not empty.

      // Set file open flag to true.
      fileOpen = true;
    } // End of if a fileName is selected.
  } // End of openFile method.

  // -------------------------------------------------------------------------/

  // Get exception string with current exception content.
  private void resetExceptionString() {
    // Reset the exception string to a string of zero length.
    eString = new String();
  } // End of resetExceptionString() method.

  // -------------------------------------------------------------------------/

  // Method to saveAsFile().
  private void saveAsFile() {
    // Set a file.
    fileName = FileIO.nameFile(this);

    // If a file name is selected.
    if (fileName != null) {
      // Try block to throw a custom exception.
      try {
        // Save file.
        FileIO.saveFile(this, fileName, sender.getText());

      } // End of try to get message.
      catch (BufferEmptyException e) // Catch InvalidFileReference.
      {
        // Capture the stack trace into a String.
        setExceptionString(e.fillInStackTrace());

        // Pass message to the JOptionPane manager.
        setExceptionPane(
            "There is nothing in the sender panel to write.\n\n"
                + "Do you want to see the stack trace?");
      } // End of catch on BufferEmptyException.
    } // End of if a fileName is selected.
  } // End of saveAsFile() method.

  // -------------------------------------------------------------------------/

  // Method to saveFile().
  private void saveFile() {
    // If a file name is returned.
    if (fileName != null) {
      // Try block to throw a custom exception.
      try {
        // Save file.
        FileIO.saveFile(this, fileName, sender.getText());

      } // End of try to get message.
      catch (BufferEmptyException e) // Catch InvalidFileReference.
      {
        // Capture the stack trace into a String.
        setExceptionString(e.fillInStackTrace());

        // Pass message to the JOptionPane manager.
        setExceptionPane(
            "There is nothing in the sender panel to write.\n\n"
                + "Do you want to see the stack trace?");
      } // End of catch on BufferEmptyException.
    } // End of if a fileName is selected.
  } // End of saveFile() method.

  // -------------------------------------------------------------------------/

  // Method to set the debug state.
  private void setDebugEnabled(boolean enabledState) {
    // Set debugEnabled to other state.
    if (debugEnabled != enabledState) {
      // Assign the opposite state.
      debugEnabled = enabledState;
    } // End of if debug state is equal to argument.
  } // End of setDebugEnabled() method.

  // -------------------------------------------------------------------------/

  private void setExceptionPane(Object msg) {
    // If debug is enabled display dialog.
    if (debugEnabled) {
      // Display message and retrieve selected value.
      int result =
          JOptionPane.showConfirmDialog(this, msg, "Information", JOptionPane.YES_NO_OPTION);

      // Display message and retrieve selected value.
      switch (result) {
        case JOptionPane.CLOSED_OPTION:
          resetExceptionString();
          break;

        case JOptionPane.YES_OPTION:
          getStackTraceDialog();
          break;

        case JOptionPane.NO_OPTION:
          resetExceptionString();
          break;
      } // End of result evaluation switch.

    } // End of if debugEnabled evaluation.
    else {
      // Disgard the error and reset the class instance exception String.
      // This resets the value to a zero length String.
      resetExceptionString();
    } // End of else debugEnabled evaluation.
  } // End of setExceptionPane() method.

  // -------------------------------------------------------------------------/

  // Set exception string with current exception content.
  protected void setExceptionString(Throwable eThrowable) {
    // Initialize a StringWriter.
    eStringWriter = new StringWriter();

    // Initialize a PrintWriter.
    ePrintWriter = new PrintWriter(eStringWriter);

    // Pass contents from Throwable object to a StringWriter object.
    eThrowable.printStackTrace(ePrintWriter);

    // Assign String from StringWriter.
    eString = new String(eStringWriter.toString());
  } // End of setExceptionString() method.

  // -------------------------------------------------------------------------/

  // Define a setMessage() method.
  private void setMessage(JTextAreaPanel out, JTextAreaPanel in) {
    // Try to get incoming message.
    try {
      // Send message text.
      in.setMessage(out.getText());

      // Consume sent message text.
      out.replaceRange(null, 0, out.getText().length());

    } // End of try to get message.

    // Catch BufferEmptyException.
    catch (BufferEmptyException e) {
      // Capture the stack trace into a String.
      setExceptionString(e.fillInStackTrace());

      // Pass message to the JOptionPane manager.
      setExceptionPane(
          "There is nothing in the buffer to send.\n\n" + "Do you want to see the stack trace?");
    } // End of catch on BufferEmptyException.
  } // End of setMessage() method.

  // -------------------------------------------------------------------------/

  // Define a setMinimumHeight() method.
  protected int setMinimumHeight(int height) {
    // Set return value.
    int retVal = END_Y;

    // If height is greater than minimum allow override.
    if (height >= END_Y) {
      // Functionality for screen resolution of spacing not implemented.
      retVal = END_Y;
    } // End of if height is greater than or equal to minimum.

    // Return value.
    return retVal;
  } // End of setMinimumHeight() method.

  // -------------------------------------------------------------------------/

  // Define a setMinimumWidth() method.
  protected int setMinimumWidth(int width) {
    // Set return value.
    int retVal = END_X;

    // If width is greater than minimum allow override.
    if (width >= END_X) {
      // Override minimum.
      retVal = width;
    } // End of if width is greater than or equal to minimum.

    // Return value.
    return retVal;
  } // End of setMinimumWidth() method.

  // -------------------------------------------------------------------------/

  // Define a setScrollPaneProperties() method.
  private JScrollPane setScrollPaneProperties(JScrollPane pane) {
    // Set JScrollPane properties.
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    // Return value.
    return pane;
  } // End of setScrollPaneProperties() method.

  // ---------------------------- End Methods --------------------------------/

  // ------------------------- Begin Inner Class -----------------------------/

  // Inner class to manage help modal diaglog object.
  class HelpHandler extends JDialog implements ActionListener {
    // Define and initialize AWT container.
    Container c = getContentPane();

    // Define and initialize Swing widgets.
    JButton okButton = new JButton("Check the Java API");
    ImageIcon imageIcon = new ImageIcon("surfing.gif");
    JLabel image = new JLabel(imageIcon);

    // Define and intialize phsyical size dimensions.
    int left = 0;
    int top = 0;
    int buttonWidth = 150;
    int buttonHeight = 25;
    int imageWidth = imageIcon.getIconWidth();
    int imageHeight = imageIcon.getIconHeight();
    int offsetMargin = 20;

    // The dialog width and height are derived from base objects.
    int dialogWidth = imageWidth + offsetMargin;
    int dialogHeight = imageHeight + buttonHeight + (3 * offsetMargin);

    // --------------------------- Constructor -------------------------------/

    // The inner class requires an owning frame and cannot be called from
    // a default constructor.  So, the default constructor is excluded.
    public HelpHandler(Frame owner, boolean modal) {
      super(owner, modal);
      buildDialogBox();
    }

    // -------------------------- Begin Methods ------------------------------/

    // Method to build the dialog box for help.
    private void buildDialogBox() {
      // Set the JDialog window properties.
      setTitle("Learning about Java");
      setResizable(false);
      setSize(dialogWidth, dialogHeight);

      // Define behaviors of container.
      c.setLayout(null);
      c.setBackground(Color.cyan);
      c.add(image);
      c.add(okButton);

      // Set the bounds for the image.
      image.setBounds(
          (dialogWidth / 2) - (imageWidth / 2),
          (top + (offsetMargin / 2)),
          imageWidth,
          imageHeight);

      // Set the behaviors, bounds and action listener for the button.
      okButton.setBounds(
          (dialogWidth / 2) - (buttonWidth / 2),
          (imageHeight + (int) 1.5 * offsetMargin),
          buttonWidth,
          buttonHeight);

      // Set the font to the platform default Font for the object with the
      // properties of bold and font size of 11.
      okButton.setFont(new Font(okButton.getFont().getName(), Font.BOLD, 11));

      // Set foreground and background of JButton(s).
      okButton.setForeground(Color.white);
      okButton.setBackground(Color.blue);

      // The class implements the ActionListener interface and therefore
      // provides an implementation of the actionPerformed() method.  When a
      // class implements ActionListener, the instance handler returns an
      // ActionListener.  The ActionListener then performs actionPerformed()
      // method on an ActionEvent.
      okButton.addActionListener(this);

      // Set the screen and display dialog window in relation to screen size.
      dim = tk.getScreenSize();
      setLocation((dim.width / 2) - (dialogWidth / 2), (dim.height / 2) - (dialogHeight / 2));

      // Display the dialog.
      show();
    } // End of buildDialogBox method.

    // --------------------- Window ActionListener ---------------------------/

    // Class listener based on implementing ActionListener.
    public void actionPerformed(ActionEvent e) {
      // Dispose of the help dialog.
      setVisible(false);
      dispose();
    } // End of actionPerformed method.

    // -------------------------- End Methods --------------------------------/

  } // End of HelpHandler inner class.

  // -------------------------- End Inner Class ------------------------------/

  // ------------------------- Begin Static Main -----------------------------/

  // Static main program for executing a test of the class.
  public static void main(String args[]) {
    // Define int variables.
    int width = 0;
    int height = 0;

    // If arguments are greater than zero.
    if (args.length > 0) {

      // If arguments are two.
      if (args.length >= 2) {
        // Use try block to parse for an integer.
        try {
          // Verify first argument is an integer.
          width = Integer.parseInt(args[0]);
          height = Integer.parseInt(args[1]);

          // Define a default instance of JMessagingFrame.
          JMessagingFrame f = new JMessagingFrame(width, height);

        } // Catch parsing failure exception.
        catch (NumberFormatException e) {
          // Print default runtime message.
          System.out.println("If you are testing the override constructor,");
          System.out.println("then you need to provide two integer values.");
        } // End try-catch block on integer parse.

      } // End of if two arguments provided.
      else // When there are less than or more than two arguments.
      {
        // Print default runtime message.
        System.out.println("If you are testing the override constructor,");
        System.out.println("then you need to provide two integer values.");
      } // End of else when there are less than or more than two arguments.

    } // End of else when there are two arguments.
    else // No arguments provided.
    {
      // Define a default instance of JMessagingFrame.
      JMessagingFrame f = new JMessagingFrame();

      // Clean-up by signaling the garbage collector.
      System.gc();
    } // End of else when no arguments are provided.
  } // End of static main.

  // -------------------------- End Static Main ------------------------------/

} // End of JMessagingFrame class.
コード例 #16
0
  /**
   * Constructor, initialises the editor components.
   *
   * @param initialText The initial text to be displayed in the editor.
   * @param handler The GUI handler for this component.
   */
  public GUITextModelEditor(String initialText, GUIMultiModelHandler handler) {
    this.handler = handler;
    setLayout(new BorderLayout());

    // Setup the editor with it's custom editor kits. To switch between
    // editor kits just use setContentType() for the desired content type.
    editor =
        new JEditorPane() {
          @Override
          public String getToolTipText(MouseEvent event) {
            if (parseError != null) {
              try {
                int offset = this.viewToModel(new Point(event.getX(), event.getY()));

                int startOffset =
                    computeDocumentOffset(parseError.getBeginLine(), parseError.getBeginColumn());
                int endOffset =
                    computeDocumentOffset(parseError.getEndLine(), parseError.getEndColumn()) + 1;

                if (offset >= startOffset && offset <= endOffset) return parseError.getMessage();
              } catch (BadLocationException e) {
              }
            }

            return null;
          }
        };

    editor.setToolTipText("dummy");

    editor.setEditorKitForContentType("text/prism", new PrismEditorKit(handler));
    editor.setEditorKitForContentType("text/pepa", new PepaEditorKit(handler));
    // The default editor kit is the Prism one.
    editor.setContentType("text/prism");
    editor.setBackground(Color.white);
    editor.addMouseListener(editorMouseListener);
    editor.setEditable(true);
    editor.setText(initialText);
    editor.getDocument().addDocumentListener(this);
    editor.addCaretListener(
        new CaretListener() {
          public void caretUpdate(CaretEvent e) {
            GUITextModelEditor.this
                .handler
                .getGUIPlugin()
                .getSelectionChangeHandler()
                .notifyListeners(new GUIEvent(1));
          }
        });
    editor.getDocument().putProperty(PlainDocument.tabSizeAttribute, new Integer(4));

    editor.addMouseListener(this);
    errorHighlightPainter =
        new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 192, 192));
    undoManager = new GUIUndoManager(GUIPrism.getGUI());
    undoManager.setLimit(200);

    // Setup the scrollpane
    editorScrollPane = new JScrollPane(editor);
    add(editorScrollPane, BorderLayout.CENTER);
    gutter = new GUITextModelEditorGutter(editor);

    // Get the 'show line numbers' setting to determine
    // if the line numbers should be shown.
    showLineNumbersSetting =
        handler
            .getGUIPlugin()
            .getPrism()
            .getSettings()
            .getBoolean(PrismSettings.MODEL_SHOW_LINE_NUMBERS);
    if (showLineNumbersSetting) {
      editorScrollPane.setRowHeaderView(gutter);
    }

    // Add a Prism settings listener to catch changes made to the
    // 'show line numbers' setting.
    handler
        .getGUIPlugin()
        .getPrism()
        .getSettings()
        .addSettingsListener(
            new PrismSettingsListener() {
              public void notifySettings(PrismSettings settings) {
                // Check if the setting has changed.
                if (settings.getBoolean(PrismSettings.MODEL_SHOW_LINE_NUMBERS)
                    != showLineNumbersSetting) {
                  showLineNumbersSetting = !showLineNumbersSetting;
                  if (showLineNumbersSetting) {
                    editorScrollPane.setRowHeaderView(gutter);
                  } else {
                    editorScrollPane.setRowHeaderView(null);
                  }
                }
              }
            });

    // initialize the actions for the context menu
    initActions();

    // method to initialize the context menu popup
    initContextMenu();

    InputMap inputMap = editor.getInputMap();
    inputMap.clear();

    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_undo");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_undo");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_redo");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_selectall");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_delete");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_cut");
    inputMap.put(
        KeyStroke.getKeyStroke(
            KeyEvent.VK_Z,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
                | java.awt.event.InputEvent.SHIFT_MASK),
        "prism_redo");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_paste");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_E, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_jumperr");

    ActionMap actionMap = editor.getActionMap();
    actionMap.put("prism_undo", GUIPrism.getClipboardPlugin().getUndoAction());
    actionMap.put("prism_redo", GUIPrism.getClipboardPlugin().getRedoAction());
    actionMap.put("prism_selectall", GUIPrism.getClipboardPlugin().getSelectAllAction());
    actionMap.put("prism_cut", GUIPrism.getClipboardPlugin().getCutAction());
    actionMap.put("prism_copy", GUIPrism.getClipboardPlugin().getCopyAction());
    actionMap.put("prism_paste", GUIPrism.getClipboardPlugin().getPasteAction());
    actionMap.put("prism_delete", GUIPrism.getClipboardPlugin().getDeleteAction());
    actionMap.put("prism_jumperr", actionJumpToError);

    // Attempt to programmatically allow all accelerators
    /*ArrayList plugins = ((GUIMultiModel)handler.getGUIPlugin()).getGUI().getPlugins();
    Iterator it = plugins.iterator();

    while (it.hasNext())
    {
    	GUIPlugin plugin = ((GUIPlugin)it.next());
    	System.out.println(plugin.getName());
    	JMenu firstMenu = plugin.getMenu();

    	Stack<MenuElement> menuStack = new Stack<MenuElement>();

    	menuStack.add(firstMenu);

    	while (!menuStack.empty())
    	{
    		MenuElement menu = menuStack.pop();

    		if (menu instanceof JMenuItem)
    		{
    			JMenuItem menuItem = ((JMenuItem)menu);

    			KeyStroke accelerator = menuItem.getAccelerator();
    			Action action = menuItem.getAction();

    			if (action != null && accelerator != null && menuItem.getText() != null)
    			{
    				System.out.println(menuItem.getText() + " " + menuItem.getName());
    				inputMap.put(accelerator, "prism_" + menuItem.getText());
    				actionMap.put("prism_" + menuItem.getText(), action);
    			}
    		}

    		MenuElement[] subelements = menu.getSubElements();

    		if (subelements != null)
    		{
    			for (int i = 0; i < subelements.length; i++)
    				menuStack.push(subelements[i]);
    		}
    	}
    }*/

    editor.getDocument().addUndoableEditListener(undoManager);
    editor
        .getDocument()
        .addUndoableEditListener(
            new UndoableEditListener() {
              public void undoableEditHappened(UndoableEditEvent e) {
                System.out.println("adding undo edit");
              }
            });
  }
コード例 #17
0
public class NewUser extends JFrame {
  private JLabel username, password, confirm, label1, label2;
  private JPasswordField pass1, pass2;
  private JTextField txtusername, name;
  private JButton button1, button2;
  private JPanel panel1, panel2;
  private JComboBox combo1;
  Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();

  public NewUser() {
    super("Adding New User");
    label1 = new JLabel("Name");
    label2 = new JLabel("Category");
    username = new JLabel("Username");
    password = new JLabel("Password");
    confirm = new JLabel("Re-enter Password");
    pass1 = new JPasswordField();
    pass2 = new JPasswordField();
    txtusername = new JTextField();
    name = new JTextField();
    combo1 = new JComboBox();
    button1 = new JButton("Ok", new ImageIcon("Icon/i16x16/ok.png"));
    button2 = new JButton("Cancel", new ImageIcon("Icon/i16x16/exit.png"));

    panel1 = new JPanel(new GridLayout(6, 2));
    panel1.add(label1);
    panel1.add(name);
    panel1.add(label2);
    panel1.add(combo1);
    panel1.add(username);
    panel1.add(txtusername);
    panel1.add(password);
    panel1.add(pass1);
    panel1.add(confirm);
    panel1.add(pass2);
    panel1.add(button1);
    panel1.add(button2);
    combo1.addItem("Manager");
    combo1.addItem("Booking Clerk");
    combo1.addItem("Supervisor");
    panel2 = new JPanel();
    panel2.add(panel1);
    getContentPane().add(panel2);
    setSize(350, 195);
    setVisible(true);
    setLocation((screen.width - 500) / 2, ((screen.height - 350) / 2));
    setResizable(false);
    name.addKeyListener(
        new KeyAdapter() {
          public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!(Character.isLetter(c)
                || (c == KeyEvent.VK_BACK_SPACE)
                || (c == KeyEvent.VK_SPACE)
                || (c == KeyEvent.VK_DELETE))) {

              getToolkit().beep();
              JOptionPane.showMessageDialog(
                  null, "Invalid Character", "ERROR", JOptionPane.DEFAULT_OPTION);
              e.consume();
            }
          }
        });
    txtusername.addKeyListener(
        new KeyAdapter() {
          public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!(Character.isLetter(c)
                || (c == KeyEvent.VK_BACK_SPACE)
                || (c == KeyEvent.VK_SPACE)
                || (c == KeyEvent.VK_DELETE))) {

              getToolkit().beep();
              JOptionPane.showMessageDialog(
                  null, "Invalid Character", "ERROR", JOptionPane.DEFAULT_OPTION);
              e.consume();
            }
          }
        });
    button1.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent e) {

            if (name.getText() == null || name.getText().equals("")) {
              JOptionPane.showMessageDialog(
                  null, "Enter name", "ERROR", JOptionPane.DEFAULT_OPTION);
              name.requestFocus();
              return;
            }
            if (txtusername.getText() == null || txtusername.getText().equals("")) {
              JOptionPane.showMessageDialog(
                  null, "Enter username", "ERROR", JOptionPane.DEFAULT_OPTION);
              txtusername.requestFocus();
              return;
            }
            if (pass1.getText() == null || pass1.getText().equals("")) {
              JOptionPane.showMessageDialog(
                  null, "Enter password", "ERROR", JOptionPane.DEFAULT_OPTION);
              pass1.requestFocus();
              return;
            }
            if (pass2.getText() == null || pass2.getText().equals("")) {
              JOptionPane.showMessageDialog(
                  null, "Confirm your password", "ERROR", JOptionPane.DEFAULT_OPTION);
              pass2.requestFocus();
              return;
            }
            if (!pass1.getText().equals(pass2.getText())) {
              JOptionPane.showMessageDialog(
                  null, "passwords do not match.", "ERROR", JOptionPane.DEFAULT_OPTION);
              pass2.requestFocus();
              return;
            }
            try {
              Statement statement = Connect.getConnection().createStatement();
              {
                String temp =
                    "INSERT INTO users (Name,Category,username, password) VALUES ('"
                        + name.getText()
                        + "', '"
                        + combo1.getSelectedItem()
                        + "', '"
                        + txtusername.getText()
                        + "', '"
                        + pass1.getText()
                        + "')";

                int result = statement.executeUpdate(temp);
                JOptionPane.showMessageDialog(
                    null, "User is succesfully added", "SUCCESS", JOptionPane.DEFAULT_OPTION);
                dispose();
              }

            } catch (Exception in) {
              in.printStackTrace();
            }
          }
        });
    button2.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        });
  }

  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    new MainMenu().setVisible(true);
  }
}
コード例 #18
0
  /** Helper method to initialize the actions used for the buttons. */
  private void initActions() {

    /*actionUndo = new AbstractAction() {
    	public void actionPerformed(ActionEvent ae) {
    		try {
    			// do redo
    			undoManager.undo();

    			// notify undo manager/toolbar of change
    			GUIPrism.getGUI().notifyEventListeners(
    					new GUIClipboardEvent(GUIClipboardEvent.UNDOMANAGER_CHANGE,
    							GUIPrism.getGUI().getFocussedPlugin().getFocussedComponent()));
    		} catch (CannotUndoException ex) {
    			//GUIPrism.getGUI().getMultiLogger().logMessage(PrismLogLevel.PRISM_ERROR, ex.getMessage());
    		}
    	}
    };
    actionUndo.putValue(Action.LONG_DESCRIPTION, "Undo the most recent action.");
    actionUndo.putValue(Action.NAME, "Undo");
    actionUndo.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("smallUndo.png"));

    actionRedo = new AbstractAction() {
    	public void actionPerformed(ActionEvent ae) {
    		try {
    			// do redo
    			undoManager.redo();

    			// notify undo manager/toolbar of change
    			GUIPrism.getGUI().notifyEventListeners(
    					new GUIClipboardEvent(GUIClipboardEvent.UNDOMANAGER_CHANGE,
    							GUIPrism.getGUI().getFocussedPlugin().getFocussedComponent()));
    		} catch (CannotRedoException ex) {
    			//GUIPrism.getGUI().getMultiLogger().logMessage(PrismLogLevel.PRISM_ERROR, ex.getMessage());
    		}
    	}
    };


    actionRedo.putValue(Action.LONG_DESCRIPTION, "Redos the most recent undo");
    actionRedo.putValue(Action.NAME, "Redo");
    actionRedo.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("smallRedo.png"));
    */
    actionJumpToError =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            jumpToError();
          }
        };

    actionJumpToError.putValue(Action.NAME, "Jump to error");
    actionJumpToError.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("tinyError.png"));
    actionJumpToError.putValue(
        Action.ACCELERATOR_KEY,
        KeyStroke.getKeyStroke(
            KeyEvent.VK_E, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

    // search and replace action
    actionSearch =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            /*
                		// System.out.println("search button pressed");
                		if (GUIMultiModelHandler.isDoingSearch()) {

            } else {
            	try {
            		GUIMultiModelHandler.setDoingSearch(true);
            		FindReplaceForm.launch(GUIPrism.getGUI().getMultiModel());
            	} catch (PluginNotFoundException pnfe) {
            		GUIPrism.getGUI().getMultiLogger().logMessage(prism.log.PrismLogLevel.PRISM_ERROR,
            				pnfe.getMessage());
            	}
            }
            */
          }
        };
    actionSearch.putValue(Action.LONG_DESCRIPTION, "Opens a find and replace dialog.");
    // actionSearch.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("find.png"));
    actionSearch.putValue(Action.NAME, "Find/Replace");
    // actionSearch.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_R,
    // Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

    insertDTMC =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            int caretPosition = editor.getCaretPosition();
            try {
              editor.getDocument().insertString(caretPosition, "dtmc", new SimpleAttributeSet());
            } catch (BadLocationException ble) {
              // todo log?
            }
          }
        };

    insertDTMC.putValue(
        Action.LONG_DESCRIPTION, "Marks this model as a \"Discrete-Time Markov Chain\"");
    // actionSearch.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("find.png"));
    insertDTMC.putValue(Action.NAME, "Probabilistic (DTMC)");

    insertCTMC =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            int caretPosition = editor.getCaretPosition();
            try {
              editor.getDocument().insertString(caretPosition, "ctmc", new SimpleAttributeSet());
            } catch (BadLocationException ble) {
              // todo log?
            }
          }
        };

    insertCTMC.putValue(
        Action.LONG_DESCRIPTION, "Marks this model as a \"Continous-Time Markov Chain\"");
    // actionSearch.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("find.png"));
    insertCTMC.putValue(Action.NAME, "Stochastic (CTMC)");

    insertMDP =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            int caretPosition = editor.getCaretPosition();
            try {
              editor.getDocument().insertString(caretPosition, "mdp", new SimpleAttributeSet());
            } catch (BadLocationException ble) {
              // todo log?
            }
          }
        };

    insertMDP.putValue(
        Action.LONG_DESCRIPTION, "Marks this model as a \"Markov Decision Process\"");
    // actionSearch.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("find.png"));
    insertMDP.putValue(Action.NAME, "Non-deterministic (MDP)");
  }
コード例 #19
0
  private void initialize(Element elem) {
    synchronized (this) {
      loading = true;
      fWidth = fHeight = 0;
    }
    int width = 0;
    int height = 0;
    boolean customWidth = false;
    boolean customHeight = false;
    try {
      fElement = elem;

      // Request image from document's cache:
      AttributeSet attr = elem.getAttributes();
      if (isURL()) {
        URL src = getSourceURL();
        if (src != null) {
          Dictionary cache = (Dictionary) getDocument().getProperty(IMAGE_CACHE_PROPERTY);
          if (cache != null) fImage = (Image) cache.get(src);
          else fImage = Toolkit.getDefaultToolkit().getImage(src);
        }
      } else {

        /** ****** Code to load from relative path ************ */
        String src = (String) fElement.getAttributes().getAttribute(HTML.Attribute.SRC);
        System.out.println("before src: " + src);
        src = processSrcPath(src);
        System.out.println("after src: " + src);
        fImage = Toolkit.getDefaultToolkit().createImage(src);
        try {
          waitForImage();
        } catch (InterruptedException e) {
          fImage = null;
        }
        /** *************************************************** */
      }

      // Get height/width from params or image or defaults:
      height = getIntAttr(HTML.Attribute.HEIGHT, -1);
      customHeight = (height > 0);
      if (!customHeight && fImage != null) height = fImage.getHeight(this);
      if (height <= 0) height = DEFAULT_HEIGHT;

      width = getIntAttr(HTML.Attribute.WIDTH, -1);
      customWidth = (width > 0);
      if (!customWidth && fImage != null) width = fImage.getWidth(this);
      if (width <= 0) width = DEFAULT_WIDTH;

      // Make sure the image starts loading:
      if (fImage != null)
        if (customWidth && customHeight)
          Toolkit.getDefaultToolkit().prepareImage(fImage, height, width, this);
        else Toolkit.getDefaultToolkit().prepareImage(fImage, -1, -1, this);

      /**
       * ****************************************************** // Rob took this out. Changed scope
       * of src. if( DEBUG ) { if( fImage != null ) System.out.println("ImageInfo: new on "+src+ "
       * ("+fWidth+"x"+fHeight+")"); else System.out.println("ImageInfo: couldn't get image at "+
       * src); if(isLink()) System.out.println(" It's a link! Border = "+ getBorder());
       * //((AbstractDocument.AbstractElement)elem).dump(System.out,4); }
       * ******************************************************
       */
    } finally {
      synchronized (this) {
        loading = false;
        if (customWidth || fWidth == 0) {
          fWidth = width;
        }
        if (customHeight || fHeight == 0) {
          fHeight = height;
        }
      }
    }
  }
コード例 #20
0
 public static void center(Window w) {
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Dimension windowSize = w.getSize();
   w.setLocation(
       (screenSize.width - windowSize.width) / 2, (screenSize.height - windowSize.height) / 2);
 }