예제 #1
0
파일: FoodEditor.java 프로젝트: kba/neon
 protected void load() {
   nameField.setText(data.name);
   costField.setValue(data.cost);
   colorBox.setSelectedItem(data.color);
   charField.setValue(data.text);
   weightField.setValue(data.weight);
   spellBox.setSelectedItem(data.spell);
 }
예제 #2
0
 public void readValues() {
   portTextField.setValue(getPortFromOptionsFile());
   memoryTextField.setValue(getMemoryLimitFromOptionsFile());
   contextPathComboBox.setSelectedItem(getContextPathFromOptionsFile());
   int httpsPort = getHttpsPortFromOptionsFile();
   boolean httpsEnabled = httpsPort != 0;
   httpsPortTextField.setValue(httpsEnabled ? httpsPort : 443);
   httpsPortTextField.setEnabled(httpsEnabled);
   httpsPortCheckBox.setSelected(httpsEnabled);
 }
예제 #3
0
  /** Create the frame */
  public DateTimer() {
    super();
    setTitle("v14 CountDown");
    getContentPane().setLayout(null);
    setBounds(100, 100, 500, 375);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JLabel finishtimeLabel = new JLabel();
    finishtimeLabel.setText("CountDown Time");
    finishtimeLabel.setBounds(10, 36, 119, 15);
    getContentPane().add(finishtimeLabel);
    finishtime =
        new JFormattedTextField(
            new DateFormatter(new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa", Locale.ENGLISH)));
    finishtime.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {}
        });

    finishtime.setValue(new Date());
    finishtime.setBounds(135, 34, 187, 19);
    getContentPane().add(finishtime);

    final JButton startButton = new JButton();
    startButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {
            startCount();
          }
        });
    startButton.setText("Start!!!");
    startButton.setBounds(334, 31, 111, 25);
    getContentPane().add(startButton);

    countLabel = new JLabel();
    countLabel.setHorizontalAlignment(SwingConstants.CENTER);
    countLabel.setHorizontalTextPosition(SwingConstants.CENTER);
    countLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
    countLabel.setBorder(new LineBorder(Color.black, 1, false));
    countLabel.setText("Countdown not Started");
    countLabel.setBounds(10, 162, 435, 47);
    getContentPane().add(countLabel);

    final JLabel credits = new JLabel();
    credits.setHorizontalAlignment(SwingConstants.RIGHT);
    credits.setText("");
    credits.setBounds(253, 328, 237, 15);
    getContentPane().add(credits);
  }
예제 #4
0
 public void setParameters(ProblemDescriptors descriptors) {
   if (descriptors == null) {
     problemSizeEdit.setText("");
     stockLengthEdit.setText("");
     orderLengthLowerBoundEdit.setText("");
     orderLengthUpperBoundEdit.setText("");
     averageDemandEdit.setText("");
   } else {
     problemSizeEdit.setValue(descriptors.getSize());
     stockLengthEdit.setValue(descriptors.getStockLength());
     orderLengthLowerBoundEdit.setValue(descriptors.getOrderLengthLowerBound());
     orderLengthUpperBoundEdit.setValue(descriptors.getOrderLengthUpperBound());
     averageDemandEdit.setValue(descriptors.getAverageDemand());
   }
 }
예제 #5
0
 public boolean verify(JComponent input) {
   if (input instanceof JFormattedTextField) {
     JFormattedTextField ftf = (JFormattedTextField) input;
     JFormattedTextField.AbstractFormatter formatter = ftf.getFormatter();
     if (formatter != null) {
       String text = ftf.getText();
       try {
         formatter.stringToValue(text);
         return true;
       } catch (ParseException pe) {
         return false;
       }
     }
   }
   return true;
 }
예제 #6
0
파일: FoodEditor.java 프로젝트: kba/neon
 protected void save() {
   data.name = nameField.getText();
   try {
     costField.commitEdit();
     data.cost = ((Long) costField.getValue()).intValue();
   } catch (ParseException e) {
     data.cost = 0;
   }
   data.color = colorBox.getSelectedItem().toString();
   data.text = charField.getText();
   data.weight = Float.parseFloat(weightField.getText());
   if (spellBox.getSelectedItem() != null) {
     data.spell = spellBox.getSelectedItem().toString();
   }
   data.setPath(Editor.getStore().getActive().get("id"));
 }
예제 #7
0
  public void acessaTecladoNumerico(
      JFormattedTextField campoAtual, JFormattedTextField proximoCampo) {

    if (Inicio.isMobile()) {
      campoAtual.setBackground(new Color(255, 255, 190));
      TelaTecladoNumerico tela = new TelaTecladoNumerico(null, true, campoAtual, proximoCampo);
      tela.setVisible(true);
    }
  }
예제 #8
0
 private int getMemoryLimit() throws SettingsException {
   int memoryLimit;
   try {
     memoryLimit = ((Number) memoryTextField.getValue()).intValue();
     if (memoryLimit < 5) {
       throw new Exception();
     }
   } catch (Exception x) {
     throw new SettingsException("Please specify a valid memory limit.", x);
   }
   return memoryLimit;
 }
예제 #9
0
 private int getPort() throws SettingsException {
   int port;
   try {
     port = ((Number) portTextField.getValue()).intValue();
     if (port < 1 || port > 65535) {
       throw new Exception();
     }
   } catch (Exception x) {
     throw new SettingsException("Please specify a valid port number.", x);
   }
   return port;
 }
예제 #10
0
  public ProblemDescriptors getParameters() {
    if (Utils.isEmpty(problemSizeEdit.getText())
        || Utils.isEmpty(stockLengthEdit.getText())
        || Utils.isEmpty(orderLengthLowerBoundEdit.getText())
        || Utils.isEmpty(orderLengthUpperBoundEdit.getText())
        || Utils.isEmpty(averageDemandEdit.getText())) {
      return null;
    }

    int problemSize = ((Number) problemSizeEdit.getValue()).intValue();
    int stockLength = ((Number) stockLengthEdit.getValue()).intValue();
    double orderLengthLowerBound = ((Number) orderLengthLowerBoundEdit.getValue()).doubleValue();
    double orderLengthUpperBound = ((Number) orderLengthUpperBoundEdit.getValue()).doubleValue();
    int averageDemand = ((Number) averageDemandEdit.getValue()).intValue();

    ProblemDescriptors descriptors =
        new ProblemDescriptors(
            problemSize, stockLength, orderLengthLowerBound, orderLengthUpperBound, averageDemand);

    return descriptors;
  }
 public void actionPerformed(ActionEvent e) {
   if (e.getSource() == submit) {
     if (rb1.isSelected()) {
       JFrame frame = Application.getFrame();
       if (typeCodes.isEmpty()) {
         JOptionPane.showMessageDialog(
             frame,
             "Please select at least one toponym type.",
             "Error",
             JOptionPane.ERROR_MESSAGE);
       } else {
         Application.getMainCitiesPanel(this, typeCodes, 0, 0.0);
       }
     } else if (rb2.isSelected()) {
       JFrame frame = Application.getFrame();
       try {
         nCities = new Integer(nCitiesField.getText());
         if (nCities <= 0) throw new NumberFormatException();
         typeCodes = new ArrayList<String>();
         Application.getMainCitiesPanel(this, typeCodes, nCities, 0.0);
       } catch (NumberFormatException ex) {
         JOptionPane.showMessageDialog(
             frame, "Please enter a positive integer number.", "Error", JOptionPane.ERROR_MESSAGE);
       }
     } else {
       JFrame frame = Application.getFrame();
       try {
         Double dist = new Double(distField.getText());
         if (dist <= 0) throw new NumberFormatException();
         typeCodes = new ArrayList<String>();
         Application.getMainCitiesPanel(this, typeCodes, 0, dist);
       } catch (NumberFormatException ex) {
         JOptionPane.showMessageDialog(
             frame, "Please enter a positive number.", "Error", JOptionPane.ERROR_MESSAGE);
       }
     }
   } else {
     Application.getOptionPanel(this, countryName);
   }
 }
  public Job getEditingJob() {
    Job job = new Job();

    job.setId(id);
    job.setName(jobNameTextField.getText());
    job.setEnabled(enabledCheckBox.isSelected());
    if (scheduledRadioButton.isSelected()) {
      job.setIntervalUnit(Job.getUnits()[intervalUnitComboBox.getSelectedIndex()]);
      job.setIntervalPeriod(parseInt(intervalFormattedTextField.getText()));
    }

    return job;
  }
  @Override
  protected void paintComponent(Graphics graphics) {
    int width = getWidth() - getInsets().left - getInsets().right;
    int height = getHeight() - getInsets().top - getInsets().bottom;

    Graphics2D g2d = (Graphics2D) graphics;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setColor(backgroundColor);

    g2d.fillRoundRect(getInsets().left, getInsets().top, width, height, 8, 8);

    super.paintComponent(
        graphics); // To change body of overridden methods use File | Settings | File Templates.
  }
예제 #14
0
  @Override
  public Object stringToValue(String text) {
    Pattern pattern = getPattern();
    Matcher matcher = pattern.matcher(text);

    if (matcher.matches()) {
      setMatcher(matcher);
      // set text to be green
      dce.setForeground(foreground);
      dce.setBackground(backgound);

      return text;
    } else {
      // set text to be red when it's not correct
      dce.setForeground(warningForeground);
      dce.setBackground(warningBackground);

      if (discardOnInvalid) {
        return "";
      }

      return text;
    }
  }
예제 #15
0
  private int getHttpsPort() throws SettingsException {
    if (!httpsPortCheckBox.isSelected()) {
      return 0;
    }

    int port;
    try {
      port = ((Number) httpsPortTextField.getValue()).intValue();
      if (port < 1 || port > 65535) {
        throw new Exception();
      }
    } catch (Exception x) {
      throw new SettingsException("Please specify a valid https port number.", x);
    }
    return port;
  }
  @Override
  protected void paintSafely(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2d.setPaint(
        new GradientPaint(
            0, 0, new Color(63, 63, 63), 0, textFormattedField.getHeight(), new Color(76, 76, 76)));
    g2d.fillRect(0, 0, textFormattedField.getWidth(), textFormattedField.getHeight());

    g2d.setPaint(
        new GradientPaint(
            0, 0, new Color(21, 21, 21), 0, textFormattedField.getHeight(), new Color(24, 24, 24)));
    g2d.fillRect(1, 1, textFormattedField.getWidth() - 2, textFormattedField.getHeight() - 2);

    g2d.setPaint(new Color(53, 53, 53));
    g2d.fillRect(2, 2, textFormattedField.getWidth() - 4, textFormattedField.getHeight() - 4);
    super.paintSafely(g);
  }
예제 #17
0
  /** Sets up the panel. */
  private void setupPanel() {

    // layout the panel
    setLayout(new GridLayout(1, 1));
    add(panelMain);

    setPreferredSize(new Dimension(-1, 35));
    setMaximumSize(new Dimension(500, 35));

    // set the scale types
    comboboxType.setModel(
        new DefaultComboBoxModel(
            (ScaleType[])
                ScaleType.getEnumList().toArray(new ScaleType[ScaleType.getEnumList().size()])));

    DefaultFormatterFactory formatterTare =
        new DefaultFormatterFactory(new NumberFormatter(formatTare));

    textfieldTare.setFormatterFactory(formatterTare);
  }
  public void setJob(Job job) {
    jobNameTextField.setEnabled(false);
    enabledCheckBox.setEnabled(true);
    saveButton.setEnabled(true);

    id = job.getId();
    jobNameTextField.setText(job.getName());
    enabledCheckBox.setSelected(job.isEnabled());
    if (job.getIntervalUnit() == null) {
      onDemandRadioButton.setSelected(true);
    } else {
      scheduledRadioButton.setSelected(true);
      intervalFormattedTextField.setText(String.valueOf(job.getIntervalPeriod()));

      int index = 0;
      String[] units = Job.getUnits();
      for (int i = 0; i < units.length; i++) if (job.getIntervalUnit().equals(units[i])) index = i;

      intervalUnitComboBox.setSelectedIndex(index);
    }
  }
예제 #19
0
  /** Setup field listeners. */
  private void initializeFieldListeners() {

    checkboxMonitor.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {

            model.setMonitor(new Boolean(checkboxMonitor.isSelected()));
          }
        });

    textfieldName.addFocusListener(
        new FocusAdapter() {
          public void focusLost(FocusEvent event) {
            model.setName(textfieldName.getText());
          }
        });

    textfieldTare.addFocusListener(
        new FocusAdapter() {
          public void focusLost(FocusEvent event) {

            try {
              textfieldTare.commitEdit();
            } catch (ParseException e) {
              logger.warn(e);
            }

            model.setTare((Double) textfieldTare.getValue());
          }
        });

    comboboxType.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            model.setScaletype((ScaleType) comboboxType.getSelectedItem());
          }
        });
  }
예제 #20
0
  private void createZoomTextField() {
    mZoomTextField = new JFormattedTextField(new DecimalFormat("##0.00%"));
    mZoomTextField.setFocusLostBehavior(JFormattedTextField.REVERT);
    mZoomTextField.setHorizontalAlignment(SwingConstants.CENTER);
    mZoomTextField.setColumns(6);
    mZoomTextField.setMinimumSize(mZoomTextField.getPreferredSize());

    mZoomTextField.addActionListener(
        (x) -> mImagePresentationModel.setZoom(((Number) mZoomTextField.getValue()).doubleValue()));

    mImagePresentationModel.addListener(
        new ImagePresentationModel.Listener() {
          @Override
          public void onVisibleImageContentUpdate() {
            mZoomTextField.setValue(mImagePresentationModel.getZoom());
          }

          @Override
          public void onImageChange() {
            onVisibleImageContentUpdate();
          }
        });
  }
  public void init() {
    // 添加按钮
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(okButton);

    mainPanel.setLayout(new GridLayout(0, 3));
    mainWin.add(mainPanel, BorderLayout.CENTER);

    JFormattedTextField intField0 =
        new JFormattedTextField(
            new InternationalFormatter(NumberFormat.getIntegerInstance()) {
              protected DocumentFilter getDocumentFilter() {
                return new NumberFilter();
              }
            });
    intField0.setValue(100);
    addRow("只接受数字的文本框", intField0);

    JFormattedTextField intField1 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField1.setValue(new Integer(100));
    // 添加输入校验器
    intField1.setInputVerifier(new FormattedTextFieldVerifier());
    addRow("带输入校验器的文本框", intField1);

    // 创建自定义格式器对象
    IPAddressFormatter ipFormatter = new IPAddressFormatter();
    ipFormatter.setOverwriteMode(false);
    // 以自定义格式器对象创建格式化文本框
    JFormattedTextField ipField = new JFormattedTextField(ipFormatter);
    ipField.setValue(new byte[] {(byte) 192, (byte) 168, 4, 1});
    addRow("IP地址格式", ipField);

    mainWin.add(buttonPanel, BorderLayout.SOUTH);
    mainWin.pack();
    mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainWin.setVisible(true);
  }
예제 #22
0
  public void actionPerformed(ActionEvent a) {

    int code = 0;
    String roomtypeCompare_arr = null;
    String roomtypeCompare_dep = null;
    if ("book".equals(a.getActionCommand())) {
      try {
        Class.forName("com.mysql.jdbc.Driver");

        // Database connection information. Please note that when porting the code, you must have
        // the jdbc Driver installed where the code is running.
        Connection con =
            DriverManager.getConnection(
                "jdbc:mysql://67.20.111.85:3306/jeehtove_caliking?relaxAutoCommit=true",
                "jeehtove_ck",
                "Z_^PBBZT+kcy");

        // The SELECT query
        String query_arr =
            "SELECT * from reservations WHERE checkin BETWEEN '"
                + checkindateField.getText()
                + "' AND '"
                + checkoutdateField.getText()
                + "'";
        String query_dep =
            "SELECT * from reservations WHERE checkout BETWEEN '"
                + checkindateField.getText()
                + "' AND '"
                + checkoutdateField.getText()
                + "'";

        Statement stmt_arr = con.createStatement();
        Statement stmt_dep = con.createStatement();
        Statement stmt_insert = con.createStatement();
        ResultSet result_arr = stmt_arr.executeQuery(query_arr);
        ResultSet result_dep = stmt_dep.executeQuery(query_dep);

        // Get room type from radio buttons
        String room_type;
        if (standardRoom.isSelected()) {
          room_type = "Standard";
          code = 1;
        } else if (familyRoom.isSelected()) {
          room_type = "Family";
          code = 2;
        } else {
          room_type = "Suite";
          code = 3;
        }

        bookRoom();
        // ResultSet rs=stmt.executeQuery("select * from emp");
        /*if (!result_arr.next() && !result_dep.next()){

        	bookRoom();

        	//Query Prep for checking for open rooms
        	/*String query_checkrooms = "SELECT * FROM makereservation_rooms WHERE type = '" + code + "' AND booked = '0';";
        	Statement stmt_checkrooms = con.createStatement();
        	ResultSet checkrooms = stmt_checkrooms.executeQuery(query_checkrooms);

        	if (checkrooms.next()){
        	String getroomnumber = checkrooms.getString("room");
        	String insert = "INSERT INTO `reservations` VALUES ('" + getroomnumber + "', '" +  checkindateField.getText() + "', '" +  checkoutdateField.getText() + "',  '" + room_type + "',  '" + nameField.getText() + "');";
        	String bookroom = "UPDATE `makereservation_rooms` SET booked = '1' WHERE room = '" + getroomnumber + "';";
        	//System.out.println(insert);
        	int rs=stmt_insert.executeUpdate(insert);
        	int cr=stmt_checkrooms.executeUpdate(bookroom);
        	con.commit();
        	System.out.println("Room Booked!");
        }

        	else System.out.println("All " + room_type + " rooms are booked for the time requested.");
        }

        else {
        	if (result_arr.next()){
        		roomtypeCompare_arr = result_arr.getString("type");
        		System.out.println("(arrival) Does " + roomtypeCompare_arr + " equal " + room_type + "?");
        		if (roomtypeCompare_arr.equals(room_type)){
        			String  checkindateDB_arr = result_arr.getString("checkin");
        			String  checkoutdateDB_arr = result_arr.getString("checkout");
        			System.out.println("There is a room booked on " +  checkindateDB_arr + " that checks out on " +  checkoutdateDB_arr + ". Please select another date.");
        		}

        		else {

        			System.out.println("Room Booked!");
        		}
        	}
        }
        	//System.out.println(query_dep);
        	if (result_dep.next()){
        		roomtypeCompare_dep = result_dep.getString("type");
        		System.out.println("(departure) Does " + roomtypeCompare_dep + " equal " + room_type + "?");
        		if (roomtypeCompare_dep.equals(room_type)){
        			String  checkindateDB_dep = result_dep.getString("checkin");
        			String  checkoutdateDB_dep = result_dep.getString("checkout");
        			System.out.println("There is a room booked on " +  checkindateDB_dep + " that checks out on " +  checkoutdateDB_dep + ". Please select another date.");
        		}

        		else {
        			System.out.println("Room Booked!");
        		}
        	}*/
        con.close();

      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }
예제 #23
0
  private void addInformationPanel() {
    // Create UI elements for connection information.
    JPanel informationPanel = new JPanel();
    informationPanel.setLayout(new BorderLayout());

    // Add the Host information
    JPanel connPanel = new JPanel();
    connPanel.setLayout(new GridBagLayout());
    connPanel.setBorder(BorderFactory.createTitledBorder("Connection information"));

    JLabel label = new JLabel("Host: ");
    label.setMinimumSize(new java.awt.Dimension(150, 14));
    label.setMaximumSize(new java.awt.Dimension(150, 14));
    connPanel.add(
        label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0));
    JFormattedTextField field = new JFormattedTextField(connection.getServiceName());
    field.setMinimumSize(new java.awt.Dimension(150, 20));
    field.setMaximumSize(new java.awt.Dimension(150, 20));
    field.setEditable(false);
    field.setBorder(null);
    connPanel.add(
        field, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0));

    // Add the Port information
    label = new JLabel("Port: ");
    label.setMinimumSize(new java.awt.Dimension(150, 14));
    label.setMaximumSize(new java.awt.Dimension(150, 14));
    connPanel.add(
        label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0));
    field = new JFormattedTextField(connection.getPort());
    field.setMinimumSize(new java.awt.Dimension(150, 20));
    field.setMaximumSize(new java.awt.Dimension(150, 20));
    field.setEditable(false);
    field.setBorder(null);
    connPanel.add(
        field, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0));

    // Add the connection's User information
    label = new JLabel("User: "******"Creation time: ");
    label.setMinimumSize(new java.awt.Dimension(150, 14));
    label.setMaximumSize(new java.awt.Dimension(150, 14));
    connPanel.add(
        label, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0));
    field = new JFormattedTextField(new SimpleDateFormat("yyyy.MM.dd hh:mm:ss:SS aaa"));
    field.setMinimumSize(new java.awt.Dimension(150, 20));
    field.setMaximumSize(new java.awt.Dimension(150, 20));
    field.setValue(creationTime);
    field.setEditable(false);
    field.setBorder(null);
    connPanel.add(
        field, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0));

    // Add the connection's creationTime information
    label = new JLabel("Status: ");
    label.setMinimumSize(new java.awt.Dimension(150, 14));
    label.setMaximumSize(new java.awt.Dimension(150, 14));
    connPanel.add(
        label, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0));
    statusField = new JFormattedTextField();
    statusField.setMinimumSize(new java.awt.Dimension(150, 20));
    statusField.setMaximumSize(new java.awt.Dimension(150, 20));
    statusField.setValue("Active");
    statusField.setEditable(false);
    statusField.setBorder(null);
    connPanel.add(
        statusField,
        new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0));
    // Add the connection panel to the information panel
    informationPanel.add(connPanel, BorderLayout.NORTH);

    // Add the Number of sent packets information
    JPanel packetsPanel = new JPanel();
    packetsPanel.setLayout(new GridLayout(1, 1));
    packetsPanel.setBorder(BorderFactory.createTitledBorder("Transmitted Packets"));

    statisticsTable =
        new DefaultTableModel(
            new Object[][] {
              {"IQ", 0, 0}, {"Message", 0, 0}, {"Presence", 0, 0}, {"Other", 0, 0}, {"Total", 0, 0}
            },
            new Object[] {"Type", "Received", "Sent"}) {
          private static final long serialVersionUID = -6793886085109589269L;

          public boolean isCellEditable(int rowIndex, int mColIndex) {
            return false;
          }
        };
    JTable table = new JTable(statisticsTable);
    // Allow only single a selection
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    packetsPanel.add(new JScrollPane(table));

    // Add the packets panel to the information panel
    informationPanel.add(packetsPanel, BorderLayout.CENTER);

    tabbedPane.add("Information", new JScrollPane(informationPanel));
    tabbedPane.setToolTipTextAt(4, "Information and statistics about the debugged connection");
  }
예제 #24
0
  public NewTaskFrame() throws SQLException {

    this.setModal(true);
    this.setTitle("Create Task"); // title of frame
    this.setSize(400, 350);
    this.setLayout(new BorderLayout()); // layout of frame

    JLabel task_id = new JLabel("ID:");
    JLabel task_name = new JLabel("Name:");
    JLabel task_desc = new JLabel("Description:");

    JLabel priority = new JLabel("Level of Priority:");
    JLabel duedate = new JLabel("Due Date (yyyy-mm-dd)");
    JLabel numberofdays = new JLabel("Number of days required:");
    JLabel skills_required = new JLabel("Skills Required:");

    Object[] id_possibilities = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    StringBuffer generated_name = new StringBuffer("t");

    for (int i = 0; i < 6; ++i) {
      generated_name.append(
          id_possibilities[new java.util.Random().nextInt(id_possibilities.length)]);
    }

    task_idfield = new JTextField(generated_name.toString());
    taskname_field = new JTextField();
    taskdesc_field = new JTextArea();

    priority_checkbox = new JCheckBox("High", false);
    numberofdays_field = new JTextField();

    format = new SimpleDateFormat("dd-MM-yyyy"); // set format
    duedate_field = new JFormattedTextField(format);

    // set the duedatefield to tomorrow (since minimum task length = 1)
    java.util.Calendar cal = java.util.Calendar.getInstance();
    cal.setTime(new Date()); // get current date
    cal.add(Calendar.DAY_OF_MONTH, 1); // add 1 to current date
    Date date = cal.getTime(); // get this date
    duedate_field.setValue(date); // set this date to the field

    // panel to hold labels and text fields
    JPanel labeltextpanel = new JPanel();
    labeltextpanel.setLayout(new GridLayout(7, 2));
    labeltextpanel.add(task_id);
    labeltextpanel.add(task_idfield);
    labeltextpanel.add(task_name);
    labeltextpanel.add(taskname_field);
    labeltextpanel.add(task_desc);
    labeltextpanel.add(taskdesc_field);
    labeltextpanel.add(priority);
    labeltextpanel.add(priority_checkbox);
    labeltextpanel.add(numberofdays);
    labeltextpanel.add(numberofdays_field);
    labeltextpanel.add(duedate);
    labeltextpanel.add(duedate_field);
    labeltextpanel.add(skills_required);

    this.getSkills();

    // main panel for frame including its layout
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(labeltextpanel, BorderLayout.CENTER);

    // buttons
    clear_button = new JButton("Clear");
    submit_button = new JButton("Submit");

    // add listeners to buttons
    clear_button.addActionListener(this);
    submit_button.addActionListener(this);

    // create panel for buttons and add buttons
    JPanel buttonpanel = new JPanel();
    buttonpanel.setLayout(new FlowLayout());
    buttonpanel.add(clear_button);
    buttonpanel.add(submit_button);

    JPanel checkbox_panel = new JPanel();
    checkbox_panel.setLayout(new FlowLayout());

    for (int i = 0; i < skill_list.size(); i++) {
      checkbox_panel.add(skill_list.get(i)); // make this panel flowlayout
    }

    scrollpane = new JScrollPane(checkbox_panel);
    scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(mainPanel, BorderLayout.CENTER);
    panel.add(scrollpane, BorderLayout.SOUTH);
    // add the main panel to main frame

    add(panel, BorderLayout.CENTER);
    add(buttonpanel, BorderLayout.SOUTH);

    this.setVisible(true);
  }
예제 #25
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
  }
예제 #26
0
  private void initializeComponents() {
    this.setTitle("Configuration");
    this.setResizable(false);

    setLayout(new BorderLayout(20, 20));

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
    mainPanel.setBorder(new LineBorder(mainPanel.getBackground(), 10));
    add(mainPanel, BorderLayout.CENTER);

    GridBagConstraints labelConstraints = new GridBagConstraints();
    labelConstraints.gridx = 0;
    labelConstraints.anchor = GridBagConstraints.WEST;
    labelConstraints.insets = new Insets(5, 5, 5, 5);

    GridBagConstraints inputConstraints = new GridBagConstraints();
    inputConstraints.gridx = 1;
    inputConstraints.anchor = GridBagConstraints.EAST;
    inputConstraints.weightx = 1;
    inputConstraints.insets = new Insets(5, 5, 5, 5);

    JPanel evolutionOptionsPanel = new JPanel();
    evolutionOptionsPanel.setBorder(new TitledBorder("Evolution"));
    evolutionOptionsPanel.setLayout(new BoxLayout(evolutionOptionsPanel, BoxLayout.Y_AXIS));
    mainPanel.add(evolutionOptionsPanel);

    // world size
    JPanel worldSizePanel = new JPanel(new GridBagLayout());
    evolutionOptionsPanel.add(worldSizePanel);
    JLabel worldSizeLabel = new JLabel("World Size");
    worldSizeLabel.setToolTipText("Size of the world in pixels. Width x Height.");
    worldSizePanel.add(worldSizeLabel, labelConstraints);
    JPanel worldSizeInputPanel = new JPanel();
    worldSizeInputPanel.setLayout(new GridBagLayout());
    final AutoSelectOnFocusSpinner worldSizeWidthSpinner =
        new AutoSelectOnFocusSpinner(
            new SpinnerNumberModel(config.getDimension().width, 1, Integer.MAX_VALUE, 1));
    final AutoSelectOnFocusSpinner worldSizeHeightSpinner =
        new AutoSelectOnFocusSpinner(
            new SpinnerNumberModel(config.getDimension().height, 1, Integer.MAX_VALUE, 1));
    worldSizeInputPanel.add(worldSizeWidthSpinner);
    JLabel separatorLabel = new JLabel("x");
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(0, 5, 0, 5);
    worldSizeInputPanel.add(separatorLabel, c);
    worldSizeInputPanel.add(worldSizeHeightSpinner);
    worldSizePanel.add(worldSizeInputPanel, inputConstraints);

    // starting energy
    JPanel startingEnergyPanel = new JPanel(new GridBagLayout());
    evolutionOptionsPanel.add(startingEnergyPanel);
    JLabel startingEnergyLabel = new JLabel("Starting Energy");
    startingEnergyLabel.setToolTipText(
        "<html>The amount of energy all newly painted pixels start out with.<br />Note that changing this will not affect already painted pixels.</html>");
    startingEnergyPanel.add(startingEnergyLabel, labelConstraints);
    final AutoSelectOnFocusSpinner startingEnergySpinner =
        new AutoSelectOnFocusSpinner(
            new SpinnerNumberModel(config.startingEnergy, 1, Integer.MAX_VALUE, 1));
    startingEnergyPanel.add(startingEnergySpinner, inputConstraints);

    // mutation rate
    JPanel mutationRatePanel = new JPanel(new GridBagLayout());
    evolutionOptionsPanel.add(mutationRatePanel);
    JLabel mutationRateLabel = new JLabel("Mutation Rate");
    mutationRateLabel.setToolTipText(
        "<html>Chance for a mutation to occur during copy or mixing operations.<br />A value of 0.01 means a 1% chance, a value of 0 disables mutation.</html>");
    mutationRatePanel.add(mutationRateLabel, labelConstraints);
    final JSpinner mutationRateSpinner =
        new JSpinner(new SpinnerNumberModel(config.mutationRate, 0.0, 1.0, 0.01));
    mutationRateSpinner.setEditor(
        new JSpinner.NumberEditor(mutationRateSpinner, "#.##############"));
    mutationRateSpinner.setPreferredSize(
        new Dimension(180, mutationRateSpinner.getPreferredSize().height));
    final JFormattedTextField mutationRateSpinnerText =
        ((JSpinner.NumberEditor) mutationRateSpinner.getEditor()).getTextField();
    mutationRateSpinnerText.addFocusListener(
        new FocusListener() {
          public void focusGained(FocusEvent e) {
            SwingUtilities.invokeLater(
                new Runnable() {
                  public void run() {
                    mutationRateSpinnerText.selectAll();
                  }
                });
          }

          public void focusLost(FocusEvent e) {}
        });
    mutationRatePanel.add(mutationRateSpinner, inputConstraints);

    JPanel guiOptionsPanel = new JPanel();
    guiOptionsPanel.setBorder(new TitledBorder("GUI"));
    guiOptionsPanel.setLayout(new BoxLayout(guiOptionsPanel, BoxLayout.Y_AXIS));
    mainPanel.add(guiOptionsPanel);

    // background color
    JPanel backgroundColorPanel = new JPanel(new GridBagLayout());
    guiOptionsPanel.add(backgroundColorPanel, labelConstraints);
    JLabel backgroundColorLabel = new JLabel("Background Color");
    backgroundColorLabel.setToolTipText(
        "<html>Pick the background color.<br />If you have a lot of dark pixels, you might want to set this to a light color.</html>");
    backgroundColorPanel.add(backgroundColorLabel, labelConstraints);
    backgroundColor = new PixelColor(config.backgroundColor);
    JPanel backgroundColorAlignmentPanel = new JPanel();
    backgroundColorAlignmentPanel.setLayout(new GridBagLayout());
    backgroundColorAlignmentPanel.setPreferredSize(mutationRateSpinner.getPreferredSize());
    final ColorChooserLabel backgroundColorChooserLabel = new ColorChooserLabel(backgroundColor);
    backgroundColorAlignmentPanel.add(backgroundColorChooserLabel);
    backgroundColorPanel.add(backgroundColorAlignmentPanel, inputConstraints);

    // FPS
    JPanel fpsPanel = new JPanel(new GridBagLayout());
    guiOptionsPanel.add(fpsPanel);
    JLabel fpsLabel = new JLabel("FPS");
    fpsLabel.setToolTipText(
        "<html>The repaint interval in frames per second (FPS).<br />Set this to a lower value to save a few CPU cycles.</html>");
    fpsPanel.add(fpsLabel, labelConstraints);
    final AutoSelectOnFocusSpinner fpsSpinner =
        new AutoSelectOnFocusSpinner(new SpinnerNumberModel(config.fps, 1, Integer.MAX_VALUE, 1));
    fpsPanel.add(fpsSpinner, inputConstraints);

    // paint history size
    JPanel paintHistorySizePanel = new JPanel(new GridBagLayout());
    guiOptionsPanel.add(paintHistorySizePanel);
    JLabel paintHistorySizeLabel = new JLabel("Paint-History Size");
    paintHistorySizeLabel.setToolTipText(
        "<html>Sets the number of entries in the paint history.<br />In case you have not found it yet: the paint history is the little menu that appears when you right-click on the image.</html>");
    paintHistorySizePanel.add(paintHistorySizeLabel, labelConstraints);
    final AutoSelectOnFocusSpinner paintHistorySizeSpinner =
        new AutoSelectOnFocusSpinner(
            new SpinnerNumberModel(config.paintHistorySize, 1, Integer.MAX_VALUE, 1));
    paintHistorySizePanel.add(paintHistorySizeSpinner, inputConstraints);

    JPanel videoOptionsPanel = new JPanel();
    videoOptionsPanel.setBorder(new TitledBorder("Video Recording"));
    videoOptionsPanel.setLayout(new BoxLayout(videoOptionsPanel, BoxLayout.Y_AXIS));
    mainPanel.add(videoOptionsPanel);

    // FPS video
    JPanel fpsVideoPanel = new JPanel(new GridBagLayout());
    videoOptionsPanel.add(fpsVideoPanel);
    JLabel fpsVideoLabel = new JLabel("FPS of videos");
    fpsVideoLabel.setToolTipText("The number of frames per second (FPS) in recorded videos.");
    fpsVideoPanel.add(fpsVideoLabel, labelConstraints);
    final AutoSelectOnFocusSpinner fpsVideoSpinner =
        new AutoSelectOnFocusSpinner(
            new SpinnerNumberModel(config.fpsVideo, 1, Integer.MAX_VALUE, 1));
    fpsVideoPanel.add(fpsVideoSpinner, inputConstraints);

    // video encoder command
    JPanel videoEncoderPanel = new JPanel(new GridBagLayout());
    videoOptionsPanel.add(videoEncoderPanel);
    JLabel videoEncoderLabel = new JLabel("Video Encoder");
    videoEncoderLabel.setToolTipText(
        "<html>The command to invoke your video encoder.<br />Use the tokens INPUT_FILE and OUTPUT_FILE to denote input and output files of your encoder.</html>");
    videoEncoderPanel.add(videoEncoderLabel, labelConstraints);
    final JTextArea videoEncoderTextArea = new JTextArea(Configuration.ENCODER_COMMAND);
    videoEncoderTextArea.setLineWrap(true);
    videoEncoderTextArea.setWrapStyleWord(true);
    JScrollPane videoEncoderScrollPane =
        new JScrollPane(
            videoEncoderTextArea,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    videoEncoderScrollPane.setViewportBorder(null);
    videoEncoderScrollPane.setPreferredSize(
        new Dimension(worldSizeInputPanel.getPreferredSize().width, 100));
    videoEncoderPanel.add(videoEncoderScrollPane, inputConstraints);

    JPanel controlPanel = new JPanel();
    add(controlPanel, BorderLayout.SOUTH);

    JButton okButton = new JButton("OK");
    okButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {

            new Thread() {

              @Override
              public void run() {
                config.world.addChangeListener(
                    new IChangeListener() {

                      public void changed() {
                        int i, j;
                        double d;
                        String s;

                        // evolution

                        i = (Integer) worldSizeWidthSpinner.getValue();
                        j = (Integer) worldSizeHeightSpinner.getValue();
                        if (config.getDimension().width != i || config.getDimension().height != i) {
                          config.setDimension(new Dimension(i, j));
                        }

                        i = (Integer) startingEnergySpinner.getValue();
                        if (config.startingEnergy != i) {
                          config.startingEnergy = i;
                        }

                        d = (Double) mutationRateSpinner.getValue();
                        if (config.mutationRate != d) {
                          config.mutationRate = d;
                        }

                        // gui

                        i = backgroundColor.getInteger();
                        if (config.backgroundColor != i) {
                          config.backgroundColor = i;
                        }

                        i = (Integer) fpsSpinner.getValue();
                        if (config.fps != i) {
                          config.fps = i;
                        }

                        i = (Integer) paintHistorySizeSpinner.getValue();
                        if (config.paintHistorySize != i) {
                          config.paintHistorySize = i;
                        }

                        // video recording

                        i = (Integer) fpsVideoSpinner.getValue();
                        if (config.fpsVideo != i) {
                          config.fpsVideo = i;
                        }

                        s = videoEncoderTextArea.getText();
                        if (false == Configuration.ENCODER_COMMAND.equals(s)) {
                          Configuration.ENCODER_COMMAND = s;
                        }

                        dispose();
                      }
                    });
              }
            }.start();
          }
        });
    controlPanel.add(okButton);
    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        });
    controlPanel.add(cancelButton);

    pack();
  }
예제 #27
0
  public FormatTestFrame() {
    JPanel buttonPanel = new JPanel();
    okButton = new JButton("Ok");
    buttonPanel.add(okButton);
    add(buttonPanel, BorderLayout.SOUTH);

    mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(0, 3));
    add(mainPanel, BorderLayout.CENTER);

    JFormattedTextField intField = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField.setValue(new Integer(100));
    addRow("Number:", intField);

    JFormattedTextField intField2 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField2.setValue(new Integer(100));
    intField2.setFocusLostBehavior(JFormattedTextField.COMMIT);
    addRow("Number (Commit behavior):", intField2);

    JFormattedTextField intField3 =
        new JFormattedTextField(
            new InternationalFormatter(NumberFormat.getIntegerInstance()) {
              protected DocumentFilter getDocumentFilter() {
                return filter;
              }
            });
    intField3.setValue(new Integer(100));
    addRow("Filtered Number", intField3);

    JFormattedTextField intField4 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField4.setValue(new Integer(100));
    intField4.setInputVerifier(
        new InputVerifier() {
          public boolean verify(JComponent component) {
            JFormattedTextField field = (JFormattedTextField) component;
            return field.isEditValid();
          }
        });
    addRow("Verified Number:", intField4);

    JFormattedTextField currencyField = new JFormattedTextField(NumberFormat.getCurrencyInstance());
    currencyField.setValue(new Double(10));
    addRow("Currency:", currencyField);

    JFormattedTextField dateField = new JFormattedTextField(DateFormat.getDateInstance());
    dateField.setValue(new Date());
    addRow("Date (default):", dateField);

    DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);
    format.setLenient(false);
    JFormattedTextField dateField2 = new JFormattedTextField(format);
    dateField2.setValue(new Date());
    addRow("Date (short, not lenient):", dateField2);

    try {
      DefaultFormatter formatter = new DefaultFormatter();
      formatter.setOverwriteMode(false);
      JFormattedTextField urlField = new JFormattedTextField(formatter);
      urlField.setValue(new URL("http://java.sun.com"));
      addRow("URL:", urlField);
    } catch (MalformedURLException ex) {
      ex.printStackTrace();
    }

    try {
      MaskFormatter formatter = new MaskFormatter("###-##-####");
      formatter.setPlaceholderCharacter('0');
      JFormattedTextField ssnField = new JFormattedTextField(formatter);
      ssnField.setValue("078-05-1120");
      addRow("SSN Mask:", ssnField);
    } catch (ParseException ex) {
      ex.printStackTrace();
    }

    JFormattedTextField ipField = new JFormattedTextField(new IPAddressFormatter());
    ipField.setValue(new byte[] {(byte) 130, 65, 86, 66});
    addRow("IP Address:", ipField);
    pack();
  }
예제 #28
0
  public GUI() {

    // Frame
    frame = new JFrame("HardwareSwap Notifier");

    // Panels
    panel = new JPanel();
    group1 = new JPanel();
    group2 = new JPanel();
    group3 = new JPanel();
    group4 = new JPanel();
    group5 = new JPanel();
    group6 = new JPanel();
    group7 = new JPanel();
    group8 = new JPanel();

    // Menu Bar
    menus = new JMenuBar();
    fileMenu = new JMenu("File");
    clearCurrent = new JMenuItem("Clear");
    quitItem = new JMenuItem("Quit");
    load = new JMenuItem("Load");
    saveCurrent = new JMenuItem("Save All");
    clearSaved = new JMenuItem("Clear Saved");
    removeItem = new JMenuItem("Remove Item");
    removePhone = new JMenuItem("Remove Phone");
    saveCurrent = new JMenuItem("Save Current");
    helpMenu = new JMenu("Help");
    help = new JMenuItem("How To Use");
    about = new JMenuItem("About");

    // Buttons
    add1 = new JButton("Add");
    add2 = new JButton("Add");
    start = new JButton("Start");
    stop = new JButton("Stop");
    save1 = new JButton("Add/Save");
    save2 = new JButton("Add/Save");
    show = new JButton("Display Data");

    add1.setFocusPainted(false);
    add2.setFocusPainted(false);
    start.setFocusPainted(false);
    stop.setFocusPainted(false);
    save1.setFocusPainted(false);
    save2.setFocusPainted(false);
    show.setFocusPainted(false);

    stop.setEnabled(false);

    // CheckBox
    remove = new JCheckBox("Remove items when found");
    remove.setFocusable(false);

    // Listener
    ButtonListener listener = new ButtonListener();

    add1.addActionListener(listener);
    add2.addActionListener(listener);
    start.addActionListener(listener);
    stop.addActionListener(listener);
    load.addActionListener(listener);
    save1.addActionListener(listener);
    save2.addActionListener(listener);
    saveCurrent.addActionListener(listener);
    show.addActionListener(listener);
    quitItem.addActionListener(listener);
    clearCurrent.addActionListener(listener);
    clearSaved.addActionListener(listener);
    saveCurrent.addActionListener(listener);
    help.addActionListener(listener);
    about.addActionListener(listener);
    removePhone.addActionListener(listener);
    removeItem.addActionListener(listener);
    remove.addActionListener(listener);

    // Carrier Selection
    options = new String[10];
    options[0] = "AT&T";
    options[1] = "Boost Mobile";
    options[2] = "Cellular One";
    options[3] = "Nextel";
    options[4] = "T-Mobile";
    options[5] = "Tracfone";
    options[6] = "US Cellular";
    options[7] = "Sprint";
    options[8] = "Verizon";
    options[9] = "Virgin Mobile";

    carriers = new JComboBox<String>(options);

    // Text Fields
    searchName = new JTextField(15);
    item = new JTextField(15);
    phone = new JTextField(15);
    interval2 = new JTextField(15);
    results = new JTextArea(10, 20);

    JScrollPane scrollPane = new JScrollPane(results);

    results.setEditable(false);

    // Interval
    intOptions = new SpinnerNumberModel(5, 1, 60, 1);
    interval = new JSpinner(intOptions);
    JFormattedTextField tf = ((JSpinner.DefaultEditor) interval.getEditor()).getTextField();
    tf.setHorizontalAlignment(JFormattedTextField.LEFT);

    // Background
    panelBackground = new Color(237, 237, 237);

    panel.setBackground(panelBackground);
    searchName.setBackground(panelBackground);
    item.setBackground(panelBackground);
    phone.setBackground(panelBackground);
    interval.setBackground(panelBackground);

    // Panel Layouts
    panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
    group1.setLayout(new BoxLayout(group1, BoxLayout.PAGE_AXIS));
    group2.setLayout(new BoxLayout(group2, BoxLayout.X_AXIS));
    group3.setLayout(new BoxLayout(group3, BoxLayout.PAGE_AXIS));
    group4.setLayout(new BoxLayout(group4, BoxLayout.X_AXIS));
    group5.setLayout(new BoxLayout(group5, BoxLayout.X_AXIS));
    group6.setLayout(new BoxLayout(group6, BoxLayout.X_AXIS));
    group7.setLayout(new BoxLayout(group7, BoxLayout.X_AXIS));
    group8.setLayout(new BoxLayout(group8, BoxLayout.X_AXIS));

    // Borders
    searchName.setBorder(
        BorderFactory.createTitledBorder(
            null,
            "Search Name",
            TitledBorder.DEFAULT_JUSTIFICATION,
            TitledBorder.DEFAULT_JUSTIFICATION,
            null,
            Color.DARK_GRAY));
    item.setBorder(
        BorderFactory.createTitledBorder(
            null,
            "Item",
            TitledBorder.DEFAULT_JUSTIFICATION,
            TitledBorder.DEFAULT_JUSTIFICATION,
            null,
            Color.DARK_GRAY));
    phone.setBorder(
        BorderFactory.createTitledBorder(
            null,
            "Cell Phone",
            TitledBorder.DEFAULT_JUSTIFICATION,
            TitledBorder.DEFAULT_JUSTIFICATION,
            null,
            Color.DARK_GRAY));
    group5.setBorder(
        BorderFactory.createTitledBorder(
            null,
            "Check Interval (mins)",
            TitledBorder.DEFAULT_JUSTIFICATION,
            TitledBorder.DEFAULT_JUSTIFICATION,
            null,
            Color.DARK_GRAY));

    // Sizes
    panel.setPreferredSize(new Dimension(200, 0));
    searchName.setMaximumSize(new Dimension(190, 50));
    item.setMaximumSize(new Dimension(190, 50));
    phone.setMaximumSize(new Dimension(185, 50));
    carriers.setMaximumSize(new Dimension(175, 20));
    group5.setPreferredSize(new Dimension(190, 47));
    group5.setMaximumSize(new Dimension(190, 47));

    add1.setMaximumSize(new Dimension(90, 20));
    save1.setMaximumSize(new Dimension(90, 20));
    add2.setMaximumSize(new Dimension(90, 20));
    save2.setMaximumSize(new Dimension(90, 20));
    start.setMaximumSize(new Dimension(90, 20));
    stop.setMaximumSize(new Dimension(90, 20));
    show.setMaximumSize(new Dimension(120, 20));

    // Add file menu items
    fileMenu.add(clearCurrent);
    fileMenu.add(clearSaved);
    fileMenu.add(load);
    fileMenu.add(removeItem);
    fileMenu.add(removePhone);
    fileMenu.add(saveCurrent);
    fileMenu.add(quitItem);

    // Add help menu items
    helpMenu.add(help);
    helpMenu.add(about);

    // Add to menu bar
    menus.add(fileMenu);
    menus.add(helpMenu);

    // Add items to panel
    group1.add(searchName);
    group1.add(item);

    group2.add(add1);
    group2.add(Box.createHorizontalStrut(10));
    group2.add(save1);

    group6.add(remove);

    group3.add(phone);
    group3.add(Box.createVerticalStrut(10));
    group3.add(carriers);

    group4.add(add2);
    group4.add(Box.createHorizontalStrut(10));
    group4.add(save2);

    group5.add(interval);

    group7.add(show);

    group8.add(start);
    group8.add(Box.createHorizontalStrut(10));
    group8.add(stop);

    panel.add(Box.createVerticalStrut(10));
    panel.add(group1);
    panel.add(Box.createVerticalStrut(10));
    panel.add(group2);
    panel.add(Box.createVerticalStrut(40));
    panel.add(group3);
    panel.add(Box.createVerticalStrut(10));
    panel.add(group4);
    panel.add(Box.createVerticalStrut(40));
    panel.add(group5);
    panel.add(Box.createVerticalStrut(30));
    panel.add(group6);
    panel.add(Box.createVerticalStrut(40));
    panel.add(group7);
    panel.add(Box.createVerticalStrut(10));
    panel.add(group8);
    panel.add(Box.createVerticalStrut(10));

    // Setup frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(menus);
    frame.add(scrollPane);
    frame.add(BorderLayout.EAST, panel);
    frame.pack();
    frame.setSize(new Dimension(670, 620));
    frame.setVisible(true);
  }
예제 #29
0
  public MakeReservation() {
    new BorderLayout();

    standardRoom.setMnemonic(KeyEvent.VK_K);
    standardRoom.setActionCommand("Standard Room");
    standardRoom.setSelected(true);

    familyRoom.setMnemonic(KeyEvent.VK_F);
    familyRoom.setActionCommand("Family Room");

    suiteRoom.setMnemonic(KeyEvent.VK_S);
    suiteRoom.setActionCommand("Suite");

    // Add Booking Button
    ImageIcon bookRoomIcon = createImageIcon("images/book.png");
    bookRoom = new JButton("Book Room", bookRoomIcon);
    bookRoom.setVerticalTextPosition(AbstractButton.BOTTOM);
    bookRoom.setHorizontalTextPosition(AbstractButton.CENTER);
    bookRoom.setMnemonic(KeyEvent.VK_M);
    bookRoom.addActionListener(this);
    bookRoom.setActionCommand("book");

    // Group the radio buttons.
    group.add(standardRoom);
    group.add(familyRoom);
    group.add(suiteRoom);

    // Create the labels.
    nameLabel = new JLabel("Name: ");
    amountroomsLabel = new JLabel("How many rooms? ");
    checkoutdateLabel = new JLabel("Check-Out Date: ");
    checkindateLabel = new JLabel("Check-In Date: ");

    // Create the text fields and set them up.
    nameField = new JFormattedTextField();
    nameField.setColumns(10);

    amountroomsField = new JFormattedTextField(new Integer(1));
    amountroomsField.setValue(new Integer(1));
    amountroomsField.setColumns(10);

    // java.util.Date dt_checkin = new java.util.Date();
    LocalDate today = LocalDate.now();
    // java.text.SimpleDateFormat sdf_checkin = new java.text.SimpleDateFormat("MM/dd/yyyy");
    currentDate_checkin = today.toString();
    checkindateField = new JFormattedTextField(currentDate_checkin);
    checkindateField.setColumns(10);

    // java.util.Date dt_checkout = new java.util.Date();
    LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
    // java.text.SimpleDateFormat sdf_checkout = new java.text.SimpleDateFormat("MM/dd/yyyy");
    currentDate_checkout = tomorrow.toString();
    checkoutdateField = new JFormattedTextField(currentDate_checkout);
    checkoutdateField.setColumns(10);

    // Tell accessibility tools about label/textfield pairs.
    nameLabel.setLabelFor(nameField);
    amountroomsLabel.setLabelFor(amountroomsField);
    checkoutdateLabel.setLabelFor(checkoutdateField);
    checkindateLabel.setLabelFor(checkindateField);

    // Lay out the labels in a panel.
    JPanel labelPane1 = new JPanel(new GridLayout(0, 1));

    labelPane1.add(amountroomsLabel);

    JPanel labelPane3 = new JPanel(new GridLayout(0, 1));
    labelPane3.add(checkindateLabel);

    JPanel labelPane2 = new JPanel(new GridLayout(0, 1));
    labelPane2.add(checkoutdateLabel);

    JPanel labelPane4 = new JPanel(new GridLayout(0, 1));
    labelPane4.add(nameLabel);

    // Layout the text fields in a panel.
    JPanel fieldPane1 = new JPanel(new GridLayout(0, 1));
    fieldPane1.add(amountroomsField);

    JPanel fieldPane3 = new JPanel(new GridLayout(0, 1));
    fieldPane3.add(checkindateField);

    JPanel fieldPane2 = new JPanel(new GridLayout(0, 1));
    fieldPane2.add(checkoutdateField);

    JPanel fieldPane4 = new JPanel(new GridLayout(0, 1));
    fieldPane4.add(nameField);

    // Put the radio buttons in a column in a panel.
    JPanel radioPanel = new JPanel(new GridLayout(0, 1));
    radioPanel.add(standardRoom);
    radioPanel.add(familyRoom);
    radioPanel.add(suiteRoom);

    // Put the panels in this panel, labels on left,
    // text fields on right.
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    add(labelPane1, BorderLayout.LINE_START);
    add(fieldPane1, BorderLayout.LINE_END);
    add(labelPane3, BorderLayout.LINE_START);
    add(fieldPane3, BorderLayout.LINE_END);
    add(labelPane2, BorderLayout.LINE_START);
    add(fieldPane2, BorderLayout.LINE_END);
    add(labelPane4, BorderLayout.LINE_START);
    add(fieldPane4, BorderLayout.LINE_END);

    add(radioPanel, BorderLayout.LINE_END);
    add(bookRoom);
  }
예제 #30
0
  public void bookRoom() {
    try {
      int code = 0;
      Connection con =
          DriverManager.getConnection(
              "jdbc:mysql://67.20.111.85:3306/jeehtove_caliking?relaxAutoCommit=false",
              "jeehtove_ck",
              "Z_^PBBZT+kcy");
      Statement stmt_insert = con.createStatement();
      Statement stmt_tableRange = con.createStatement();
      Statement stmt_checkrooms = con.createStatement();
      Statement stmt_checkrooms_2 = con.createStatement();

      String insert = null;
      int flag = 0;

      String room_type;
      if (standardRoom.isSelected()) {
        room_type = "Standard";
        code = 1;
      } else if (familyRoom.isSelected()) {
        room_type = "Family";
        code = 2;
      } else {
        room_type = "Suite";
        code = 3;
      }

      // Converting string from checkin and checkout dates so that they can access the correct table
      String currentDate_checkin_getText = checkindateField.getText();
      String currentDate_checkin_rest = currentDate_checkin_getText.substring(5);
      String currentDate_checkin_replace = currentDate_checkin_rest.replace("-", "_");
      String currentDate_checkin_year = currentDate_checkin.substring(0, 4);
      String currentDate_checkin_final =
          currentDate_checkin_year + "_" + currentDate_checkin_replace;

      String currentDate_checkout_getText = checkoutdateField.getText();
      String currentDate_checkout_rest = currentDate_checkout_getText.substring(5);
      String currentDate_checkout_replace = currentDate_checkout_rest.replace("-", "_");
      String currentDate_checkout_year = currentDate_checkout.substring(0, 4);
      String currentDate_checkout_final =
          currentDate_checkout_year + "_" + currentDate_checkout_replace;

      // MySQL Statement to select tables from schema that are in between checkin and checkout range
      String tableRange =
          "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='jeehtove_caliking' AND TABLE_NAME BETWEEN 'rooms_"
              + currentDate_checkin_final
              + "' AND 'rooms_"
              + currentDate_checkout_final
              + "';";
      ResultSet tb_Range = stmt_tableRange.executeQuery(tableRange);

      System.out.println(tableRange);
      List tb_range_list = new ArrayList();

      while (tb_Range.next()) {
        String tb_range_date = tb_Range.getString("table_name");
        tb_range_list.add(tb_range_date);
        // String current_table = tb_Range.getString("table_name");
        // System.out.println(tb_range_list.add(tb_Range.getString("table_name")));
      }

      stmt_tableRange.close();

      for (int x = 0; x < tb_range_list.size(); x++) {
        String query_checkrooms =
            "SELECT * FROM "
                + tb_range_list.get(x)
                + " WHERE type = '"
                + code
                + "' AND booked = '0' LIMIT 1;";
        // System.out.println(query_checkrooms);
        ResultSet checkrooms = stmt_checkrooms.executeQuery(query_checkrooms);
        while (checkrooms.next()) {
          String getroomnumber = checkrooms.getString("room");
          insert =
              "INSERT INTO `reservations` VALUES ('"
                  + getroomnumber
                  + "', '"
                  + checkindateField.getText()
                  + "', '"
                  + checkoutdateField.getText()
                  + "',  '"
                  + room_type
                  + "',  '"
                  + nameField.getText()
                  + "');";
          String bookroom =
              "UPDATE `"
                  + tb_range_list.get(x)
                  + "` SET booked = '1' WHERE room = '"
                  + getroomnumber
                  + "';";
          // System.out.println(insert);
          int cr = stmt_checkrooms_2.executeUpdate(bookroom);
          flag = 1;
          System.out.println("Room Booked!");
        }
      }

      if (flag == 1) {
        int rs = stmt_insert.executeUpdate(insert);
      } else {
        System.out.println("All " + room_type + " rooms are booked for the time requested.");
      }

      /*String query_checkrooms = "SELECT * FROM rooms_" + currentDate_checkin_final + " WHERE type = '" + code + "' AND booked = '0';";
      System.out.println(query_checkrooms);
      Statement stmt_checkrooms = con.createStatement();
      ResultSet checkrooms = stmt_checkrooms.executeQuery(query_checkrooms);*/

      /*if (checkrooms.next()){
      		String getroomnumber = checkrooms.getString("room");
      		String insert = "INSERT INTO `reservations` VALUES ('" + getroomnumber + "', '" +  checkindateField.getText() + "', '" +  checkoutdateField.getText() + "',  '" + room_type + "',  '" + nameField.getText() + "');";
      		String bookroom = "UPDATE `rooms_" + currentDate_checkin_final + "` SET booked = '1' WHERE room = '" + getroomnumber + "';";
      //System.out.println(insert);
      	int rs=stmt_insert.executeUpdate(insert);
      	int cr=stmt_checkrooms.executeUpdate(bookroom);
      	con.commit();
      	System.out.println("Room Booked!");
      	}*/

      // else System.out.println("All " + room_type + " rooms are booked for the time requested.");
      System.out.println("Complete.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }