private void initGUI() {

    JPanel pCommand = new JPanel();

    pResult = new JPanel();
    nsSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pCommand, pResult);

    pCommand.setLayout(new BorderLayout());
    pResult.setLayout(new BorderLayout());

    Font fFont = new Font("Dialog", Font.PLAIN, 12);

    txtCommand = new JTextArea(5, 40);

    txtCommand.setMargin(new Insets(5, 5, 5, 5));
    txtCommand.addKeyListener(this);

    txtCommandScroll = new JScrollPane(txtCommand);
    txtResult = new JTextArea(20, 40);

    txtResult.setMargin(new Insets(5, 5, 5, 5));

    txtResultScroll = new JScrollPane(txtResult);

    txtCommand.setFont(fFont);
    txtResult.setFont(new Font("Courier", Font.PLAIN, 12));
    /*
    // button replaced by toolbar
            butExecute = new JButton("Execute");

            butExecute.addActionListener(this);
            pCommand.add(butExecute, BorderLayout.EAST);
    */
    pCommand.add(txtCommandScroll, BorderLayout.CENTER);

    gResult = new GridSwing();
    gResultTable = new JTable(gResult);
    gScrollPane = new JScrollPane(gResultTable);

    // getContentPane().setLayout(new BorderLayout());
    pResult.add(gScrollPane, BorderLayout.CENTER);

    // Set up the tree
    rootNode = new DefaultMutableTreeNode("Connection");
    treeModel = new DefaultTreeModel(rootNode);
    tTree = new JTree(treeModel);
    tScrollPane = new JScrollPane(tTree);

    tScrollPane.setPreferredSize(new Dimension(120, 400));
    tScrollPane.setMinimumSize(new Dimension(70, 100));
    txtCommandScroll.setPreferredSize(new Dimension(360, 100));
    txtCommandScroll.setMinimumSize(new Dimension(180, 100));
    gScrollPane.setPreferredSize(new Dimension(460, 300));

    ewSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tScrollPane, nsSplitPane);

    fMain.getContentPane().add(ewSplitPane, BorderLayout.CENTER);
    doLayout();
    fMain.pack();
  }
  private void showHelp(String help[]) {

    txtCommand.setText(help[0]);

    bHelp = true;

    pResult.removeAll();
    pResult.add(txtResultScroll, BorderLayout.CENTER);
    pResult.doLayout();
    txtResult.setText(help[1]);
    pResult.repaint();
    txtCommand.requestFocus();
    txtCommand.setCaretPosition(help[0].length());
  }
  @Override
  public void run() {
    while (true) {
      try {
        String msgFromClient = din.readUTF();
        StringTokenizer st = new StringTokenizer(msgFromClient);
        String loginName = st.nextToken();

        if (loginName.equals("server")) // message is from server, special request
        {
          String MsgType = st.nextToken();

          if (MsgType.equals("newRoom")) // create a new chatclient window
          {
            String token;
            token = st.nextToken();
            new ChatClient(loginName + " - " + token, userId, Integer.parseInt(token));
          }

        } else
          ta.append(
              " \n"
                  + msgFromClient); // normal communication, display all text received from server
                                    // onto text area.

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 public CFSecuritySwingISOCurrencyAskDeleteJPanel(
     ICFSecuritySwingSchema argSchema, ICFSecurityISOCurrencyObj argFocus) {
   super();
   final String S_ProcName = "construct-schema-focus";
   if (argSchema == null) {
     throw CFLib.getDefaultExceptionFactory()
         .newNullArgumentException(getClass(), S_ProcName, 1, "argSchema");
   }
   // argFocus is optional; focus may be set later during execution as
   // conditions of the runtime change.
   swingSchema = argSchema;
   swingFocus = argFocus;
   // Construct the various objects
   textAreaMessage = new JTextArea("Are you sure you want to delete this ISO Currency?");
   actionOk = new ActionOk();
   actionCancel = new ActionCancel();
   buttonOk = new JButton(actionOk);
   buttonCancel = new JButton(actionCancel);
   attrJPanel = argSchema.getISOCurrencyFactory().newAttrJPanel(argFocus);
   scrollPane = new CFHSlaveJScrollPane(attrJPanel);
   // Lay out the widgets
   setSize(1024, 480);
   Dimension min = new Dimension(480, 300);
   setMinimumSize(min);
   add(textAreaMessage);
   textAreaMessage.setBounds(0, 0, 1024, 50);
   int xparts = (768 - (2 * 125)) / 3;
   add(buttonOk);
   buttonOk.setBounds(xparts, 55, 125, 40);
   add(buttonCancel);
   buttonCancel.setBounds(xparts + 125 + xparts, 55, 125, 40);
   add(scrollPane);
   scrollPane.setBounds(0, 100, 1024, 480 - 100);
 }
 public void doLayout() {
   Dimension sz = getSize();
   textAreaMessage.setBounds(0, 0, sz.width, 50);
   int xparts = (sz.width - (2 * 125)) / 3;
   buttonOk.setBounds(xparts, 55, 125, 40);
   buttonCancel.setBounds(xparts + 125 + xparts, 55, 125, 40);
   scrollPane.setBounds(0, 100, sz.width, sz.height - 100);
   scrollPane.doLayout();
 }
Esempio n. 6
0
  private void initUI() {
    // Create tabbed pane with commands in it
    tabbedPane = new JTabbedPane();
    getContentPane().add(tabbedPane, BorderLayout.NORTH);

    tabbedPane.addTab("Book", null, createBookPane(), "View book information");
    tabbedPane.addTab("Author", null, createAuthorPane(), "View author information");
    tabbedPane.addTab("Customer", null, createCustomerPane(), "View customer information");
    tabbedPane.addTab("Borrow Book", null, createBorrowPane(), "Borrow books for a customer");
    tabbedPane.addTab("Return Book", null, createReturnPane(), "Return books for a customer");

    // Create output area with scrollpane
    outputArea = new JTextArea();
    // outputArea.setFont(new Font("Monospaced",Font.PLAIN,12));
    outputArea.setFont(new Font("Monospaced", Font.ROMAN_BASELINE, 12));
    outputArea.setEditable(false);
    outputArea.setFocusable(false);
    outputArea.setTabSize(2);
    JScrollPane sp = new JScrollPane(outputArea);
    sp.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);

    getContentPane().add(sp, BorderLayout.CENTER);

    // Create menus
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');

    JMenuItem clearTextMenuItem = new JMenuItem(clearTextAction);
    JMenuItem exitMenuItem = new JMenuItem(exitAction);

    fileMenu.add(clearTextMenuItem);
    fileMenu.addSeparator();
    fileMenu.add(exitMenuItem);

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);

    // Pack it all
    pack();
  }
  private void updateResult() {

    if (iResult == 0) {

      // in case 'help' has removed the grid
      if (bHelp) {
        pResult.removeAll();
        pResult.add(gScrollPane, BorderLayout.CENTER);
        pResult.doLayout();
        gResult.fireTableChanged(null);
        pResult.repaint();

        bHelp = false;
      }
    } else {
      showResultInText();
    }

    txtCommand.selectAll();
    txtCommand.requestFocus();
  }
  /** Display the file in the text area */
  private void showFile() {
    Scanner input = null;
    try {
      // Use a Scanner to read text from the file
      input = new Scanner(new File(jtfFilename.getText().trim()));

      // Read a line and append the line to the text area
      while (input.hasNext()) jtaFile.append(input.nextLine() + '\n');
    } catch (FileNotFoundException ex) {
      System.out.println("File not found: " + jtfFilename.getText());
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) input.close();
    }
  }
  private void insertTestData() {

    try {
      DatabaseManagerCommon.createTestTables(sStatement);
      refreshTree();
      txtCommand.setText(DatabaseManagerCommon.createTestData(sStatement));
      refreshTree();

      for (int i = 0; i < DatabaseManagerCommon.testDataSql.length; i++) {
        addToRecent(DatabaseManagerCommon.testDataSql[i]);
      }

      execute();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
Esempio n. 10
0
  @Override
  public void run() {
    // TODO Auto-generated method stub
    try {
      Socket s = new Socket(hostin, portin);
      InputStream ins = s.getInputStream();
      OutputStream os = s.getOutputStream();
      ir = new BufferedReader(new InputStreamReader(ins));
      pw = new PrintWriter(new OutputStreamWriter(os), true);

      pw.print(nick);
      while (true) {
        String line = ir.readLine();
        jta.append(line + "\n");
        jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMaximum());
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 11
0
  public void actionPerformed(ActionEvent evt) {
    String arg = evt.getActionCommand();
    if (arg.equals("Query")) { // 用户按下Query按钮
      ResultSet rs = null;
      try {
        String author = (String) authors.getSelectedItem();
        String publisher = (String) publishers.getSelectedItem();
        if (!author.equals("Any") && !publisher.equals("Any")) {
          if (authorPublisherQueryStmt == null) {
            //  根据用户选择的出版社名和作者名查询相关的书名和书价
            String authorPublisherQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, BooksAuthors, Authors, Publishers "
                    + "WHERE Authors.Author_Id = BooksAuthors.Author_Id AND "
                    + "BooksAuthors.ISBN = Books.ISBN AND "
                    + "Books.Publisher_Id = Publishers.Publisher_Id AND "
                    + "Authors.Name = ? AND "
                    + "Publishers.Name = ?";
            authorPublisherQueryStmt = con.prepareStatement(authorPublisherQuery);
          }

          authorPublisherQueryStmt.setString(1, author);
          authorPublisherQueryStmt.setString(2, publisher);
          rs = authorPublisherQueryStmt.executeQuery();
        } else if (!author.equals("Any") && publisher.equals("Any")) {
          if (authorQueryStmt == null) {
            //  根据用户选择的作者名查询相关的书名和书价
            String authorQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, BooksAuthors, Authors "
                    + "WHERE Authors.Author_Id = BooksAuthors.Author_Id AND "
                    + "BooksAuthors.ISBN = Books.ISBN AND "
                    + "Authors.Name = ?";
            authorQueryStmt = con.prepareStatement(authorQuery);
          }
          authorQueryStmt.setString(1, author);
          rs = authorQueryStmt.executeQuery();
        } else if (author.equals("Any") && !publisher.equals("Any")) {
          if (publisherQueryStmt == null) {
            //  根据用户选择的出版社名查询相关的书名和书价
            String publisherQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, Publishers "
                    + "WHERE Books.Publisher_Id = Publishers.Publisher_Id AND "
                    + "Publishers.Name = ?";
            publisherQueryStmt = con.prepareStatement(publisherQuery);
          }
          publisherQueryStmt.setString(1, publisher);
          rs = publisherQueryStmt.executeQuery();
        } else {
          if (allQueryStmt == null) {
            // 若用户未选任何信息,则输出所有的书名和对应的书价
            String allQuery = "SELECT Books.Price, Books.Title FROM Books";
            allQueryStmt = con.prepareStatement(allQuery);
          }
          rs = allQueryStmt.executeQuery();
        }

        result.setText("");
        while (rs.next()) result.append(rs.getString(1) + " | " + rs.getString(2) + "\n");
        rs.close();
      } catch (Exception e) {
        result.setText("Error " + e);
      }
    } else if (arg.equals("Change prices")) { //  用户选择“Change prices”按钮
      String publisher = (String) publishers.getSelectedItem();
      if (publisher.equals("Any")) result.setText("I am sorry, but I cannot do that.");
      else
        try {
          // 根据用户输入的新的书价更新Books表的数据
          String updateStatement =
              "UPDATE Books "
                  + "SET Price = Price + "
                  + priceChange.getText()
                  + " WHERE Books.Publisher_Id = "
                  + "(SELECT Publisher_Id FROM Publishers WHERE Name = '"
                  + publisher
                  + "')";
          int r = stmt.executeUpdate(updateStatement);
          result.setText(r + " records updated.");
        } catch (Exception e) {
          result.setText("Error " + e);
        }
    }
  }
  public void actionPerformed(ActionEvent ev) {

    String s = ev.getActionCommand();

    if (s == null) {
      if (ev.getSource() instanceof JMenuItem) {
        JMenuItem i;

        s = ((JMenuItem) ev.getSource()).getText();
      }
    }

    /*
    // button replace by toolbar
            if (s.equals("Execute")) {
                execute();
            } else
    */
    if (s.equals("Exit")) {
      windowClosing(null);
    } else if (s.equals("Transfer")) {
      Transfer.work(null);
    } else if (s.equals("Dump")) {
      Transfer.work(new String[] {"-d"});
    } else if (s.equals("Restore")) {
      Transfer.work(new String[] {"-r"});
    } else if (s.equals("Logging on")) {
      javaSystem.setLogToSystem(true);
    } else if (s.equals("Logging off")) {
      javaSystem.setLogToSystem(false);
    } else if (s.equals("Refresh Tree")) {
      refreshTree();
    } else if (s.startsWith("#")) {
      int i = Integer.parseInt(s.substring(1));

      txtCommand.setText(sRecent[i]);
    } else if (s.equals("Connect...")) {
      connect(ConnectionDialogSwing.createConnection(fMain, "Connect"));
      refreshTree();
    } else if (s.equals("Results in Grid")) {
      iResult = 0;

      pResult.removeAll();
      pResult.add(gScrollPane, BorderLayout.CENTER);
      pResult.doLayout();
      gResult.fireTableChanged(null);
      pResult.repaint();
    } else if (s.equals("Open Script...")) {
      JFileChooser f = new JFileChooser(".");

      f.setDialogTitle("Open Script...");

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setCurrentDirectory(new File(defDirectory));
      }

      int option = f.showOpenDialog(fMain);

      if (option == JFileChooser.APPROVE_OPTION) {
        File file = f.getSelectedFile();

        if (file != null) {
          StringBuffer buf = new StringBuffer();

          ifHuge = DatabaseManagerCommon.readFile(file.getAbsolutePath());

          if (4096 <= ifHuge.length()) {
            buf.append("This huge file cannot be edited. Please execute\n");
            txtCommand.setText(buf.toString());
          } else {
            txtCommand.setText(ifHuge);
          }
        }
      }
    } else if (s.equals("Save Script...")) {
      JFileChooser f = new JFileChooser(".");

      f.setDialogTitle("Save Script");

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setCurrentDirectory(new File(defDirectory));
      }

      int option = f.showSaveDialog(fMain);

      if (option == JFileChooser.APPROVE_OPTION) {
        File file = f.getSelectedFile();

        if (file != null) {
          DatabaseManagerCommon.writeFile(file.getAbsolutePath(), txtCommand.getText());
        }
      }
    } else if (s.equals("Save Result...")) {
      JFileChooser f = new JFileChooser(".");

      f.setDialogTitle("Save Result...");

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setCurrentDirectory(new File(defDirectory));
      }

      int option = f.showSaveDialog(fMain);

      if (option == JFileChooser.APPROVE_OPTION) {
        File file = f.getSelectedFile();

        if (file != null) {
          showResultInText();
          DatabaseManagerCommon.writeFile(file.getAbsolutePath(), txtResult.getText());
        }
      }
    } else if (s.equals("Results in Text")) {
      iResult = 1;

      pResult.removeAll();
      pResult.add(txtResultScroll, BorderLayout.CENTER);
      pResult.doLayout();
      showResultInText();
      pResult.repaint();
    } else if (s.equals("AutoCommit on")) {
      try {
        cConn.setAutoCommit(true);
      } catch (SQLException e) {
      }
    } else if (s.equals("AutoCommit off")) {
      try {
        cConn.setAutoCommit(false);
      } catch (SQLException e) {
      }
    } else if (s.equals("Commit")) {
      try {
        cConn.commit();
      } catch (SQLException e) {
      }
    } else if (s.equals("Insert test data")) {
      insertTestData();
    } else if (s.equals("Rollback")) {
      try {
        cConn.rollback();
      } catch (SQLException e) {
      }
    } else if (s.equals("Disable MaxRows")) {
      try {
        sStatement.setMaxRows(0);
      } catch (SQLException e) {
      }
    } else if (s.equals("Set MaxRows to 100")) {
      try {
        sStatement.setMaxRows(100);
      } catch (SQLException e) {
      }
    } else if (s.equals("SELECT")) {
      showHelp(DatabaseManagerCommon.selectHelp);
    } else if (s.equals("INSERT")) {
      showHelp(DatabaseManagerCommon.insertHelp);
    } else if (s.equals("UPDATE")) {
      showHelp(DatabaseManagerCommon.updateHelp);
    } else if (s.equals("DELETE")) {
      showHelp(DatabaseManagerCommon.deleteHelp);
    } else if (s.equals("CREATE TABLE")) {
      showHelp(DatabaseManagerCommon.createTableHelp);
    } else if (s.equals("DROP TABLE")) {
      showHelp(DatabaseManagerCommon.dropTableHelp);
    } else if (s.equals("CREATE INDEX")) {
      showHelp(DatabaseManagerCommon.createIndexHelp);
    } else if (s.equals("DROP INDEX")) {
      showHelp(DatabaseManagerCommon.dropIndexHelp);
    } else if (s.equals("CHECKPOINT")) {
      showHelp(DatabaseManagerCommon.checkpointHelp);
    } else if (s.equals("SCRIPT")) {
      showHelp(DatabaseManagerCommon.scriptHelp);
    } else if (s.equals("SHUTDOWN")) {
      showHelp(DatabaseManagerCommon.shutdownHelp);
    } else if (s.equals("SET")) {
      showHelp(DatabaseManagerCommon.setHelp);
    } else if (s.equals("Test Script")) {
      showHelp(DatabaseManagerCommon.testHelp);
    }
  }
Esempio n. 13
0
  public EchoAWT() throws UnknownHostException {

    super("채팅 프로그램");

    // 각종 정의
    h = new JPanel(new GridLayout(2, 3));
    m = new JPanel(new BorderLayout());
    f = new JPanel(new BorderLayout());
    s = new JPanel(new BorderLayout());
    login = new JPanel(new BorderLayout());

    // name = new JLabel(" 사용자 이름 ");
    name = new JLabel(" 메세지 입력 ");

    jta = new JTextArea();
    // clientList = new JTextArea(0, 10);
    clientList = new JList();

    jsp = new JScrollPane(jta);
    list = new JScrollPane(clientList);

    jtf = new JTextField("입력하세요.");
    hi = new JTextField("HOST IP 입력");
    pi = new JTextField("PORT 입력");
    localport = new JTextField("원하는 PORT 입력");
    lid = new JTextField("ID를 입력하세요.");
    lpw = new JTextField("PW를 입력하세요.");

    serveropen = new JButton("서버 오픈");
    textin = new JButton("입력");
    clientin = new JButton("서버 접속");
    conf = new JButton("로그인");
    join = new JButton("회원가입");

    addr = InetAddress.getLocalHost();

    // 사용자 해상도 및 창 크기 설정 및 가져오기.
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension screenSize = tk.getScreenSize();

    setSize(500, 500);
    Dimension d = getSize();

    // 각종 버튼 및 텍스트 필드 리스너
    jtf.addActionListener(this);
    hi.addActionListener(this);
    pi.addActionListener(this);
    localport.addActionListener(this);
    lid.addActionListener(this);
    lpw.addActionListener(this);
    conf.addActionListener(this);
    join.addActionListener(this);

    serveropen.addActionListener(this);
    clientin.addActionListener(this);
    textin.addActionListener(this);

    jtf.addFocusListener(this);
    hi.addFocusListener(this);
    pi.addFocusListener(this);
    localport.addFocusListener(this);
    lid.addFocusListener(this);
    lpw.addFocusListener(this);

    // 서버 접속
    h.add(hi);
    h.add(pi);
    h.add(clientin);

    // 서버 생성
    h.add(new JLabel("IP : " + addr.getHostAddress(), (int) CENTER_ALIGNMENT));
    h.add(localport);
    h.add(serveropen);

    // 채팅글창 글 작성 막기
    jta.setEditable(false);

    // 접속자 리스트 width 제한
    clientList.setFixedCellWidth(d.width / 3);

    // 입력 창
    f.add(name, "West");
    f.add(jtf, "Center");
    f.add(textin, "East");

    // 접속자 확인창
    s.add(new JLabel("접속자", (int) CENTER_ALIGNMENT), "North");
    s.add(list, "Center");
    // clientList.setEditable(false);

    // 메인 창
    m.add(jsp, "Center");
    m.add(s, "East");

    // 프레임 설정
    add(h, "North");
    add(m, "Center");
    add(f, "South");

    // 로그인 다이얼로그
    jd = new JDialog();
    jd.setTitle("채팅 로그인");
    jd.add(login);
    jd.setSize(200, 200);
    Dimension dd = jd.getSize();
    jd.setLocation(screenSize.width / 2 - (dd.width / 2), screenSize.height / 2 - (dd.height / 2));
    jd.setVisible(true);

    // 로그인창
    JPanel lm = new JPanel(new GridLayout(4, 1));
    lm.add(lid);
    lm.add(new Label());
    lm.add(lpw);
    lm.add(new Label());

    JPanel bt = new JPanel();
    bt.add(conf);
    bt.add(join);

    login.add(new Label(), "North");
    login.add(new Label(), "West");
    login.add(new Label(), "East");
    login.add(lm, "Center");
    login.add(bt, "South");

    // 창의 위치, 보임, EXIT 단추 활성화.
    setLocation(screenSize.width / 2 - (d.width / 2), screenSize.height / 2 - (d.height / 2));

    setVisible(false);

    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
Esempio n. 14
0
  public void actionPerformed(ActionEvent event) {

    // if clear button is pressed, clear all fields
    if (event.getSource() == clear_button) {
      // erase all fields

      taskname_field.setText("");
      taskdesc_field.setText("");

      priority_checkbox.setSelected(false);
      numberofdays_field.setText("");
      // isallocatedcheckbox.setSelected(false);
      duedate_field.setText("");
    }

    // if submit button is pressed, save all data onto database
    if (event.getSource() == submit_button) {
      try {
        {
          Calendar calendar = Calendar.getInstance();
          calendar.setTime(new Date()); // set to current date
          calendar.add(
              Calendar.DAY_OF_MONTH,
              Integer.parseInt(this.numberofdays_field.getText())
                  - 1); // add days required... then:
          // ^ subtract one day, because if task is created today and allocated tomorrow for one
          // day,
          // then it should be done by end of day tomorrow
          Date date = calendar.getTime(); // (see next *1) use this date to be the earliest
          // because of expected task duration

          /*This is a constraint
           * the date and the length of days that user expected to take
           * if not feasible then the program will say so
           * */
          // method compares the current date and the date that was entered by the user
          if (this.task_idfield.getText().length() != 7 // check chars
              || this.taskname_field.getText().length() > 50 // check chars
              || this.taskdesc_field.getText().length() > 50
              || ((Date) this.duedate_field.getValue()).compareTo(date)
                  < 0 // check that the date is possible (see last *1)
              || this.numberofdays_field.getText().length() > 2
              || this.numberofdays_field.getText().length() == 0 // check number of digits
              || Integer.parseInt(this.numberofdays_field.getText())
                  < 1) // check number of days required for task
          {
            JOptionPane.showMessageDialog(
                this,
                "Task ID has to be 7 chars; "
                    + "\n"
                    + "Description <= 50 chars; "
                    + "\n"
                    + "Because the expected duration of the task is "
                    + Integer.parseInt(this.numberofdays_field.getText())
                    + " days, the due date cannot be earlier than: "
                    + new StringBuffer(new SimpleDateFormat("dd/MM/yyyy").format(date)).toString()
                    + "; "
                    + "\n"
                    + "Task duration must be 2 digit number maximum and must be an integer greater than 0");
          } else

          // check if taskid_field is equals to any of the fields on the database

          if (task_idfield.equals("")) {
            JOptionPane.showMessageDialog(
                this, "Please insert an identification number for a task");

          } else // add constraint and tell customer to enter 7 values
          if (taskname_field.equals("")) {
            JOptionPane.showMessageDialog(this, "Please insert a name to identity the task");

          } else {

            // get all inputs from user inputs and store in variables
            taskid_input = task_idfield.getText();
            taskname_input = taskname_field.getText();
            taskdesc_input = taskdesc_field.getText();

            if (priority_checkbox.isSelected()) {
              priority_input = 1;
            } else {
              priority_input = 0;
            }

            // create and store date from user input
            date = (Date) duedate_field.getValue();

            // store number of days input from user
            numberofdays_input = Integer.parseInt(numberofdays_field.getText());

            // 	String[] column_names = { "Task ID", "Task Name", "Task Description", "Task
            // Priority", "Due Date", "Number of Days", "Is Allocated" , "Unallocateable" };

            task = new Object[8];
            task[0] = taskid_input;
            task[1] = taskname_input;
            task[2] = taskdesc_input;
            task[3] = priority_input;
            task[4] = date;
            task[5] = numberofdays_input;
            task[6] = 0;
            task[7] = 0;

            try {
              //
              SqlConnection.connect();

              SqlConnection.ps =
                  SqlConnection.connection.prepareStatement(
                      "INSERT  INTO TASK VALUES (?,?,?,?,?,?,?,?)");

              SqlConnection.ps.setString(1, taskid_input);
              SqlConnection.ps.setString(2, taskname_input);
              SqlConnection.ps.setString(3, taskdesc_input);
              SqlConnection.ps.setInt(4, priority_input);
              SqlConnection.ps.setDate(5, new java.sql.Date(date.getTime()));
              SqlConnection.ps.setInt(6, numberofdays_input);
              SqlConnection.ps.setInt(7, 0);
              SqlConnection.ps.setInt(8, 0);

              SqlConnection.ps.executeUpdate();

              // now enter skills into TASK SKILL database
              for (int i = 0; i < skill_list.size(); i++) {
                if (skill_list.get(i).isSelected()) {
                  String skillid = skill_list.get(i).getText();
                  SqlConnection.statement.executeUpdate(
                      "INSERT INTO TASKSKILL VALUES ('" + taskid_input + "', '" + skillid + "')");
                }
              }

              SqlConnection.ps.close();
            } catch (SQLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            // SqlConnection.ps.close();
            SqlConnection.closeConnection();
            this.setVisible(false);
          }
        }

      } catch (Exception exc) {
        JOptionPane.showMessageDialog(
            this,
            "Check your inputs:"
                + "\n"
                + "Priority has to be a 1-digit number;"
                + "\n"
                + "Date has to be in the format dd/MM/yyyy;"
                + "\n"
                + "Task length has to be 2-digit number");
        System.out.println(exc);
      }
    }
    // display dialog box asking task manager if they want to quit,
    // if task manager does not want to quit, go back to adding more tasks
    // if customer quits, close the dialog box and the frame

    // now close the window after saving
  }
Esempio n. 15
0
    public void actionPerformed(ActionEvent e) {
      String t = fid.getText();
      // char[] t2=fpass.getPassword();
      String t2 = fpass.getText();

      try {
        DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        Connection con =
            DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe", "system", "9696030257");
        Statement st = con.createStatement();
        ResultSet rs =
            st.executeQuery(
                "select * from database where userid='" + t + "' AND password='******'");
        rs.next();
        String g = rs.getString("userid");
        String h = rs.getString("password");
        String i = rs.getString("mob");
        String j = rs.getString("dob");
        if (g.equals(t) && h.equals(t2)) {
          // JOptionPane.showMessageDialog(null,"WoW  !!  You  Are  a  Valid  User");
          JFrame jf1 = new JFrame("About Saras");
          jf1.setBounds(500, 40, 500, 500);
          jf1.setVisible(true);
          jf1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          jf1.setLayout(null);
          String ab =
              "\n\nHis Name is Saraswatendra Singh.\nHe is pursuing B.Tech from ABES Engineering College(032) Ghaziabad U.P.\nHe is belong from VARANASI which is also called BANARAS.\nHis Email and Facebook id is  <*****@*****.**>\n\n\n \t\t\tTHANK YOU";
          String bc =
              "\n\n\nABOUT YOU:-\n\n\t UserId is < "
                  + g
                  + " >\n\t Password is <"
                  + h
                  + " > \n\t Mobile No is < "
                  + i
                  + " >\n\t Date Of Birth(dd/mm/yyyy) is < "
                  + j
                  + " >\n \n\nABOUT DEVELOPER:-"
                  + ab;
          JTextArea about = new JTextArea(bc);
          jf1.add(about);
          about.setBounds(0, 0, 500, 500);
          JButton rest = new JButton("ResetPassword");
          about.add(rest);
          rest.setBounds(30, 400, 150, 20);
          Cursor k1 = new Cursor(Cursor.HAND_CURSOR);
          rest.setCursor(k1);
          rest.addActionListener(new ResetPassword());
          JButton restmob = new JButton("ResetMobileNo");
          about.add(restmob);
          restmob.setBounds(230, 400, 150, 20);
          Cursor k2 = new Cursor(Cursor.HAND_CURSOR);
          restmob.setCursor(k2);
          restmob.addActionListener(new ResetMob());
        }
      } catch (Exception ex) {
        System.out.print(ex);
        JOptionPane.showMessageDialog(
            null,
            "UserId  or  Password  MissMatched !!!  please  Enter  Valid  UserId and Password");
      }
    }
  private void clear() {

    ifHuge = "";

    txtCommand.setText(ifHuge);
  }
Esempio n. 17
0
 private void appendOutput(String str) {
   if (str != null && !str.equals("")) outputArea.append(str + "\n\n");
   outputArea.setCaretPosition(outputArea.getDocument().getLength());
 }
  private void execute() {

    gResult.clear();

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    try {
      lTime = System.currentTimeMillis();

      sStatement.execute(sCmd);

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = "" + r;

        gResult.addRow(g);
      }

      lTime = System.currentTimeMillis() - lTime;

      addToRecent(txtCommand.getText());
      gResult.fireTableChanged(null);
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
      gResult.fireTableChanged(null);
    }

    updateResult();
    System.gc();
  }
  private void testPerformance() {

    String all = txtCommand.getText();
    StringBuffer b = new StringBuffer();
    long total = 0;

    for (int i = 0; i < all.length(); i++) {
      char c = all.charAt(i);

      if (c != '\n') {
        b.append(c);
      }
    }

    all = b.toString();

    String g[] = new String[4];

    g[0] = "ms";
    g[1] = "count";
    g[2] = "sql";
    g[3] = "error";

    gResult.setHead(g);

    int max = 1;

    lTime = System.currentTimeMillis() - lTime;

    while (!all.equals("")) {
      int i = all.indexOf(';');
      String sql;

      if (i != -1) {
        sql = all.substring(0, i);
        all = all.substring(i + 1);
      } else {
        sql = all;
        all = "";
      }

      if (sql.startsWith("--#")) {
        max = Integer.parseInt(sql.substring(3));

        continue;
      } else if (sql.startsWith("--")) {
        continue;
      }

      g[2] = sql;

      long l = 0;

      try {
        l = DatabaseManagerCommon.testStatement(sStatement, sql, max);
        total += l;
        g[0] = "" + l;
        g[1] = "" + max;
        g[3] = "";
      } catch (SQLException e) {
        g[0] = g[1] = "n/a";
        g[3] = e.toString();
      }

      gResult.addRow(g);
      System.out.println(l + " ms : " + sql);
    }

    g[0] = "" + total;
    g[1] = "total";
    g[2] = "";

    gResult.addRow(g);

    lTime = System.currentTimeMillis() - lTime;

    updateResult();
  }
Esempio n. 20
0
  public QueryDBFrame() {
    setTitle("QueryDB");
    setSize(400, 300);
    addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });

    getContentPane().setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    authors = new JComboBox();
    authors.setEditable(false);
    authors.addItem("Any");

    publishers = new JComboBox();
    publishers.setEditable(false);
    publishers.addItem("Any");

    result = new JTextArea(4, 50);
    result.setEditable(false);

    priceChange = new JTextField(8);
    priceChange.setText("-5.00");

    try {
      //  连接数据库
      con = getConnection();
      stmt = con.createStatement();

      // 将数据库中的作者名添加到组合框
      String query = "SELECT Name FROM Authors";
      ResultSet rs = stmt.executeQuery(query);
      while (rs.next()) authors.addItem(rs.getString(1));

      //  将出版社名添加到组合框
      query = "SELECT Name FROM Publishers";
      rs = stmt.executeQuery(query);
      while (rs.next()) publishers.addItem(rs.getString(1));
    } catch (Exception e) {
      result.setText("Error " + e);
    }

    gbc.fill = GridBagConstraints.NONE;
    gbc.weightx = 100;
    gbc.weighty = 100;
    add(authors, gbc, 0, 0, 2, 1);

    add(publishers, gbc, 2, 0, 2, 1);

    gbc.fill = GridBagConstraints.NONE;
    JButton queryButton = new JButton("Query");
    queryButton.addActionListener(this);
    add(queryButton, gbc, 0, 1, 1, 1);

    JButton changeButton = new JButton("Change prices");
    changeButton.addActionListener(this);
    add(changeButton, gbc, 2, 1, 1, 1);

    gbc.fill = GridBagConstraints.HORIZONTAL;
    add(priceChange, gbc, 3, 1, 1, 1);

    gbc.fill = GridBagConstraints.BOTH;
    add(result, gbc, 0, 2, 4, 1);
  }
  void main() {

    CommonSwing.setDefaultColor();

    fMain = new JFrame("HSQL Database Manager");

    // (ulrivo): An actual icon.
    fMain.getContentPane().add(createToolBar(), "North");
    fMain.setIconImage(CommonSwing.getIcon());
    fMain.addWindowListener(this);

    JMenuBar bar = new JMenuBar();

    // used shortcuts: CERGTSIUDOLM
    String fitems[] = {
      "-Connect...", "--", "-Open Script...", "-Save Script...", "-Save Result...", "--", "-Exit"
    };

    addMenu(bar, "File", fitems);

    String vitems[] = {"RRefresh Tree", "--", "GResults in Grid", "TResults in Text"};

    addMenu(bar, "View", vitems);

    String sitems[] = {
      "SSELECT",
      "IINSERT",
      "UUPDATE",
      "DDELETE",
      "---",
      "-CREATE TABLE",
      "-DROP TABLE",
      "-CREATE INDEX",
      "-DROP INDEX",
      "--",
      "-CHECKPOINT",
      "-SCRIPT",
      "-SET",
      "-SHUTDOWN",
      "--",
      "-Test Script"
    };

    addMenu(bar, "Command", sitems);

    mRecent = new JMenu("Recent");

    bar.add(mRecent);

    String soptions[] = {
      "-AutoCommit on",
      "-AutoCommit off",
      "OCommit",
      "LRollback",
      "--",
      "-Disable MaxRows",
      "-Set MaxRows to 100",
      "--",
      "-Logging on",
      "-Logging off",
      "--",
      "-Insert test data"
    };

    addMenu(bar, "Options", soptions);

    String stools[] = {"-Dump", "-Restore", "-Transfer"};

    addMenu(bar, "Tools", stools);
    fMain.setJMenuBar(bar);
    initGUI();

    sRecent = new String[iMaxRecent];

    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension size = fMain.getSize();

    // (ulrivo): full size on screen with less than 640 width
    if (d.width >= 640) {
      fMain.setLocation((d.width - size.width) / 2, (d.height - size.height) / 2);
    } else {
      fMain.setLocation(0, 0);
      fMain.setSize(d);
    }

    fMain.show();

    // (ulrivo): load query from command line
    if (defScript != null) {
      if (defDirectory != null) {
        defScript = defDirectory + File.separator + defScript;
      }

      // if insert stmet is thousands of records...skip showing it
      // as text.  Too huge.
      StringBuffer buf = new StringBuffer();

      ifHuge = DatabaseManagerCommon.readFile(defScript);

      if (4096 <= ifHuge.length()) {
        buf.append("This huge file cannot be edited. Please execute\n");
        txtCommand.setText(buf.toString());
      } else {
        txtCommand.setText(ifHuge);
      }
    }

    txtCommand.requestFocus();
  }
Esempio n. 22
0
  public void createGUI() {
    setLayout(new BorderLayout());
    JPanel topPan = new JPanel(new BorderLayout());
    //        topPan.setBorder(BorderFactory.createRaisedSoftBevelBorder());
    JPanel topCentPan = new JPanel();
    JLabel titleLab = new JLabel();
    titleLab.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 15));
    topCentPan.add(titleLab);

    JPanel topRightPan = new JPanel();
    //        Cursor handCursor = new Cursor(Cursor.HAND_CURSOR);
    replyBut = new JButton(new ImageIcon("src\\images\\replyIcon.png"));
    replyBut.setBorder(BorderFactory.createEmptyBorder());
    replyBut.addActionListener(this);
    replyBut.setCursor(new Cursor(Cursor.HAND_CURSOR));
    replyBut.setToolTipText("Reply");
    replyBut.setContentAreaFilled(false);
    replyBut.setRolloverEnabled(true);
    forwardBut = new JButton(new ImageIcon("src\\images\\forwardIcon.png"));
    forwardBut.setBorder(BorderFactory.createEmptyBorder());
    forwardBut.addActionListener(this);
    forwardBut.setCursor(new Cursor(Cursor.HAND_CURSOR));
    forwardBut.setToolTipText("Forward");
    forwardBut.setContentAreaFilled(false);
    forwardBut.setRolloverEnabled(true);
    topRightPan.add(replyBut);
    topRightPan.add(forwardBut);
    topPan.add(topCentPan, "Center");
    topPan.add(topRightPan, "East");

    JPanel centPan = new JPanel(new BorderLayout());
    JPanel centTopPan = new JPanel(new BorderLayout());
    JPanel centTopLeftPan = new JPanel();
    JLabel fromLab = new JLabel();
    fromLab.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 12));
    JTextArea contentTA = new JTextArea();
    //            JEditorPane contentTA = new JEditorPane(JEditorPane.W3C_LENGTH_UNITS,"");
    contentTA.setLineWrap(true);
    contentTA.setEditable(false);
    centTopLeftPan.add(fromLab);
    JPanel centTopRightPan = new JPanel();
    JLabel dateLab = new JLabel();
    dateLab.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11));
    centTopRightPan.add(dateLab);
    centTopPan.add(centTopLeftPan, "West");
    centTopPan.add(centTopRightPan, "East");
    centPan.add(centTopPan, "North");
    centPan.add(new JScrollPane(contentTA), "Center");

    add(topPan, "North");
    add(centPan, "Center");

    try {
      workingSet.absolute(pointer + 1);
      msgID = Home.bodyPan.msgID[pointer];
      titleLab.setText(workingSet.getString("subject"));
      fromLab.setText("From: " + workingSet.getString("mail_addresses"));
      dateLab.setText(workingSet.getString("sent_date"));
      contentTA.setText(workingSet.getString("content"));
    } catch (SQLException sqlExc) {
      JOptionPane.showMessageDialog(this, sqlExc, "EXCEPTION", JOptionPane.ERROR_MESSAGE);
    }
    Home.bodyPan.remove(Home.bodyPan.contentPan);
    Home.bodyPan.contentPan = new JScrollPane(this);
    Home.bodyPan.add(Home.bodyPan.contentPan);
    Home.home.homeFrame.setVisible(true);
  }
  /** Method declaration */
  private void showResultInText() {

    String col[] = gResult.getHead();
    int width = col.length;
    int size[] = new int[width];
    Vector data = gResult.getData();
    String row[];
    int height = data.size();

    for (int i = 0; i < width; i++) {
      size[i] = col[i].length();
    }

    for (int i = 0; i < height; i++) {
      row = (String[]) data.elementAt(i);

      for (int j = 0; j < width; j++) {
        int l = row[j].length();

        if (l > size[j]) {
          size[j] = l;
        }
      }
    }

    StringBuffer b = new StringBuffer();

    for (int i = 0; i < width; i++) {
      b.append(col[i]);

      for (int l = col[i].length(); l <= size[i]; l++) {
        b.append(' ');
      }
    }

    b.append(NL);

    for (int i = 0; i < width; i++) {
      for (int l = 0; l < size[i]; l++) {
        b.append('-');
      }

      b.append(' ');
    }

    b.append(NL);

    for (int i = 0; i < height; i++) {
      row = (String[]) data.elementAt(i);

      for (int j = 0; j < width; j++) {
        b.append(row[j]);

        for (int l = row[j].length(); l <= size[j]; l++) {
          b.append(' ');
        }
      }

      b.append(NL);
    }

    b.append(NL + height + " row(s) in " + lTime + " ms");
    txtResult.setText(b.toString());
  }