Example #1
0
 public void Window() {
   JFrame f = new JFrame("test");
   f.setSize(570, 383);
   f.add(new test());
   f.setLocationRelativeTo(null);
   f.setResizable(false);
   f.setVisible(true);
 }
  public void init() {
    frame = new JFrame();
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("PersistentFrameTest");
    frame.setSize(400, 200);

    JButton loadButton = new JButton("Load");
    frame.add(loadButton);
    loadButton.addActionListener(EventHandler.create(ActionListener.class, this, "load"));

    JButton saveButton = new JButton("Save");
    frame.add(saveButton);
    saveButton.addActionListener(EventHandler.create(ActionListener.class, this, "save"));

    frame.setVisible(true);
  }
Example #3
0
  public ArcViewer() {

    JFrame frame = new JFrame("ArcViewer v.0.9");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    frame.add("Center", this);
    frame.setSize(900, 600);
    frame.setVisible(true);

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

    // Add content to the window.
    frame.add(new FileChooserDemo());

    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be invoked from the event
   * dispatch thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("Viettel Enterprise Platform - Module Friendlizer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Add content to the window.
    frame.add(new GuiFriendlizerApp());

    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
 // --------初始化界面的方法---------
 public void init() {
   JPanel top = new JPanel();
   top.add(new JLabel("输入查询语句:"));
   top.add(sqlField);
   top.add(execBn);
   // 为执行按钮、单行文本框添加事件监听器
   execBn.addActionListener(new ExceListener());
   sqlField.addActionListener(new ExceListener());
   jf.add(top, BorderLayout.NORTH);
   jf.setSize(680, 480);
   jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   jf.setVisible(true);
 }
Example #7
0
  public static void main(String[] args) throws IOException {

    JFrame f = new JFrame("Packet Sender");
    f.add(new Sender(), BorderLayout.CENTER);

    f.setBounds(
        (d.width - (((rez == 1) ? 550 : 450))) / 2,
        (d.height - (((rez == 1) ? 400 : 300))) / 2,
        (((rez == 1) ? 550 : 450)),
        (((rez == 1) ? 400 : 300)));
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(false);
    f.setVisible(true);
  }
Example #8
0
  public void hacerInterfaz() {
    ventana_chat = new JFrame("Cliente");
    btn_enviar = new JButton("Enviar");
    txt_mensaje = new JTextField(4);
    area_chat = new JTextArea(10, 17);
    scroll = new JScrollPane(area_chat);
    contenedor_areachat = new JPanel();
    contenedor_areachat.setLayout(new GridLayout(1, 1));
    contenedor_areachat.add(scroll);
    contenedor_btntxt = new JPanel();
    contenedor_btntxt.setLayout(new GridLayout(1, 2));
    contenedor_btntxt.add(txt_mensaje);
    contenedor_btntxt.add(btn_enviar);
    ventana_chat.setLayout(new BorderLayout());
    ventana_chat.add(contenedor_areachat, BorderLayout.NORTH);
    ventana_chat.add(contenedor_btntxt, BorderLayout.SOUTH);
    ventana_chat.setSize(300, 220);
    ventana_chat.setVisible(true);
    ventana_chat.setResizable(false);
    ventana_chat.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Thread principal =
        new Thread(
            new Runnable() {
              public void run() {
                try {
                  socket = new Socket("localhost", 8000);
                  leer();
                  escribir();
                } catch (Exception ex) {
                  ex.printStackTrace();
                }
              }
            });
    principal.start();
  }
Example #9
0
 public void init() throws Exception {
   table = ImageIO.read(new File("image/board.jpg"));
   black = ImageIO.read(new File("image/black.gif"));
   white = ImageIO.read(new File("image/white.gif"));
   selected = ImageIO.read(new File("image/selected.gif"));
   // 把每个元素赋为"╋",用于在控制台画出棋盘
   for (int i = 0; i < BOARD_SIZE; i++) {
     for (int j = 0; j < BOARD_SIZE; j++) {
       board[i][j] = "╋";
     }
   }
   chessBoard.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HETGHT));
   chessBoard.addMouseListener(
       new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
           // 将用户鼠标事件的座标转换成棋子数组的座标。
           int xPos = (int) ((e.getX() - X_OFFSET) / RATE);
           int yPos = (int) ((e.getY() - Y_OFFSET) / RATE);
           board[xPos][yPos] = "●";
           /*
           电脑随机生成2个整数,作为电脑下棋的座标,赋给board数组。
           还涉及:
           1.如果下棋的点已经棋子,不能重复下棋。
           2.每次下棋后,需要扫描谁赢了
           */
           chessBoard.repaint();
         }
         // 当鼠标退出棋盘区后,复位选中点座标
         public void mouseExited(MouseEvent e) {
           selectedX = -1;
           selectedY = -1;
           chessBoard.repaint();
         }
       });
   chessBoard.addMouseMotionListener(
       new MouseMotionAdapter() {
         // 当鼠标移动时,改变选中点的座标
         public void mouseMoved(MouseEvent e) {
           selectedX = (e.getX() - X_OFFSET) / RATE;
           selectedY = (e.getY() - Y_OFFSET) / RATE;
           chessBoard.repaint();
         }
       });
   f.add(chessBoard);
   f.pack();
   f.setVisible(true);
 }
Example #10
0
  public static void main(String[] args) {

    Global.debugging = true;

    // make frame

    final JFrame frame = new JFrame("Test Client Game");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // make game
    ClientGame game = null;
    String[] names = {
      "Alpha", "Beta", "Charlie", "Delta", "Epsilon", "Foxtrot", "Gamma", "Hurricane"
    };
    int ptr = 0;

    while (true) {
      try {
        game = new ClientGame(names[ptr++], (args.length > 1 ? args[1] : "localhost"));
        break;
      } catch (ClientNameException ex) {
        System.err.println(ex);
      } catch (IOException ex) {
        System.err.println("Could not connect to server");
      }
    }

    // add controls to frame

    game.getPlayerShip().getControls().setContainer(frame);

    // add full screen toggle

    FullScreenToggle.addToggleToGame(frame, game, KeyEvent.VK_F11);

    // add game to frame

    frame.add(game);

    // show frame

    frame.pack();
    frame.setVisible(true);

    game.startTheGame();
  }
Example #11
0
  static void GoEnd(JFrame frame, int i) {
    Image background = new ImageIcon("image/final_" + i + ".png").getImage();
    background =
        background.getScaledInstance(frame.getWidth(), frame.getHeight(), Image.SCALE_DEFAULT);
    JLabel back = new JLabel();
    back.setBounds(0, 0, frame.getWidth(), frame.getHeight());
    back.setIcon(new ImageIcon(background));
    frame.add(back, 1);
    frame.validate();
    frame.repaint();
    if (i == 1) { // 烤好
      Talk.say("你成功的通過了這學期", 1);
      Talk.say("這次經驗也讓你對學習產生濃烈的興趣", 1);
      Talk.say("讓你大四成為了神,進而順利畢業", 1);

    } else if (i == 2) { // 系館
      Talk.say("經由你的捐贈", 1);
      Talk.say("資訊系逐漸自成一個校區", 1);
      Talk.say("而在原系館中庭擺放了一個十倍放大的銅像", 1);
      Talk.say("用來紀念資訊系傑出校友─大恩碩像", 1);

    } else if (i == 3) { // 出國
      Talk.say("你放棄了學業,踏上了桌球國手之路", 1);
      Talk.say("過五關斬六將", 1);
      Talk.say("終於成為了世界桌球王", 1);

    } else if (i == 4) { // 0分 game over
      Talk.say("輕輕的我走了", 1);
      Talk.say("正如我輕輕地來", 1);
      Talk.say("我揮一揮衣袖", 1);
      Talk.say("不帶走任何學分", 1);
    } else if (i == 5) { // final
      Talk.say("你完成了final project", 1);
      Talk.say("跟其他同學一起過了OOP", 1);
      Talk.say("不過大四還有更嚴苛的挑戰在等著你", 1);
      Talk.say("同學!加油吧!", 1);
    }
  }
Example #12
0
    public helpMenu() {
      helpMenuPanel = new JPanel();
      back = new JButton();
      back = new JButton("back");
      // ----------------------------------------- The instructions that will be displayed
      String str =
          new String(
              "MOVIE DATABASE\n"
                  + "This program is to allow you to personally keep track of movies \n"
                  + "This functionalities of this database are\n"
                  + "- Adding a new record\n"
                  + "- Editing a record\n"
                  + "- Deleting a record\n"
                  + "- Sorting records\n"
                  + "- Searching records\n"
                  + "- Saving and Loading the data of the database\n"
                  + "\n"
                  + "To make a NEW RECORD\n"
                  + "Click ‘new record’ on the top left of the screen\n"
                  + "a new window will pop up where you can fill in information about the movie.\n"
                  + "Make sure to fill in the name of the movie, this is the piece of information that MUST be filled in\n"
                  + "\n"
                  + "To EDIT A RECORD\n"
                  + "\n"
                  + "Click ‘edit record’ on the top left of the screen\n"
                  + "A window will appear where you can enter the ID Number of the record you want to edit.\n"
                  + "Another window will appear with the information of that record. At this point, you can begin editing\n"
                  + "the information of that record\n"
                  + "\n"
                  + "To DELETE RECORD\n"
                  + "\n"
                  + "Click 'delete record’ on the top left of the screen\n"
                  + "A Window will appear where you can enter the ID Number of the record you want to delete\n"
                  + "After entering the ID Number of the record you want to delete, you can press okay and that record will\n"
                  + "be deleted\n"
                  + "\n"
                  + "To SORT RECORDS\n"
                  + "\n"
                  + "The column name of each field is also a Button.\n"
                  + "By pressing any of the column labels, you sort the records by the label you clicked\n"
                  + "e.g. if you want to sort the records by release year, you would click the release year header\n"
                  + "\n"
                  + "NOTE: If you have searched through records and want to sort the records again, you have to click the\n"
                  + "“Clear Parameters button”. This will allow you to see all the records again and allow the sort\n"
                  + "functions to work again.\n"
                  + "\n"
                  + "To SEARCH RECORDS\n"
                  + "\n"
                  + "There is a text field above each field name. Over the field you can type in what you want to search\n"
                  + "for in that field. e.g. if you wanted to search for movies that were made in 1999, you would type 1999\n"
                  + "in the textfield above release year\n"
                  + "Afterwards, click the Search Button and the program will return all of the records\n"
                  + "that match your search.\n"
                  + "\n"
                  + "This search is also capable of searching with multiple parameters,e.g. if you wanted to search for movies \n"
                  + "with the word 'the' in it, that also have a movie rating of R, you would type in 'the' in the textfield \n"
                  + "above the moviename header and a 'R' in the textfield above movie rating. After clicking search This will \n"
                  + "return all movies rated R with a 'the' in the name of its movie");
      TextArea = new JTextArea(str, 35, 55); // sets up the text area where the intructions will be
      TextArea.setEditable(false);
      Scroll =
          new JScrollPane(TextArea); // set up the text area so that you can scroll up and down it
      Scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      // ----------------------------------------- adds the components to the Panel
      helpMenuPanel.add(Scroll);
      helpMenuPanel.add(back);
      helpFrame = new JFrame("HELP");

      back.addActionListener(
          new ActionListener() {
            /* back
             * the method will make the instructions window invisible as if the user exit out of it
             * Pre: the user clicks back in the instructions window
             * Post: the instructions window will become invisible
             */
            public void actionPerformed(ActionEvent e) {
              // this is executed when the button is pressed
              helpFrame.setVisible(false);
            }
          });
      helpFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      // frame.setResizable(false);
      helpFrame.add(helpMenuPanel);
      // frame.setSize(200, 300);
      helpFrame.setVisible(true);
      helpFrame.pack();
    }
Example #13
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);
  }
  public ODEWizardScalaSci() {
    editingClassName = "Lorenz";
    systemOrder = 3; // the order of ODE system

    copyTemplateButton =
        new JButton("1. Copy and Edit Template", new ImageIcon("/scalaLab.jar/yellow-ball.gif"));
    generateEditingButton = new JButton("2. Generate Java Class", new ImageIcon("./blue-ball.gif"));
    saveJavaClassButton =
        new JButton("3. Save Java Class", new ImageIcon("scalaLab.jar/red-ball.gif"));
    compileJavaClassButton =
        new JButton("4.a. Java Compile - External Compiler", new ImageIcon("blue-ball.gif"));
    compileJavaInternalCompilerButton =
        new JButton("4.b. Java Compile - Internal Compiler", new ImageIcon("blue-ball.gif"));
    generateScriptCodeButton =
        new JButton("Generate scalaSci Script", new ImageIcon("red-ball.gif"));

    ODEWizardFrame = new JFrame("ODE Wizard for scalaSci with Java implementation of. ODEs");

    editPanel = new JPanel();
    editPanel.setLayout(new GridLayout(1, 2));

    paramPanel = new JPanel(new GridLayout(1, 4));
    availODEMethods.add("ODErke");
    availODEMethods.add("ODEmultistep");
    availODEMethods.add("ODEdiffsys");
    ODEselectMethodLabel = new JLabel("ODE method: ");
    ODEselectMethodComboBox = new JComboBox(availODEMethods);
    ODEselectMethodComboBox.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            ODESolveMethod = ODEselectMethodComboBox.getSelectedIndex();
            updateTemplateText();
            templateTextArea.setText(templateText);
            currentlySelectedLabel.setText(
                "Selected Method: " + (String) availODEMethods.get(ODESolveMethod));
          }
        });

    JLabel javaFileTextLabel = new JLabel("Java File Name: ");
    javaFileTextBox = new JTextField(editingClassName);
    javaFileTextBox.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            editingClassName = javaFileTextBox.getText();
            String updatedStatusText = prepareStatusText();
            statusAreaTop.setText(updatedStatusText);
          }
        });

    JLabel systemOrderLabel = new JLabel("System order: ");
    systemOrderText = new JTextField(String.valueOf(systemOrder));
    systemOrderText.addActionListener(new editSystemOrder());
    JPanel javaFilePanel = new JPanel();
    javaFilePanel.add(javaFileTextLabel);
    javaFilePanel.add(javaFileTextBox);
    JPanel systemOrderPanel = new JPanel();
    systemOrderPanel.add(systemOrderLabel);
    systemOrderPanel.add(systemOrderText);

    paramMethodPanel = new JPanel();
    paramMethodPanel.add(ODEselectMethodLabel);
    paramMethodPanel.add(ODEselectMethodComboBox);
    paramPanel.add(paramMethodPanel);
    paramPanel.add(javaFilePanel);
    paramPanel.add(systemOrderPanel);
    currentlySelectedLabel =
        new JLabel("Selected Method: " + (String) availODEMethods.get(ODESolveMethod));
    paramPanel.add(currentlySelectedLabel);

    statusPanel = new JPanel(new GridLayout(2, 1));
    statusAreaTop = new JTextArea();
    statusAreaTop.setFont(new Font("Arial", Font.BOLD, 16));
    String statusText = prepareStatusText();

    statusAreaTop.setText(statusText);
    statusAreaBottom = new JTextArea();
    statusAreaBottom.setText(
        "Step1:  Copy and edit the template ODE  (implements the famous Lorenz chaotic system),\n"
            + "Then set the name of your Java Class (instead of \"Lorenz\"),  without the extension .java\n"
            + "Also set the proper order (i.e. number of equations and variables) of your system. ");
    statusPanel.add(statusAreaTop);
    statusPanel.add(statusAreaBottom);

    templateTextArea = new JTextArea();
    updateTemplateText();

    templateTextArea.setFont(new Font("Arial", Font.ITALIC, 12));
    templateTextArea.setText(templateText);
    templateScrollPane = new JScrollPane();
    templateViewPort = templateScrollPane.getViewport();
    templateViewPort.add(templateTextArea);

    ODEWizardTextArea = new JTextArea();
    ODEWizardText = "";
    ODEWizardTextArea.setText(ODEWizardText);
    ODEWizardTextArea.setFont(new Font("Arial", Font.BOLD, 12));

    ODEWizardScrollPane = new JScrollPane();
    wizardViewPort = ODEWizardScrollPane.getViewport();
    wizardViewPort.add(ODEWizardTextArea);

    editPanel.add(ODEWizardScrollPane);
    editPanel.add(templateScrollPane);

    // Step 1: copy template of ODE implementation from the
    // templateTextArea to ODEWizardTextArea
    copyTemplateButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            ODEWizardTextArea.setText(templateTextArea.getText());
            generateEditingButton.setEnabled(true);
            statusAreaBottom.setText(
                "Step2:  If you have implemented correctly your ODE, the wizard completes the ready to compile Java class");
          }
        });

    // Step 2: generate Java Class from template
    JPanel buttonPanel = new JPanel();
    generateEditingButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String editingODE = ODEWizardTextArea.getText();
            String classImplementationString = // "package javaPluggins; \n"+
                "import  numal.*; \n\n"
                    + "public class "
                    + editingClassName
                    + " extends Object \n             implements "
                    + implementingInterfaces[ODESolveMethod]
                    + " \n \n "
                    + "{ \n";

            classImplementationString += (editingODE + "}\n");

            ODEWizardTextArea.setText(classImplementationString);
            saveJavaClassButton.setEnabled(true);
            statusAreaBottom.setText(
                "Step3:  The generated Java source is ready, you can check it, and then proceed to save.");
          }
        });

    // Step 3: save generated Java Class on disk
    saveJavaClassButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String currentWorkingDirectory = Directory.Current().get().path();
            JFileChooser chooser = new JFileChooser(currentWorkingDirectory);
            chooser.setSelectedFile(new File(editingClassName + ".java"));
            int ret = chooser.showSaveDialog(ODEWizardFrame);

            if (ret != JFileChooser.APPROVE_OPTION) {
              return;
            }
            File f = chooser.getSelectedFile();
            try {
              PrintWriter out = new PrintWriter(f);
              String javaCodeText = ODEWizardTextArea.getText();
              out.write(javaCodeText);
              out.close();
              // update the notion  of the working directory
              String fullPathOfSavedFile = f.getAbsolutePath();
              GlobalValues.workingDir =
                  fullPathOfSavedFile.substring(
                      0, fullPathOfSavedFile.lastIndexOf(File.separatorChar) + 1);

              compileJavaClassButton.setEnabled(true);
              compileJavaInternalCompilerButton.setEnabled(true);
              statusAreaBottom.setText(
                  "Step4:  The Java source file was saved to disk,  \n "
                      + "you can proceed to compile and load the corresponding class file");
            } catch (java.io.FileNotFoundException enf) {
              System.out.println("File " + f.getName() + " not found");
              enf.printStackTrace();
            } catch (Exception eOther) {
              System.out.println("Exception trying to create PrintWriter");
              eOther.printStackTrace();
            }
          }
        });

    // Step 4: Compile the generated Java class
    compileJavaClassButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String currentWorkingDirectory = GlobalValues.workingDir;
            JFileChooser chooser = new JFileChooser(currentWorkingDirectory);
            int ret = chooser.showOpenDialog(ODEWizardFrame);

            if (ret != JFileChooser.APPROVE_OPTION) {
              return;
            }
            File f = chooser.getSelectedFile();
            String javaFile = null;
            try {
              javaFile = f.getCanonicalPath();
            } catch (IOException ex) {
              System.out.println("I/O Exception in getCanonicalPath");
              ex.printStackTrace();
            }

            //   extract the path specification of the generated Java class that implements the ODE
            // solution method,
            //    in order to update the ScalaSci class path
            String SelectedFileWithPath = f.getAbsolutePath();
            String SelectedFilePathOnly =
                SelectedFileWithPath.substring(
                    0, SelectedFileWithPath.lastIndexOf(File.separatorChar));

            if (GlobalValues.ScalaSciClassPath.length() == 0) GlobalValues.ScalaSciClassPath = ".";
            if (GlobalValues.ScalaSciClassPath.indexOf(SelectedFilePathOnly) == -1) {
              GlobalValues.ScalaSciClassPathComponents.add(0, SelectedFilePathOnly);
              GlobalValues.ScalaSciClassPath =
                  GlobalValues.ScalaSciClassPath + File.pathSeparator + SelectedFilePathOnly;
            }
            // update also the ScalaSciClassPath property
            StringBuilder fileStr = new StringBuilder();
            Enumeration enumDirs = GlobalValues.ScalaSciClassPathComponents.elements();
            while (enumDirs.hasMoreElements()) {
              Object ce = enumDirs.nextElement();
              fileStr.append(File.pathSeparator + (String) ce);
            }
            GlobalValues.settings.setProperty("ScalaSciClassPath", fileStr.toString());

            ClassLoader parentClassLoader = getClass().getClassLoader();
            GlobalValues.extensionClassLoader =
                new ExtensionClassLoader(GlobalValues.ScalaSciClassPath, parentClassLoader);

            // update GUI components to account for the updated ScalaSci classpath
            scalaExec.scalaLab.scalaLab.updateTree();

            boolean compilationSucccess = true;

            String tempFileName = "";
            tempFileName =
                javaFile + ".java"; // public classes and Java files should have the same name

            String[] command = new String[6];
            command[0] = "javac";
            command[1] = "-cp";
            command[2] = GlobalValues.jarFilePath + File.pathSeparator + GlobalValues.homeDir;
            command[3] = "-d"; // where to place output class files
            command[4] = SelectedFilePathOnly; //  the path to save the compiled class files
            command[5] = javaFile; // full filename to compile

            String compileCommandString =
                command[0]
                    + "  "
                    + command[1]
                    + "  "
                    + command[2]
                    + " "
                    + command[3]
                    + " "
                    + command[4]
                    + " "
                    + command[5];

            System.out.println("compileCommand Java= " + compileCommandString);

            try {
              Runtime rt = Runtime.getRuntime();
              Process javaProcess = rt.exec(command);
              // an error message?
              StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

              // any output?
              StreamGobbler outputGobbler =
                  new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

              // kick them off
              errorGobbler.start();
              outputGobbler.start();

              // any error???
              javaProcess.waitFor();
              int rv = javaProcess.exitValue();
              String commandString = command[0] + "  " + command[1] + "  " + command[2];
              if (rv == 0) {
                System.out.println("Process:  " + commandString + "  exited successfully ");
                generateScriptCodeButton.setEnabled(true);
                statusAreaBottom.setText(
                    "Step5:  You can proceed now to create a draft script that utilizes your Java-based  ODE integrator");
              } else
                System.out.println(
                    "Process:  " + commandString + "  exited with error, error value = " + rv);

            } catch (IOException exio) {
              System.out.println("IOException trying to executing " + command);
              exio.printStackTrace();

            } catch (InterruptedException ie) {
              System.out.println("Interrupted Exception  trying to executing " + command);
              ie.printStackTrace();
            }
          }
        });

    // Compile with the internal compiler
    compileJavaInternalCompilerButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            String currentWorkingDirectory = GlobalValues.workingDir;
            JFileChooser chooser = new JFileChooser(currentWorkingDirectory);
            int ret = chooser.showOpenDialog(ODEWizardFrame);

            if (ret != JFileChooser.APPROVE_OPTION) {
              return;
            }
            File f = chooser.getSelectedFile();
            String javaFile = null;
            try {
              javaFile = f.getCanonicalPath();
            } catch (IOException ex) {
              System.out.println("I/O Exception in getCanonicalPath");
              ex.printStackTrace();
            }

            //   extract the path specification of the generated Java class that implements the ODE
            // solution method,
            //    in order to update the ScalaSci class path
            String SelectedFileWithPath = f.getAbsolutePath();
            String SelectedFilePathOnly =
                SelectedFileWithPath.substring(
                    0, SelectedFileWithPath.lastIndexOf(File.separatorChar));

            if (GlobalValues.ScalaSciClassPath.length() == 0) GlobalValues.ScalaSciClassPath = ".";
            if (GlobalValues.ScalaSciClassPath.indexOf(SelectedFilePathOnly) == -1) {
              GlobalValues.ScalaSciClassPathComponents.add(0, SelectedFilePathOnly);
              GlobalValues.ScalaSciClassPath =
                  GlobalValues.ScalaSciClassPath + File.pathSeparator + SelectedFilePathOnly;
            }
            // update also the ScalaSciClassPath property
            StringBuilder fileStr = new StringBuilder();
            Enumeration enumDirs = GlobalValues.ScalaSciClassPathComponents.elements();
            while (enumDirs.hasMoreElements()) {
              Object ce = enumDirs.nextElement();
              fileStr.append(File.pathSeparator + (String) ce);
            }
            GlobalValues.settings.setProperty("ScalaSciClassPath", fileStr.toString());

            ClassLoader parentClassLoader = getClass().getClassLoader();
            GlobalValues.extensionClassLoader =
                new ExtensionClassLoader(GlobalValues.ScalaSciClassPath, parentClassLoader);

            // update GUI components to account for the updated ScalaSci classpath
            scalaExec.scalaLab.scalaLab.updateTree();

            String[] command = new String[11];
            String toolboxes = "";
            for (int k = 0; k < GlobalValues.ScalaSciClassPathComponents.size(); k++)
              toolboxes =
                  toolboxes
                      + File.pathSeparator
                      + GlobalValues.ScalaSciClassPathComponents.elementAt(k);

            // compile the temporary file
            command[0] = "java";
            command[1] = "-classpath";
            command[2] =
                "."
                    + File.pathSeparator
                    + GlobalValues.jarFilePath
                    + File.pathSeparator
                    + toolboxes
                    + File.pathSeparator
                    + SelectedFilePathOnly;
            command[3] = "com.sun.tools.javac.Main"; // the name of the Java  compiler class
            command[4] = "-classpath";
            command[5] = command[2];
            command[6] = "-sourcepath";
            command[7] = command[2];
            command[8] = "-d"; // where to place output class files
            command[9] = SelectedFilePathOnly;
            command[10] = SelectedFileWithPath;
            String compileCommandString =
                command[0]
                    + "  "
                    + command[1]
                    + "  "
                    + command[2]
                    + " "
                    + command[3]
                    + " "
                    + command[4]
                    + " "
                    + command[5]
                    + " "
                    + command[6]
                    + " "
                    + command[7]
                    + " "
                    + command[8]
                    + " "
                    + command[9]
                    + " "
                    + command[10];

            System.out.println("compileCommand Java= " + compileCommandString);

            try {
              Runtime rt = Runtime.getRuntime();
              Process javaProcess = rt.exec(command);
              // an error message?
              StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

              // any output?
              StreamGobbler outputGobbler =
                  new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

              // kick them off
              errorGobbler.start();
              outputGobbler.start();

              // any error???
              javaProcess.waitFor();
              int rv = javaProcess.exitValue();
              if (rv == 0) {
                System.out.println("Process:  exited successfully ");

                JavaCompile javaCompileObj = null;
                try {
                  javaCompileObj = new JavaCompile();
                } catch (Exception ex) {
                  JOptionPane.showMessageDialog(
                      null,
                      "Unable to compile. Please check if your system's PATH variable includes the path to your javac compiler",
                      "Cannot compile - Check PATH",
                      JOptionPane.INFORMATION_MESSAGE);
                  ex.printStackTrace();
                }
                generateScriptCodeButton.setEnabled(true);
                statusAreaBottom.setText(
                    "Step5:  You can proceed now to create a draft ScalaSci-Script that utilizes your Java-based  ODE integrator");

              } else System.out.println("Process:  exited with error, error value = " + rv);

            } catch (IOException exio) {
              System.out.println("IOException trying to executing " + command);
              exio.printStackTrace();

            } catch (InterruptedException ie) {
              System.out.println("Interrupted Exception  trying to executing " + command);
              ie.printStackTrace();
            }
          }
        });

    // Step 5: Generate Script Code
    generateScriptCodeButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            new scriptCodeGenerationFrame("ODE Script code", editingClassName, systemOrder);
          }
        });

    buttonPanel.add(copyTemplateButton); // Step 1
    buttonPanel.setEnabled(true);
    buttonPanel.add(generateEditingButton); // Step 2
    generateEditingButton.setEnabled(false);
    buttonPanel.add(saveJavaClassButton); // Step 3
    saveJavaClassButton.setEnabled(false);
    buttonPanel.add(compileJavaClassButton); // Step 4
    buttonPanel.add(compileJavaInternalCompilerButton);
    compileJavaClassButton.setEnabled(false);
    compileJavaInternalCompilerButton.setEnabled(false);
    buttonPanel.add(generateScriptCodeButton); // Step 5
    generateScriptCodeButton.setEnabled(false);

    ODEWizardFrame.add(buttonPanel, BorderLayout.NORTH);
    ODEWizardFrame.add(editPanel, BorderLayout.CENTER);
    JPanel bottomPanel = new JPanel(new GridLayout(2, 1));

    bottomPanel.add(paramPanel);
    bottomPanel.add(statusPanel);
    ODEWizardFrame.add(bottomPanel, BorderLayout.SOUTH);
    ODEWizardFrame.setLocation(100, 100);
    ODEWizardFrame.setSize(1400, 800);
    ODEWizardFrame.setVisible(true);
  }
  /**
   * Create the train module GUI (the dynamic and static windows). Both windows are HIDE_ON_CLOSE so
   * that closing them does not cause the train module to close.
   */
  public TrainModelUI() {
    try {
      JPanel emptyJPanel = new JPanel();
      emptyJPanel.add(new JLabel("            "));
      isPaused = true;

      // Setup the dynamicWindow.

      btnShowStaticValues = buildJButton("Show Static Values");
      btnSelectTrain = buildJButton("Select Train");
      btnPauseResume = buildJButton("Pause");
      btnPauseResume.setEnabled(false);
      btnSetManRecPower = buildJButton("Set Manual Received Power");
      btnToggleManRecPower = buildJButton("Toggle Manual Received Power");
      btnSetManDesSpdLmt = buildJButton("Set Manual Desired Speed Limit");
      btnToggleManDesSpdLmt = buildJButton("Toggle Manual Desired Speed Limit");
      btnToggleSignalPickupFailure = buildJButton("Toggle Signal Pickup Failure");
      btnToggleEngineFailure = buildJButton("Toggle Engine Failure");
      btnToggleBrakeFailure = buildJButton("Toggle Brake Failure");
      btnToggleServiceBrake = buildJButton("Toggle Service Brake");
      btnToggleEmergencyBrake = buildJButton("Toggle Emergency Brake");
      btnSetManLights = buildJButton("Set Manual Lights Status");
      btnToggleManLights = buildJButton("Toggle Manual Lights Status");
      btnSetManDoors = buildJButton("Set Manual Doors Status");
      btnToggleManDoors = buildJButton("Toggle Manual Doors Status");
      btnSetManTarTemperature = buildJButton("Set Manual Target Temp.");
      btnToggleManTarTemperature = buildJButton("Toggle Manual Target Temp.");

      jlTime = new JLabel("XX:XX:XX", JLabel.CENTER);
      jlCurVel = new JLabel("", JLabel.CENTER);
      jlCurAccel = new JLabel("", JLabel.CENTER);
      jlRecPowerTNC = new JLabel("", JLabel.CENTER);
      jlManRecPower = new JLabel("", JLabel.CENTER);
      jlToggleManRecPower = new JLabel("", JLabel.CENTER);
      jlPostedSpdLmt = new JLabel("", JLabel.CENTER);
      jlManDesSpdLmt = new JLabel("", JLabel.CENTER);
      jlToggleManDesSpdLmt = new JLabel("", JLabel.CENTER);
      jlGrade = new JLabel("", JLabel.CENTER);
      jlTotalMass = new JLabel("", JLabel.CENTER);
      jlPassengerCount = new JLabel("", JLabel.CENTER);
      jlCrewCount = new JLabel("", JLabel.CENTER);
      jlPosition = new JLabel("", JLabel.CENTER);
      jlToggleSignalPickupFailure = new JLabel("", JLabel.CENTER);
      jlToggleEngineFailure = new JLabel("", JLabel.CENTER);
      jlToggleBrakeFailure = new JLabel("", JLabel.CENTER);
      jlToggleServiceBrake = new JLabel("", JLabel.CENTER);
      jlToggleEmergencyBrake = new JLabel("", JLabel.CENTER);
      jlLights = new JLabel("", JLabel.CENTER);
      jlManLights = new JLabel("", JLabel.CENTER);
      jlToggleManLights = new JLabel("", JLabel.CENTER);
      jlDoors = new JLabel("", JLabel.CENTER);
      jlManDoors = new JLabel("", JLabel.CENTER);
      jlToggleManDoors = new JLabel("", JLabel.CENTER);
      jlCurTemperature = new JLabel("", JLabel.CENTER);
      jlTarTemperature = new JLabel("", JLabel.CENTER);
      jlManTarTemperature = new JLabel("", JLabel.CENTER);
      jlToggleManTarTemperature = new JLabel("", JLabel.CENTER);
      jlAnnouncement = new JLabel("", JLabel.CENTER);

      JPanel dwPanel1 = new JPanel();
      dwPanel1.setLayout(new GridLayout(18, 2));
      dwPanel1.add(buildJPanel(new JLabel("Current Velocity (m/s)", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlCurVel));
      dwPanel1.add(buildJPanel(new JLabel("Current Acceleration (m/s^2)", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlCurAccel));
      dwPanel1.add(buildJPanel(new JLabel("Received Power from TNC (W)", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlRecPowerTNC));
      dwPanel1.add(buildJPanel(btnSetManRecPower));
      dwPanel1.add(buildJPanel(jlManRecPower));
      dwPanel1.add(buildJPanel(btnToggleManRecPower));
      dwPanel1.add(buildJPanel(jlToggleManRecPower));
      dwPanel1.add(buildJPanel(new JLabel("Speed Limit Posted on Signs (m/s)", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlPostedSpdLmt));
      dwPanel1.add(buildJPanel(btnSetManDesSpdLmt));
      dwPanel1.add(buildJPanel(jlManDesSpdLmt));
      dwPanel1.add(buildJPanel(btnToggleManDesSpdLmt));
      dwPanel1.add(buildJPanel(jlToggleManDesSpdLmt));
      dwPanel1.add(buildJPanel(new JLabel("Relative Grade from TKM (%)", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlGrade));
      dwPanel1.add(
          buildJPanel(new JLabel("Total Mass (inc. passengers/crew) (kg)", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlTotalMass));
      dwPanel1.add(buildJPanel(new JLabel("Passenger Count", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlPassengerCount));
      dwPanel1.add(buildJPanel(new JLabel("Crew Count", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlCrewCount));
      dwPanel1.add(
          buildJPanel(new JLabel("Position from Onboard GPS ([block], m)", JLabel.CENTER)));
      dwPanel1.add(buildJPanel(jlPosition));
      dwPanel1.add(buildJPanel(btnToggleSignalPickupFailure));
      dwPanel1.add(buildJPanel(jlToggleSignalPickupFailure));
      dwPanel1.add(buildJPanel(btnToggleEngineFailure));
      dwPanel1.add(buildJPanel(jlToggleEngineFailure));
      dwPanel1.add(buildJPanel(btnToggleBrakeFailure));
      dwPanel1.add(buildJPanel(jlToggleBrakeFailure));
      dwPanel1.add(buildJPanel(btnToggleServiceBrake));
      dwPanel1.add(buildJPanel(jlToggleServiceBrake));
      dwPanel1.add(buildJPanel(btnToggleEmergencyBrake));
      dwPanel1.add(buildJPanel(jlToggleEmergencyBrake));
      JPanel dwPanel2 = new JPanel();
      dwPanel2.setLayout(new GridLayout(18, 2));
      dwPanel2.add(buildJPanel(new JLabel("Lights Status", JLabel.CENTER)));
      dwPanel2.add(buildJPanel(jlLights));
      dwPanel2.add(buildJPanel(btnSetManLights));
      dwPanel2.add(buildJPanel(jlManLights));
      dwPanel2.add(buildJPanel(btnToggleManLights));
      dwPanel2.add(buildJPanel(jlToggleManLights));
      dwPanel2.add(buildJPanel(new JLabel("Doors Status", JLabel.CENTER)));
      dwPanel2.add(buildJPanel(jlDoors));
      dwPanel2.add(buildJPanel(btnSetManDoors));
      dwPanel2.add(buildJPanel(jlManDoors));
      dwPanel2.add(buildJPanel(btnToggleManDoors));
      dwPanel2.add(buildJPanel(jlToggleManDoors));
      dwPanel2.add(buildJPanel(new JLabel("Current Temp. (degrees F)", JLabel.CENTER)));
      dwPanel2.add(buildJPanel(jlCurTemperature));
      dwPanel2.add(buildJPanel(new JLabel("Target Temp. from TNC (degrees F)", JLabel.CENTER)));
      dwPanel2.add(buildJPanel(jlTarTemperature));
      dwPanel2.add(buildJPanel(btnSetManTarTemperature));
      dwPanel2.add(buildJPanel(jlManTarTemperature));
      dwPanel2.add(buildJPanel(btnToggleManTarTemperature));
      dwPanel2.add(buildJPanel(jlToggleManTarTemperature));
      dwPanel2.add(buildJPanel(new JLabel("Announcement", JLabel.CENTER)));
      dwPanel2.add(buildJPanel(jlAnnouncement));

      JPanel primaryButtons = new JPanel();
      primaryButtons.setLayout(new GridLayout(1, 4));
      primaryButtons.add(btnShowStaticValues);
      primaryButtons.add(btnSelectTrain);
      primaryButtons.add(btnPauseResume);
      primaryButtons.add(buildJPanel(jlTime));

      JPanel jp = new JPanel();
      jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
      jp.add(primaryButtons);
      jp.add(emptyJPanel);
      jp.add(new JSeparator(JSeparator.HORIZONTAL));
      jp.add(dwPanel1);
      jp.add(new JSeparator(JSeparator.HORIZONTAL));
      jp.add(dwPanel2);

      jp.setMaximumSize(new Dimension(400, 700));

      JScrollPane dScroll = new JScrollPane(jp);
      dScroll.setViewportView(jp);

      dynamicWindow = new JFrame();
      dynamicWindow.setTitle("Train Model (Chris Paskie)   -   UI   (Train ID:   --)");
      dynamicWindow.setSize(600, 400);
      dynamicWindow.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
      dynamicWindow.add(dScroll);
      isVisible = false;
      dynamicWindow.setVisible(isVisible);

      // Setup the staticWindow.

      jlLength = new JLabel("", JLabel.CENTER);
      jlWidth = new JLabel("", JLabel.CENTER);
      jlHeight = new JLabel("", JLabel.CENTER);
      jlNumCars = new JLabel("", JLabel.CENTER);
      jlMotorPower = new JLabel("", JLabel.CENTER);
      jlMaxSpeed = new JLabel("", JLabel.CENTER);
      jlServiceBrakeDecel = new JLabel("", JLabel.CENTER);
      jlEmergencyBrakeDecel = new JLabel("", JLabel.CENTER);
      jlFrictionCoeff = new JLabel("", JLabel.CENTER);
      jlEmptyTrainMass = new JLabel("", JLabel.CENTER);
      jlPersonMass = new JLabel("", JLabel.CENTER);
      jlMaxSeatedCount = new JLabel("", JLabel.CENTER);
      jlMaxStandingCount = new JLabel("", JLabel.CENTER);
      jlMaxCrewCount = new JLabel("", JLabel.CENTER);

      JPanel swPanel = new JPanel();
      swPanel.setLayout(new GridLayout(14, 2));
      swPanel.add(buildJPanel(new JLabel("Length (m)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlLength));
      swPanel.add(buildJPanel(new JLabel("Width (m)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlWidth));
      swPanel.add(buildJPanel(new JLabel("Height (m)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlHeight));
      swPanel.add(buildJPanel(new JLabel("Number of Cars", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlNumCars));
      swPanel.add(buildJPanel(new JLabel("Motor Power (W)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlMotorPower));
      swPanel.add(buildJPanel(new JLabel("Maximum Speed (m/s)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlMaxSpeed));
      swPanel.add(buildJPanel(new JLabel("Service Brake Deceleration (m/s^2)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlServiceBrakeDecel));
      swPanel.add(buildJPanel(new JLabel("Emergency Brake Deceleration (m/s^2)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlEmergencyBrakeDecel));
      swPanel.add(buildJPanel(new JLabel("Coefficient of Friction", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlFrictionCoeff));
      swPanel.add(
          buildJPanel(new JLabel("Train Mass (not inc. passengers/crew) (kg)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlEmptyTrainMass));
      swPanel.add(buildJPanel(new JLabel("Mass Per Passenger/Crew (kg)", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlPersonMass));
      swPanel.add(buildJPanel(new JLabel("Maximum Seated Passenger Count", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlMaxSeatedCount));
      swPanel.add(buildJPanel(new JLabel("Maximum Standing Passenger Count", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlMaxStandingCount));
      swPanel.add(buildJPanel(new JLabel("Maximum Crew Count", JLabel.CENTER)));
      swPanel.add(buildJPanel(jlMaxCrewCount));

      staticWindow = new JFrame();
      staticWindow.setTitle("Train Model (Chris Paskie)   -   Static Values   (Train ID:   --)");
      staticWindow.setSize(700, 600);
      staticWindow.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
      staticWindow.add(swPanel);
      isVisibleStatic = false;
      staticWindow.setVisible(isVisibleStatic);

      // Set up the TNC UI.
      if (!isSolo) {
        tncUI = new TNC_UI();
      }

    } catch (Exception e) {
      e.printStackTrace(System.err);
      JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
    }
  }
Example #16
0
  public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(PORT);
    System.out.println("Started: " + s);
    frame.setPreferredSize(new Dimension(400, 400));
    frame.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });
    JMenuBar one = new JMenuBar();
    JMenu second = new JMenu("OPTIONS");
    //	JMenuItem third = new JMenuItem("NEW GAME");
    JMenuItem fourth = new JMenuItem("EXIT");
    fourth.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            try {
              exit(evt);
            } catch (IOException e) {
            }
          }
        });
    // second.add(third);
    second.add(fourth);
    one.add(second);
    frame.setJMenuBar(one);
    frame.setLayout(new java.awt.GridLayout(3, 3));
    button = new JButton[10];
    for (int i = 1; i < 10; i++) {
      button[i] = new JButton();
      button[i].setBackground(Color.lightGray);
      button[i].setActionCommand(Integer.toString(i));
      button[i].addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              print(evt.getActionCommand());
              try {
                func(socket, evt.getActionCommand());
                String check = win();
                finalresult(check);
                if (check != "") {
                  func(socket, check);
                } else {
                  func(socket, evt.getActionCommand());
                }
                ;
              } catch (IOException e) {
              }
            }
          });
      frame.add(button[i]);
    }

    try {
      socket = s.accept();
      frame.pack();
      frame.setVisible(true);
      try {
        System.out.println("Connection accepted: " + socket);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        /*  while(true)
        {
        String str=in.readLine();
        print2(str);
        }*/
        while (true) {
          String str = in.readLine();
          if (str.equals("exit")) {
            System.exit(0);
          }
          if (str.equals("tie")) {
            JOptionPane.showMessageDialog(null, "It is a tie between the two");
            System.exit(0);
          } else {

            if (str.equals("winserver")) {
              System.out.println("server has won");
              JOptionPane.showMessageDialog(null, "the server has won the game");
              System.exit(0);
            } else {
              if (str.equals("winclient")) {
                JOptionPane.showMessageDialog(null, "the client has won the game");
                System.exit(0);
              } else {
                System.out.println(str);
                print2(str);
              }
            }
          }
        }
      } catch (Exception e) {
      } // finally {socket.close();
      // }
    } catch (Exception e) {
    } // finally {s.close();
    // }
  }
Example #17
0
  public LJ3MDApp() {
    tNum.setHorizontalAlignment(JTextField.CENTER);
    tTemp.setHorizontalAlignment(JTextField.CENTER);
    tRho.setHorizontalAlignment(JTextField.CENTER);
    tSpeed.setHorizontalAlignment(JTextField.CENTER);

    tAvK.setHorizontalAlignment(JTextField.RIGHT);
    tAvU.setHorizontalAlignment(JTextField.RIGHT);
    tAvp.setHorizontalAlignment(JTextField.RIGHT);

    float[] aveKing = new float[501];
    float[] avePot = new float[501];
    float[] aveEn = new float[501];

    JFrame box = new JFrame();
    box.setLayout(new BorderLayout());
    box.setSize(1000, 1000);
    box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    cpnl = new JPanel(); // create a panel for controls
    cpnl.setLayout(new GridLayout(18, 2));
    box.add(cpnl, BorderLayout.EAST);

    // add controls
    cpnl.add(bStart);
    bStart.addActionListener(this);

    cpnl.add(bReset);
    bReset.addActionListener(this);

    cpnl.add(new JLabel(" N:"));
    tNum.addActionListener(this);
    cpnl.add(tNum);

    cpnl.add(new JLabel(" Density (\u03c1):"));
    tRho.addActionListener(this);
    cpnl.add(tRho);

    cpnl.add(new JLabel(" Steps/frame:"));
    tSpeed.addActionListener(this);
    cpnl.add(tSpeed);

    cpnl.add(bTstat);
    bTstat.addActionListener(this);

    cpnl.add(bPot);
    bPot.addActionListener(this);

    cpnl.add(new JLabel(" < K/N > :"));
    tAvK.setEditable(false);
    cpnl.add(tAvK);

    cpnl.add(new JLabel(" Temperature:"));
    tTemp.setEditable(false);
    cpnl.add(tTemp);

    cpnl.add(new JLabel(" < U/N > :"));
    tAvU.setEditable(false);
    cpnl.add(tAvU);

    cpnl.add(new JLabel(" < pressure > :"));
    tAvp.setEditable(false);
    cpnl.add(tAvp);

    cpnl.add(bRetime);
    bRetime.addActionListener(this);

    spnl = new JPanel(); // create a panel for status
    box.add(spnl, BorderLayout.SOUTH);
    lStatus.setFont(new Font("Courier", 0, 12));
    spnl.add(lStatus);

    canvas = new XYZCanvas();
    box.add(canvas, BorderLayout.CENTER);

    timer = new Timer(delay, this);
    timer.start();
    //        timer.stop();
    box.setVisible(true);
  }
 private static void initGui() {
   try {
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
   } catch (Exception exception) {
     exception.printStackTrace();
   }
   JFrame frame = new JFrame("DarkBot");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setLayout(new GridBagLayout());
   Insets noInsets = new Insets(0, 0, 0, 0);
   final JToggleButton sessionsButton = new JToggleButton("Login (0)");
   frame.add(
       sessionsButton,
       new GridBagConstraints(
           0, 0, 2, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, noInsets, 0, 0));
   sessionsButton.addActionListener(
       new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
           sessions.set(sessionsButton.isSelected());
           synchronized (sessions) {
             sessions.notifyAll();
           }
         }
       });
   final JToggleButton joinsButton = new JToggleButton("Join (0)");
   frame.add(
       joinsButton,
       new GridBagConstraints(
           0, 1, 2, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, noInsets, 0, 0));
   joinsButton.addActionListener(
       new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
           joins.set(joinsButton.isSelected());
           synchronized (joins) {
             joins.notifyAll();
           }
         }
       });
   final JTextField field = new JTextField();
   frame.add(
       field,
       new GridBagConstraints(
           0, 2, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, noInsets, 0, 0));
   final JButton button = new JButton("Start");
   frame.add(
       button,
       new GridBagConstraints(
           1, 2, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, noInsets, 0, 0));
   button.addActionListener(
       new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
           if (button.getText().startsWith("Start")) {
             field.setEnabled(false);
             spamMessage = field.getText();
             button.setText("Stop");
           } else {
             spamMessage = null;
             button.setText("Start");
             field.setEnabled(true);
           }
         }
       });
   Timer timer =
       new Timer(
           500,
           new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
               sessionsButton.setText(
                   sessionsButton.getText().split(" ")[0]
                       + " ("
                       + Integer.toString(sessionCount.get())
                       + ")");
               joinsButton.setText(
                   joinsButton.getText().split(" ")[0]
                       + " ("
                       + Integer.toString(amountJoined.get())
                       + ")");
             }
           });
   timer.setRepeats(true);
   timer.start();
   frame.pack();
   frame.setSize(500, frame.getHeight());
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }
Example #19
0
  public void launchChess() {

    mainWindow = new JFrame("网络黑白棋	作者:张炀");
    jpWest = new JPanel();
    jpEast = new JPanel();
    jpNorth = new JPanel();
    jpSouth = new JPanel();
    jpCenter = new JPanel();

    turnLabel = new JLabel();
    blackNumberLabel = new JLabel("黑棋:\n" + black + "		");
    whiteNumberLabel = new JLabel("白棋:\n" + white + "		");
    timeLabel = new JLabel("时间:  " + time + "		s");
    noticeLabel = new JLabel();

    noticeLabel = new JLabel("请选择:");
    numberPane = new JPanel();
    readyPane = new JPanel();
    jt1 = new JTextField(18); // 发送信息框
    jt2 = new JTextArea(3, 30); // 显示信息框
    js = new JScrollPane(jt2);
    jt2.setLineWrap(true);
    jt2.setEditable(false);
    //		jt1.setLineWrap(true);

    send = new JButton("发送");
    cancel = new JButton("取消");
    regret = new JButton("悔棋");
    submit = new JButton("退出");
    begin = new JButton("开始");
    save = new JButton("存盘");

    save.setEnabled(true);
    begin.setEnabled(true);

    fighter = new JRadioButton("下棋");
    audience = new JRadioButton("观看");
    group = new ButtonGroup();
    group.add(audience);
    group.add(fighter);
    group.add(AIPlayer);

    submit.addActionListener(this);
    begin.addActionListener(this);
    save.addActionListener(this);
    send.addActionListener(this);
    cancel.addActionListener(this);
    regret.addActionListener(this);
    fighter.addActionListener(this);
    audience.addActionListener(this);

    jpNorth.setLayout(new BorderLayout());
    jpNorth.add(turnLabel, BorderLayout.NORTH);
    jpNorth.add(jpCenter, BorderLayout.CENTER);
    jpSouth.add(js);
    jpSouth.add(jt1);
    jpSouth.add(send);
    jpSouth.add(cancel);
    jpEast.setLayout(new GridLayout(3, 1));
    submit.setBackground(new Color(130, 251, 241));
    panel x = new panel();
    jpEast.add(x);
    jpEast.add(numberPane);
    jpEast.add(readyPane);

    numberPane.add(blackNumberLabel);
    numberPane.add(whiteNumberLabel);
    numberPane.add(timeLabel);
    numberPane.add(submit);
    numberPane.add(begin);
    numberPane.add(save);
    numberPane.add(regret);

    readyPane.add(noticeLabel);
    readyPane.add(fighter);
    readyPane.add(audience);
    //		readyPane.add(save);
    //		readyPane.add(regret);

    jpCenter.setSize(400, 400);
    jmb = new JMenuBar();
    document = new JMenu("游戏		");
    edit = new JMenu("设置		");
    insert = new JMenu("棋盘			");
    help = new JMenu("帮助		");
    jmb.add(document);
    jmb.add(edit);
    jmb.add(insert);
    jmb.add(help);
    // mainWindow.setJMenuBar(jmb);

    mainWindow.setBounds(80, 80, 600, 600);
    mainWindow.setResizable(false);

    jsLeft = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, jpNorth, jpSouth);
    jsBase = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, jsLeft, jpEast);

    mainWindow.add(jsBase);
    mainWindow.setVisible(true);
    mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    jsBase.setDividerLocation(0.7);
    jsLeft.setDividerLocation(0.78);

    jpCenter.setLayout(new GridLayout(8, 8, 0, 0));
    ImageIcon key = new ImageIcon("chess1.jpg");
    for (int i = 0; i < cell.length; i++)
      for (int j = 0; j < cell.length; j++) {
        cell[i][j] = new ChessBoard(i, j);
        cell[i][j].addMouseListener(this);
        jpCenter.add(cell[i][j]);
      }

    cell[3][3].state = cell[4][4].state = '黑';
    cell[4][3].state = cell[3][4].state = '白';
    cell[3][3].taken = cell[4][4].taken = true;
    cell[4][3].taken = cell[3][4].taken = true;

    RememberState();

    new Thread(new TurnLabel(this)).start();

    file = new File("D:/" + myRole);
    try {
      fout = new FileOutputStream(file);
      out = new ObjectOutputStream(fout);
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    Connect();

    try {
      out99 = new ObjectOutputStream(socket99.getOutputStream());
      in99 = new ObjectInputStream(socket99.getInputStream());

      out66 = new ObjectOutputStream(socket66.getOutputStream());
      in66 = new ObjectInputStream(socket66.getInputStream());

      out88 = new DataOutputStream(socket88.getOutputStream());
    } catch (IOException e) {
      e.printStackTrace();
    }

    new Thread(new Client9999(this)).start();
    new Thread(new Client6666(this)).start();
  }
Example #20
0
  // compile a Java file with the installed javac compiler
  public boolean compileFile(String sourceFile) {
    boolean compilationResult = true; // no errors

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) { // Sterg-SOS why not loaded?
      System.out.println(
          "ToolProvider.getSystemJavaCompiler: no compiler provided. Unable to compile");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

    StringWriter compileWriter = new StringWriter();

    List<File> sourceFileList = new ArrayList<File>();
    sourceFileList.add(new File(sourceFile));
    Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromFiles(sourceFileList);

    String pathOfFile = sourceFile.substring(0, sourceFile.lastIndexOf(File.separatorChar));
    String classpath =
        GlobalValues.jarFilePath
            + File.pathSeparatorChar
            + pathOfFile
            + File.pathSeparatorChar
            + ".";
    Iterable<String> options = Arrays.asList("-cp", classpath);

    CompilationTask task =
        compiler.getTask(compileWriter, fileManager, null, options, null, compilationUnits);

    boolean compileResult = task.call();
    if (compileResult == false) {
      compilationResult = false; // compilation errors
      JFrame compResultsFrame = new JFrame("Compilation Results");
      String diagnString = compileWriter.toString();
      JTextArea compResultsArea = new JTextArea(diagnString);
      compResultsArea.setFont(new Font("Arial", Font.BOLD, 16));
      JPanel compResultsPanel = new JPanel();
      compResultsPanel.add(compResultsArea);
      compResultsFrame.add(compResultsPanel);
      compResultsFrame.setSize(800, 200);
      compResultsFrame.setLocation(100, 200);
      compResultsFrame.setVisible(true);
      int response =
          JOptionPane.showOptionDialog(
              null,
              "File " + sourceFile + " has compilation errors ",
              "Edit File? ",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              null,
              null);
      if (response == JOptionPane.YES_OPTION) { // edit it with scalalabEditor
        new scalalabEdit.EditorPaneEdit(sourceFile);
      }
    }

    try {
      fileManager.close();
    } catch (IOException e) {
    }

    return compilationResult;
  }
Example #21
0
  /**
   * Create a new, empty, not-visible TaxRef window. Really just activates the setup frame and setup
   * memory monitor components, then starts things off.
   */
  public MainFrame() {
    setupMemoryMonitor();

    // Set up the main frame.
    mainFrame = new JFrame(basicTitle);
    mainFrame.setJMenuBar(setupMenuBar());
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Set up the JTable.
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setSelectionBackground(COLOR_SELECTION_BACKGROUND);
    table.setShowGrid(true);

    // Add a blank table model so that the component renders properly on
    // startup.
    table.setModel(blankDataModel);

    // Add a list selection listener so we can tell the matchInfoPanel
    // that a new name was selected.
    table
        .getSelectionModel()
        .addListSelectionListener(
            new ListSelectionListener() {
              @Override
              public void valueChanged(ListSelectionEvent e) {
                if (currentCSV == null) return;

                int row = table.getSelectedRow();
                int column = table.getSelectedColumn();

                columnInfoPanel.columnChanged(column);

                Object o = table.getModel().getValueAt(row, column);
                if (Name.class.isAssignableFrom(o.getClass())) {
                  matchInfoPanel.nameSelected(currentCSV.getRowIndex(), (Name) o, row, column);
                } else {
                  matchInfoPanel.nameSelected(currentCSV.getRowIndex(), null, -1, -1);
                }
              }
            });

    // Set up the left panel (table + matchInfoPanel)
    JPanel leftPanel = new JPanel();

    matchInfoPanel = new MatchInformationPanel(this);
    leftPanel.setLayout(new BorderLayout());
    leftPanel.add(matchInfoPanel, BorderLayout.SOUTH);
    leftPanel.add(new JScrollPane(table));

    // Set up the right panel (columnInfoPanel)
    JPanel rightPanel = new JPanel();

    columnInfoPanel = new ColumnInformationPanel(this);

    progressBar.setStringPainted(true);

    rightPanel.setLayout(new BorderLayout());
    rightPanel.add(columnInfoPanel);
    rightPanel.add(progressBar, BorderLayout.SOUTH);

    // Set up a JSplitPane to split the panels up.
    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, leftPanel, rightPanel);
    split.setResizeWeight(1);
    mainFrame.add(split);
    mainFrame.pack();

    // Set up a drop target so we can pick up files
    mainFrame.setDropTarget(
        new DropTarget(
            mainFrame,
            new DropTargetAdapter() {
              @Override
              public void dragEnter(DropTargetDragEvent dtde) {
                // Accept any drags.
                dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
              }

              @Override
              public void dragOver(DropTargetDragEvent dtde) {}

              @Override
              public void dropActionChanged(DropTargetDragEvent dtde) {}

              @Override
              public void dragExit(DropTargetEvent dte) {}

              @Override
              public void drop(DropTargetDropEvent dtde) {
                // Accept a drop as long as its File List.

                if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                  dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

                  Transferable t = dtde.getTransferable();

                  try {
                    java.util.List<File> files =
                        (java.util.List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);

                    // If we're given multiple files, pick up only the last file and load that.
                    File f = files.get(files.size() - 1);
                    loadFile(f, DarwinCSV.FILE_CSV_DELIMITED);

                  } catch (UnsupportedFlavorException ex) {
                    dtde.dropComplete(false);

                  } catch (IOException ex) {
                    dtde.dropComplete(false);
                  }
                }
              }
            }));
  }
Example #22
0
  public GUI() {
    // ===============================================loads data from savefiles (textfiles)
    Classes.LoadData();
    // =========================================== resets the arrayIndexes array so that the the GUI
    // will first show the records according to IDNumber
    Classes.resetArrayIndexes();
    // =========================================== Redeclaring GUI Components (this is part of GUI
    // Syntax for some reason)
    // =========================================== This also gives text to those GUI Components
    search = new JButton("search");
    clearSearchParameters = new JButton("clear Parameters");
    help = new JButton("Help");
    resetDatabase = new JButton("Reset Database");
    messageToUser = new JLabel("");
    emptyLabel = new JLabel[3];
    newRecordButton = new JButton(" New Record");
    editRecordButton = new JButton(" Edit Record");
    deleteRecordButton = new JButton("Delete Record");

    searchTextfield = new JTextField[7];
    fieldNames = new JButton[7];
    textfield = new JTextField[6][100];
    indexes = new JLabel[100];
    RecordsFieldButtons = new JPanel();
    scrollPane = new JScrollPane();

    emptyLabel[0] = new JLabel("");
    emptyLabel[1] = new JLabel("");
    emptyLabel[2] = new JLabel("");
    fieldNames[0] = new JButton("ID#");
    fieldNames[1] = new JButton("Movie Name");
    fieldNames[2] = new JButton("Movie Length");
    fieldNames[3] = new JButton("Movie Director");
    fieldNames[4] = new JButton("Movie Rating");
    fieldNames[5] = new JButton("Movie Release Year");
    fieldNames[6] = new JButton("Movie Review" + "Rating");
    // =========================================== All the searchTextfields will be preset to the
    // text "enter Search Parameter"
    for (int x = 0; x < 7; x++) {
      searchTextfield[x] = new JTextField("enter Search Parameter");
    }
    // =========================================== This for loop attaches the correct array value to
    // the GUI Components
    for (int x = 0; x < 7; x++) {
      for (int y = 0; y < 100; y++) {
        switch (x) {
          case 0:
            // =============================== This checks if the value of IDNumber[xxx] is blank
            // (which is noted by a -1)
            // =============================== If it is, then it will set the text of its
            // corresponding Textfield to blank
            if (IDNumber[arrayIndexes[y]] == -1) {
              indexes[y] = new JLabel("");
            } else {
              indexes[y] = new JLabel(Integer.toString(IDNumber[arrayIndexes[y]]));
            }
            break;
          case 1:
            // =============================== This checks if the value of movieName[xxx] is blank
            // (which is noted by a "null")
            // =============================== If it is, then it will set the text of its
            // corresponding Textfield to blank
            if (movieName[arrayIndexes[y]].equals("null") == true) {
              textfield[x - 1][y] = new JTextField("");
            } else {
              textfield[x - 1][y] = new JTextField(movieName[arrayIndexes[y]]);
            }
            break;
          case 2:
            // =============================== This checks if the value of movieLength[xxx] is blank
            // (which is noted by a -1)
            // =============================== If it is, then it will set the text of its
            // corresponding Textfield to blank
            if (movieLength[arrayIndexes[y]] == -1) {
              textfield[x - 1][y] = new JTextField("");
            } else {
              textfield[x - 1][y] =
                  new JTextField(Integer.toString(movieLength[arrayIndexes[y]]) + " minutes");
            }
            break;
          case 3:
            // =============================== This checks if the value of movieDirector[xxx] is
            // blank (which is noted by a "null")
            // =============================== If it is, then it will set the text of its
            // corresponding Textfield to blank
            if (movieDirector[arrayIndexes[y]].equals("null") == true) {
              textfield[x - 1][y] = new JTextField("");
            } else {
              textfield[x - 1][y] = new JTextField(movieDirector[arrayIndexes[y]]);
            }
            break;
          case 4:
            // =============================== This checks if the value of movieRating[xxx] is blank
            // (which is noted by a "null") or if it is unavailable "N/A"
            // =============================== If it is, then it will set the text of its
            // corresponding Textfield to blank
            if ((movieRating[arrayIndexes[y]].equals("null") == true)
                || (movieRating[arrayIndexes[y]].equals("N/A") == true)) {
              textfield[x - 1][y] = new JTextField("");
            } else {
              textfield[x - 1][y] = new JTextField(movieRating[arrayIndexes[y]]);
            }
            break;
          case 5:
            // =============================== This checks if the value of movieReleaseYear[xxx] is
            // blank (which is noted by a -1)
            // =============================== If it is, then it will set the text of its
            // corresponding Textfield to blank
            if (movieReleaseYear[arrayIndexes[y]] == -1) {
              textfield[x - 1][y] = new JTextField("");
            } else {
              textfield[x - 1][y] =
                  new JTextField(Integer.toString(movieReleaseYear[arrayIndexes[y]]));
            }
            break;
          case 6:
            // =============================== This checks if the value of movieReviewRating[xxx] is
            // blank (which is noted by a -0.1)
            // =============================== If it is, then it will set the text of its
            // corresponding Textfield to blank
            if (movieReviewRating[arrayIndexes[y]] == -0.1) {
              textfield[x - 1][y] = new JTextField("");
            } else {
              textfield[x - 1][y] =
                  new JTextField(Double.toString(movieReviewRating[arrayIndexes[y]]));
            }
            break;
        }
        // =============================== This disables the ability for the all the textfields to
        // be edited.
        if ((x <= 6) && (x >= 1)) {
          textfield[x - 1][y].setEditable(false);
        }
      }
    }
    // ======================================= Makes the layout of the panel (gridlayout)
    RecordsFieldButtons.setLayout(new GridLayout(103, 7));
    // ======================================= adds the GUI components to the GUI
    RecordsFieldButtons.add(newRecordButton);
    RecordsFieldButtons.add(editRecordButton);
    RecordsFieldButtons.add(deleteRecordButton);
    // RecordsFieldButtons.add(messageToUser);
    // RecordsFieldButtons.add(emptyLabel[0]);
    // RecordsFieldButtons.add(emptyLabel[1]);
    // RecordsFieldButtons.add(emptyLabel[2]);
    RecordsFieldButtons.add(search);
    RecordsFieldButtons.add(clearSearchParameters);
    RecordsFieldButtons.add(resetDatabase);
    RecordsFieldButtons.add(help);

    // ======================================= places the searchTextfield onto the GUI
    for (int x = 0; x < 7; x++) {
      RecordsFieldButtons.add(searchTextfield[x]);
    }
    // ======================================= places the fieldnames onto the GUI. (the fieldnames
    // are also the buttons for sort)
    for (int x = 0; x < 7; x++) {
      // fieldNames[x].setLineWrap(true);
      RecordsFieldButtons.add(fieldNames[x]);
    }
    // ======================================= places the rest of the array values( textfields) onto
    // the GUI
    for (int y = 0; y < 100; y++) {
      for (int x = 0; x < 7; x++) {
        if (x == 0) {
          RecordsFieldButtons.add(indexes[y]);
        } else {
          RecordsFieldButtons.add(textfield[x - 1][y]);
        }
      }
    }
    // ======================================= changes the color of the fields names to orange
    // ======================================= the point of this is to give a separation between the
    // arrayvalues and the function buttons
    for (int i = 0; i < 7; i++) {
      fieldNames[i].setBackground(Color.ORANGE);
    }
    // ======================================= adds actions to all the GUI Components( if any)
    fieldNames[0].addActionListener(new whenUserClickIDNumberButton());
    fieldNames[1].addActionListener(new whenUserClickMovieNameButton());
    fieldNames[2].addActionListener(new whenUserClickMovieLengthButton());
    fieldNames[3].addActionListener(new whenUserClickMovieDirectorButton());
    fieldNames[4].addActionListener(new whenUserClickMovieRatingButton());
    fieldNames[5].addActionListener(new whenUserClickMovieReleaseYearButton());
    fieldNames[6].addActionListener(new whenUserClickMovieReviewButton());
    search.addActionListener(new whenUserClickSearchButton());
    clearSearchParameters.addActionListener(new whenUserClickClearParametersButton());
    help.addActionListener(new helpFunction());
    resetDatabase.addActionListener(new whenUserClicksResetDatabse());
    newRecordButton.addActionListener(new whenUserClicksNewButton());
    editRecordButton.addActionListener(new whenUserClicksEditButton());
    deleteRecordButton.addActionListener(new whenUserClicksDeleteButton());
    JFrame frame = new JFrame("Movie Database");
    frame.addWindowListener(new whenUserClicksXOnTheCornerOfWindow());
    frame.setResizable(true);
    frame.add(new JScrollPane(RecordsFieldButtons));
    frame.setSize(100, 100);
    frame.setVisible(true);
    frame.pack();
  }
  public WebcamCaptureAndFadePanel(String saveDir, String layout) {

    System.out.println("Using " + saveDir + " as directory for the images.");
    saveDirectory = saveDir;

    getImages();
    images_used = new ArrayList<Integer>();
    images_lastadded = new ArrayList<Integer>();
    images_nevershown = new ArrayList<Integer>();

    Vector devices = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
    Enumeration enumeration = devices.elements();
    System.out.println("- Available cameras -");
    ArrayList<String> names = new ArrayList<String>();
    while (enumeration.hasMoreElements()) {
      CaptureDeviceInfo cdi = (CaptureDeviceInfo) enumeration.nextElement();
      String name = cdi.getName();
      if (name.startsWith("vfw:")) {
        names.add(name);
        System.out.println(name);
      }
    }

    // String str1 = "vfw:Logitech USB Video Camera:0";
    // String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
    if (names.size() == 0) {
      JOptionPane.showMessageDialog(
          null,
          "Ingen kamera funnet. " + "Du må koble til et kamera for å kjøre programmet.",
          "Feil",
          JOptionPane.ERROR_MESSAGE);
      System.exit(0);
    } else if (names.size() > 1) {

      JOptionPane.showMessageDialog(
          null,
          "Fant mer enn 1 kamera. " + "Velger da:\n" + names.get(0),
          "Advarsel",
          JOptionPane.WARNING_MESSAGE);
    }

    String str2 = names.get(0);
    di = CaptureDeviceManager.getDevice(str2);
    ml = di.getLocator();

    try {
      player = Manager.createRealizedPlayer(ml);
      formatControl = (FormatControl) player.getControl("javax.media.control.FormatControl");

      /*
      Format[] formats = formatControl.getSupportedFormats();
      for (int i=0; i<formats.length; i++)
      	System.out.println(formats[i].toString());
      */

      player.start();
    } catch (javax.media.NoPlayerException e) {
      JOptionPane.showMessageDialog(
          null,
          "Klarer ikke å starte" + " programmet pga. feil med kamera. Sjekk at det er koblet til.",
          "IOException",
          JOptionPane.ERROR_MESSAGE);
      System.exit(0);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }

    /*
     * Layout
     *
     * Add
     * - comp
     * - imagepanels
     */

    if (layout.equals("1024v2")) {
      layout1024v2();
    } else if (layout.equals("1280")) {
      layout1280();
    } else {
      layout1024();
    }

    // Capture Window
    if (captureWindow) {
      cw = new JFrame("Capture from webcam");
      cw.setAlwaysOnTop(true);
      cw.setSize(sizeCaptureWindow_x, sizeCaptureWindow_y);
      cw.addKeyListener(new captureWindowKeyListner());
      cw.setUndecorated(true);

      // Add webcam
      if ((comp = player.getVisualComponent()) != null) {
        cw.add(comp);
      }

      // Add panel to window and set location of window
      cw.setLocation(cwLocation_x, cwLocation_y);
    }

    // Text window
    cwText = new rotatedText("");

    /*
     * Timer for update
     */
    Timer thread = new Timer();
    thread.schedule(new frameUpdateTask(), 0, (1000 / fps));
  }
Example #24
0
  public View(Model model) {

    this.model = model;
    model.makeMeObserver(this);

    frame = new JFrame();

    statusbar = new JLabel(" 0");
    board = new Board();
    frame.add(board);

    JMenuBar menubar = new JMenuBar();
    JMenu file = new JMenu("Settings");
    file.setMnemonic(KeyEvent.VK_F);

    JMenuItem eMenuItem = new JMenuItem("New game");
    eMenuItem.setToolTipText("Start a new game");
    eMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            menuEvent = -1;
            setChanged();
            notifyObservers();
            menuEvent = 0;
          }
        });
    file.add(eMenuItem);

    eMenuItem = new JMenuItem("Pause");
    eMenuItem.setMnemonic(KeyEvent.VK_P);
    eMenuItem.setToolTipText("Set pause");
    eMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            menuEvent = 1;
            setChanged();
            notifyObservers();
            menuEvent = 0;
          }
        });
    file.add(eMenuItem);

    JMenu imp = new JMenu("Set level");
    imp.setMnemonic(KeyEvent.VK_M);

    JMenuItem lvl1 = new JMenuItem("level 1");
    lvl1.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            menuEvent = 2;
            setChanged();
            notifyObservers();
            menuEvent = 0;
          }
        });

    JMenuItem lvl2 = new JMenuItem("level 2");
    lvl2.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            menuEvent = 3;
            setChanged();
            notifyObservers();
            menuEvent = 0;
          }
        });

    JMenuItem lvl3 = new JMenuItem("level 3");
    lvl3.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            menuEvent = 4;
            setChanged();
            notifyObservers();
            menuEvent = 0;
          }
        });

    JMenuItem lvl4 = new JMenuItem("level 4");
    lvl4.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            menuEvent = 5;
            setChanged();
            notifyObservers();
            menuEvent = 0;
          }
        });

    JMenuItem lvl5 = new JMenuItem("level 5");
    lvl5.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            menuEvent = 6;
            setChanged();
            notifyObservers();
            menuEvent = 0;
          }
        });

    imp.add(lvl1);
    imp.add(lvl2);
    imp.add(lvl3);
    imp.add(lvl4);
    imp.add(lvl5);

    file.add(imp);

    eMenuItem = new JMenuItem("Table of recorgs");
    eMenuItem.setToolTipText("Show table of records");
    eMenuItem.addActionListener(
        new ActionListener() {

          public void actionPerformed(ActionEvent event) {
            recordDialog ad;
            try {
              ad = new recordDialog();
              ad.setVisible(true);
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        });
    file.add(eMenuItem);

    eMenuItem = new JMenuItem("Exit");
    eMenuItem.setMnemonic(KeyEvent.VK_C);
    eMenuItem.setToolTipText("Exit application");
    eMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            System.exit(0);
          }
        });
    file.add(eMenuItem);

    menubar.add(file);
    frame.setJMenuBar(menubar);

    statusbar.setPreferredSize(new Dimension(-1, 22));
    statusbar.setBorder(LineBorder.createGrayLineBorder());
    frame.add(statusbar, BorderLayout.SOUTH);

    frame.setSize(200, 400);
    frame.setTitle("Tetris");
    frame.setLocationRelativeTo(null);
  }
Example #25
0
  /** ** Constructor. Sets up user interface and initializations */
  public Secondtry() {
    operators = true;
    doClear = false;

    frame = new JFrame("Calculator");
    frame.setLayout(new BorderLayout(10, 10));

    display = new JTextArea();
    display.setSize(245, 100);
    display.setFont(new Font("SansSerif", Font.BOLD, 28));
    display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

    // create the numeric buttons for calculator
    for (int i = 0; i < 10; i++) {
      jb[i] = new JButton("" + (i));
      jb[i].addActionListener(this);
      jb[i].setFont(new Font("SansSerif", Font.BOLD, 14));
    }
    // create the square root button
    root = new JButton("\u221A");
    root.addActionListener(this);
    root.setFont(new Font("SansSerif", Font.BOLD, 14));

    // create the clear button
    clear = new JButton("C");
    clear.addActionListener(this);
    clear.setFont(new Font("SansSerif", Font.BOLD, 14));

    // create the plus button
    plus = new JButton("\u002B");
    plus.addActionListener(this);
    plus.setFont(new Font("SansSerif", Font.BOLD, 14));

    // create the minus button
    minus = new JButton("\u002D");
    minus.addActionListener(this);
    minus.setFont(new Font("SansSerif", Font.BOLD, 14));

    // create the multiply button
    mult = new JButton("\u002A");
    mult.addActionListener(this);
    mult.setFont(new Font("SansSerif", Font.BOLD, 14));

    // create the division button
    div = new JButton("\u002F");
    div.addActionListener(this);
    div.setFont(new Font("SansSerif", Font.BOLD, 14));

    // create the equals button
    equals = new JButton("\u003D");
    equals.addActionListener(this);
    equals.setFont(new Font("SansSerif", Font.BOLD, 14));

    equals.setPreferredSize(new Dimension(50, 60));

    // create the point button
    point = new JButton("\u002E");
    point.addActionListener(this);
    point.setFont(new Font("SansSerif", Font.BOLD, 14));

    // button grid
    JPanel buttons = new JPanel(new GridLayout(5, 4, 4, 4));

    // add buttons to grid
    buttons.add(clear);
    buttons.add(root);
    buttons.add(div);
    buttons.add(mult);
    // add numeric buttons to grid
    for (int i = 7; i < 10; i++) buttons.add(jb[i]);
    buttons.add(minus);
    // add numeric buttons to grid
    for (int i = 4; i < 7; i++) buttons.add(jb[i]);
    buttons.add(plus);
    // add numeric buttons to grid
    for (int i = 1; i < 4; i++) buttons.add(jb[i]);
    buttons.add(equals);
    buttons.add(jb[0]);
    buttons.add(point);

    frame.add(display, BorderLayout.CENTER);
    frame.add(buttons, BorderLayout.SOUTH);

    frame.setSize(300, 400);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public static void main() {
    // Main
    frame = new JFrame("Java Playground");
    frame.setSize(640, 480);
    // Make sure the divider is properly resized
    frame.addComponentListener(
        new ComponentAdapter() {
          public void componentResized(ComponentEvent c) {
            splitter.setDividerLocation(.8);
          }
        });
    // Make sure the JVM is reset on close
    frame.addWindowListener(
        new WindowAdapter() {
          public void windowClosed(WindowEvent w) {
            new FrameAction().kill();
          }
        });

    // Setting up the keybinding
    // Ctrl+k or Cmd+k -> compile
    bind(KeyEvent.VK_K);

    // Ctrl+e or Cmd+e -> console
    bind(KeyEvent.VK_E);

    // Save, New file, Open file, Print.
    // Currently UNUSED until I figure out how normal java files and playground files will
    // interface.
    bind(KeyEvent.VK_S);
    bind(KeyEvent.VK_N);
    bind(KeyEvent.VK_O);
    bind(KeyEvent.VK_P);

    // Binds the keys to the action defined in the FrameAction class.
    frame.getRootPane().getActionMap().put("console", new FrameAction());

    // The main panel for typing code in.
    text = new JTextPane();
    textScroll = new JScrollPane(text);
    textScroll.setBorder(null);
    textScroll.setPreferredSize(new Dimension(640, 480));

    // Document with syntax highlighting. Currently unfinished.
    doc = text.getStyledDocument();
    doc.addDocumentListener(
        new DocumentListener() {
          public void changedUpdate(DocumentEvent d) {}

          public void insertUpdate(DocumentEvent d) {}

          public void removeUpdate(DocumentEvent d) {}
        });

    ((AbstractDocument) doc).setDocumentFilter(new NewLineFilter());

    // The output log; a combination compiler warning/error/runtime error/output log.
    outputText = new JTextPane();
    outputScroll = new JScrollPane(outputText);
    outputScroll.setBorder(null);

    // "Constant" for the error font
    error = new SimpleAttributeSet();
    error.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE);
    error.addAttribute(StyleConstants.Foreground, Color.RED);

    // "Constant" for the warning message font
    warning = new SimpleAttributeSet();
    warning.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE);
    warning.addAttribute(StyleConstants.Foreground, Color.PINK);

    // "Constant" for the debugger error font
    progErr = new SimpleAttributeSet();
    progErr.addAttribute(StyleConstants.Foreground, Color.BLUE);

    // Print streams to redirect System.out and System.err.
    out = new TextOutputStream(outputText, null);
    err = new TextOutputStream(outputText, error);
    System.setOut(new PrintStream(out));
    System.setErr(new PrintStream(err));

    // Sets up the output log
    outputText.setEditable(false);
    outputScroll.setVisible(true);

    // File input/output setup
    chooser = new JFileChooser();

    // Setting up miscellaneous stuff
    compiler = ToolProvider.getSystemJavaCompiler();
    JVMrunning = false;
    redirectErr = null;
    redirectOut = null;
    redirectIn = null;

    // Sets up the splitter pane and opens the program up
    splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT, textScroll, outputScroll);
    consoleDisplayed = false;
    splitter.remove(outputScroll); // Initially hides terminal until it is needed
    splitter.setOneTouchExpandable(true);
    frame.add(splitter);
    frame.setVisible(true);

    // Sets the divider to the proper one, for debugging
    // splitter.setDividerLocation(.8);
  }
Example #27
0
  public MancalaPanel(LetsPlayMancala game) {

    // ------------------------------------------------------------------------------
    // Import font "Belta Regular"
    // -----------------------------------------------------------------------------
    try {
      InputStream in = MancalaPanel.class.getResourceAsStream("belta-regular.ttf");
      Font font = Font.createFont(Font.TRUETYPE_FONT, in);
    } catch (Exception ex) {
      System.out.println("Font couldn't be loaded.");
    }

    // ----------------------------------------------------------------------------
    // Set background image
    // ----------------------------------------------------------------------------
    imageFile = "/Images/GameBackground.png";
    this.game = game;
    SMALL_PIT_COUNT = 12;

    setLayout(new BorderLayout());

    add(northWindowPanel(), BorderLayout.NORTH);
    add(westWindowPanel(), BorderLayout.WEST);
    add(makeBoardPanel(), BorderLayout.CENTER);
    add(eastWindowPanel(), BorderLayout.EAST);
    add(southWindowPanel(), BorderLayout.SOUTH);

    winners = new LinkedStack<String>();
    winnersLabel = new JLabel();

    resultFrame = new JFrame();
    boardResultPanel = new BkImagePanel("/Images/board2.png");
    resultNorth = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 50));
    resultNorth.setOpaque(false);
    resultCenter = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
    resultCenter.setOpaque(false);
    resultSouth = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
    resultSouth.setOpaque(false);

    playAgainBtn.setPreferredSize(new Dimension(240, 80));
    playAgainBtn.setBackground(new Color(135, 17, 76));
    playAgainBtn.setForeground(Color.white);
    playAgainBtn.setBorder(BorderFactory.createLineBorder(Color.white, 6));
    playAgainBtn.setFont(new Font("Belta Regular", Font.BOLD, 40));
    playAgainBtn.addActionListener(new ButtonListener());

    scoresBtn.setPreferredSize(new Dimension(340, 80));
    scoresBtn.setBorder(BorderFactory.createLineBorder(Color.white, 6));
    scoresBtn.addActionListener(new ButtonListener());

    quitBtn.setPreferredSize(new Dimension(150, 80));
    quitBtn.setBorder(BorderFactory.createLineBorder(Color.white, 6));
    quitBtn.addActionListener(new ButtonListener());

    result = new JLabel();
    result.setFont(new Font("Belta Regular", Font.BOLD, 40));
    result.setForeground(Color.white);
    result.setBackground(new Color(0, 158, 121));
    result.setBorder(BorderFactory.createLineBorder(Color.white, 6));
    result.setOpaque(true);
    result.setPreferredSize(new Dimension(380, 80));

    winnersLabel = new JLabel();
    winnersLabel.setFont(new Font("Belta Regular", Font.BOLD, 40));
    winnersLabel.setForeground(Color.white);
    winnersLabel.setPreferredSize(new Dimension(420, 200));

    boardResultPanel.setLayout(new BorderLayout(50, 50));
    boardResultPanel.setPreferredSize(new Dimension(800, 700));
    boardResultPanel.setBackground(Color.yellow);
    boardResultPanel.add(resultNorth, BorderLayout.NORTH);
    boardResultPanel.add(resultCenter, BorderLayout.CENTER);
    boardResultPanel.add(resultSouth, BorderLayout.SOUTH);

    resultCenter.add(winnersLabel);
    resultSouth.add(scoresBtn);
    resultSouth.add(playAgainBtn);
    resultSouth.add(quitBtn);

    resultFrame.add(boardResultPanel);
  }
Example #28
0
  /** Call with one or more OFF model paths * */
  public static void main(String args[]) {
    JFrame f = new JFrame("VzOFF " + args[0]);
    f.setLayout(new BorderLayout());

    VisWorld vw = new VisWorld();
    VisLayer vl = new VisLayer(vw);
    VisCanvas vc = new VisCanvas(vl);

    VzMesh.Style defaultMeshStyle = new VzMesh.Style(Color.cyan);

    ArrayList<VzOFF> models = new ArrayList<VzOFF>();

    for (int i = 0; i < args.length; i++) {
      if (args[i].endsWith(".off")) {
        try {
          models.add(new VzOFF(args[i], defaultMeshStyle));
          System.out.printf("Loaded: %20s (%5.2f%%)\n", args[i], i * 100.0 / args.length);
        } catch (IOException ex) {
          System.out.println("ex: " + ex);
        }
      } else {
        System.out.printf("Ignoring file with wrong suffix: " + args[i]);
      }
    }

    if (models.size() == 0) {
      System.out.println("No models specified\n");
      return;
    }

    int rows = (int) Math.sqrt(models.size());
    int cols = models.size() / rows + 1;

    //        VzGrid.addGrid(vw);

    VisWorld.Buffer vb = vw.getBuffer("models");
    for (int y = 0; y < rows; y++) {
      for (int x = 0; x < cols; x++) {
        int idx = y * cols + x;
        if (idx >= models.size()) break;

        VzOFF model = models.get(idx);

        double mx =
            Math.max(
                model.xyz_max[2] - model.xyz_min[2],
                Math.max(model.xyz_max[1] - model.xyz_min[1], model.xyz_max[0] - model.xyz_min[0]));

        vb.addBack(
            new VisChain(
                LinAlg.translate(x + .5, rows - (y + .5), 0),
                new VzRectangle(1, 1, new VzLines.Style(Color.white, 3)),
                new VisChain(
                    LinAlg.translate(0, .4, 0),
                    new VzText(
                        VzText.ANCHOR.CENTER,
                        String.format("<<sansserif-20,scale=.003>>%s", baseName(model.path)))),
                LinAlg.scale(.5, .5, .5),
                LinAlg.scale(1.0 / mx, 1.0 / mx, 1.0 / mx),
                LinAlg.translate(
                    -(model.xyz_max[0] + model.xyz_min[0]) / 2.0,
                    -(model.xyz_max[1] + model.xyz_min[1]) / 2.0,
                    -(model.xyz_max[2] + model.xyz_min[2]) / 2.0),
                model));
      }
    }

    vb.swap();

    vl.cameraManager.fit2D(new double[] {0, 0, 0}, new double[] {cols, rows, 0}, true);
    ((DefaultCameraManager) vl.cameraManager).interfaceMode = 3.0;

    f.add(vc);
    f.setSize(600, 400);
    f.setVisible(true);
  }
Example #29
0
  /** Constructor to set everything up */
  public TicTac() {
    // Set defaults before settings are changed via menus
    // (defaults are vs AI, play as X, with graphics on)
    multiPlayers = false;
    temp = false;
    currentPlayer = Symbol.X;
    ai = Symbol.O;
    difficulty = Difficulty.IMPOSSIBLE;

    frame = new JFrame("Tic Tac Toe");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    // Set preferred size so game fills window nicely
    this.setPreferredSize(new Dimension(cellSize * ROWS, cellSize * COLS));
    frame.add(this);

    // Load images
    try {
      sword = ImageIO.read(new File("swordsBlue.png"));
      saber = ImageIO.read(new File("saber2.png"));
      skull = ImageIO.read(new File("skull.png"));
      ring = ImageIO.read(new File("ring.png"));
      smiley = ImageIO.read(new File("smiley.png"));
      hydra = ImageIO.read(new File("hydra.png"));
      finalfantasy = ImageIO.read(new File("finalfantasy.jpg"));
      dragon = ImageIO.read(new File("dargon.jpg"));
      night = ImageIO.read(new File("night.jpg"));
    } catch (IOException e) {
      System.out.println("Could not open image files, turning images off!");
      useImages = false;
    }

    imageX = saber;
    imageO = ring;
    background = dragon;

    // Create menu bars.  Each one item will need a listener
    menuBar = new JMenuBar();
    JMenu menu = new JMenu("Mode");
    JMenu menu2 = new JMenu("Side");
    JMenu menu3 = new JMenu("Graphics");
    JMenu menu4 = new JMenu("Other");
    JMenu menu5 = new JMenu("Difficulty");
    JMenu xImageMenu = new JMenu("Image for X");
    JMenu oImageMenu = new JMenu("Image for O");
    JMenu backgroundMenu = new JMenu("Set Background");
    menuBar.add(menu);
    menuBar.add(menu2);
    menuBar.add(menu5);
    menuBar.add(menu3);
    menuBar.add(menu4);

    // Create checkbox menu items for choices
    final JCheckBoxMenuItem item = new JCheckBoxMenuItem("2 Player");
    final JCheckBoxMenuItem item2 = new JCheckBoxMenuItem("VS Computer");
    final JCheckBoxMenuItem item3 = new JCheckBoxMenuItem("Play as X");
    final JCheckBoxMenuItem item4 = new JCheckBoxMenuItem("Play as O");
    final JCheckBoxMenuItem item5 = new JCheckBoxMenuItem("On");
    final JCheckBoxMenuItem item6 = new JCheckBoxMenuItem("Off");
    JMenuItem item7 = new JMenuItem("Restart");
    JMenuItem item8 = new JMenuItem("Exit");
    final JCheckBoxMenuItem item9 = new JCheckBoxMenuItem("Easy");
    final JCheckBoxMenuItem item10 = new JCheckBoxMenuItem("Hard");
    final JCheckBoxMenuItem item11 = new JCheckBoxMenuItem("Impossible");
    final JCheckBoxMenuItem itemSword = new JCheckBoxMenuItem("Sword");
    final JCheckBoxMenuItem itemSaber = new JCheckBoxMenuItem("Sabers");
    final JCheckBoxMenuItem itemSkull = new JCheckBoxMenuItem("Skull");
    final JCheckBoxMenuItem itemRing = new JCheckBoxMenuItem("One Ring");
    final JCheckBoxMenuItem itemSmiley = new JCheckBoxMenuItem("Red Smiley");
    final JCheckBoxMenuItem itemHydra = new JCheckBoxMenuItem("Hydra");
    final JCheckBoxMenuItem itemDragon = new JCheckBoxMenuItem("Dragon");
    final JCheckBoxMenuItem itemFinalFantasy = new JCheckBoxMenuItem("Final Fantasy 7");
    final JCheckBoxMenuItem itemNight = new JCheckBoxMenuItem("Nighttime");

    // Set the initial checkboxes to true (for play vs ai, as X, with graphics on)
    item2.setSelected(true);
    item3.setSelected(true);
    item5.setSelected(true);
    item11.setSelected(true);
    itemSaber.setSelected(true);
    itemRing.setSelected(true);
    itemDragon.setSelected(true);

    // Play against friend
    item.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            item.setSelected(true);
            item2.setSelected(false);
            multiPlayers = true;
            repaint();
          }
        });
    menu.add(item);

    // Checkbox for Selecting to play against AI
    item2.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            item2.setSelected(true);
            item.setSelected(false);
            if (currentPlayer == Symbol.X) ai = Symbol.O;
            else ai = Symbol.X;
            item3.setSelected(true);
            item4.setSelected(false);
            multiPlayers = false;
          }
        });
    menu.add(item2);

    // Play as X
    item3.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            // use temp variable to move after assigning symbols
            if (item4.getState() && !multiPlayers) temp = true;
            item3.setSelected(true);
            item4.setSelected(false);
            currentPlayer = Symbol.X;
            ai = Symbol.O;
            if (temp) aiMove();
            repaint();
            temp = false;
          }
        });
    menu2.add(item3);

    // Play as O
    item4.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            if (item3.getState() && !multiPlayers) temp = true;
            item4.setSelected(true);
            item3.setSelected(false);
            currentPlayer = Symbol.O;
            ai = Symbol.X;
            if (temp) aiMove();
            repaint();
            temp = false;
          }
        });
    menu2.add(item4);

    // Turn Graphics on
    item5.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            item5.setSelected(true);
            item6.setSelected(false);
            useImages = true;
            repaint();
          }
        });
    menu3.add(item5);

    // Turn Graphics off
    item6.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            item5.setSelected(false);
            item6.setSelected(true);
            useImages = false;
            repaint();
          }
        });
    menu3.add(item6);
    menu3.addSeparator();
    menu3.add(xImageMenu);
    menu3.add(oImageMenu);
    menu3.add(backgroundMenu);

    // Choose Saber for X
    itemSaber.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemSword.setSelected(false);
            itemSaber.setSelected(true);
            itemSkull.setSelected(false);
            imageX = saber;
            repaint();
          }
        });
    xImageMenu.add(itemSaber);

    // Choose Sword for X
    itemSword.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemSword.setSelected(true);
            itemSaber.setSelected(false);
            itemSkull.setSelected(false);
            imageX = sword;
            repaint();
          }
        });
    xImageMenu.add(itemSword);

    // Choose Skull for X
    itemSkull.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemSword.setSelected(false);
            itemSaber.setSelected(false);
            itemSkull.setSelected(true);
            imageX = skull;
            repaint();
          }
        });
    xImageMenu.add(itemSkull);

    // Choose ring for O
    itemRing.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemRing.setSelected(true);
            itemSmiley.setSelected(false);
            itemHydra.setSelected(false);
            imageO = ring;
            repaint();
          }
        });
    oImageMenu.add(itemRing);

    // Choose red smiley for O
    itemSmiley.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemRing.setSelected(false);
            itemSmiley.setSelected(true);
            itemHydra.setSelected(false);
            imageO = smiley;
            repaint();
          }
        });
    oImageMenu.add(itemSmiley);

    // Choose hydra for O
    itemHydra.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemRing.setSelected(false);
            itemSmiley.setSelected(false);
            itemHydra.setSelected(true);
            imageO = hydra;
            repaint();
          }
        });
    oImageMenu.add(itemHydra);

    // Set dragon as background
    itemDragon.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemDragon.setSelected(true);
            itemFinalFantasy.setSelected(false);
            itemNight.setSelected(false);
            background = dragon;
            repaint();
          }
        });
    backgroundMenu.add(itemDragon);

    // Set final fantasy 7 as background
    itemFinalFantasy.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemDragon.setSelected(false);
            itemFinalFantasy.setSelected(true);
            itemNight.setSelected(false);
            background = finalfantasy;
            repaint();
          }
        });
    backgroundMenu.add(itemFinalFantasy);

    // Set night as background
    itemNight.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemDragon.setSelected(false);
            itemFinalFantasy.setSelected(false);
            itemNight.setSelected(true);
            background = night;
            repaint();
          }
        });
    backgroundMenu.add(itemNight);

    // Reset game
    item7.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            initialize();
          }
        });
    menu4.add(item7);

    // Exit game
    item8.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            System.exit(0);
          }
        });
    menu4.add(item8);

    // Difficulty easy
    item9.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            difficulty = Difficulty.EASY;
            item9.setSelected(true);
            item10.setSelected(false);
            item11.setSelected(false);
          }
        });
    menu5.add(item9);

    // Difficulty hard
    item10.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            difficulty = Difficulty.HARD;
            item10.setSelected(true);
            item9.setSelected(false);
            item11.setSelected(false);
          }
        });
    menu5.add(item10);

    // Difficulty impossible
    item11.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            difficulty = Difficulty.IMPOSSIBLE;
            item11.setSelected(true);
            item9.setSelected(false);
            item10.setSelected(false);
          }
        });
    menu5.add(item11);

    // Add Whole menu bar to frame
    frame.setJMenuBar(menuBar);

    // Create statusBar (updates will take place in paintComponent)
    statusBar = new JLabel("  ");
    statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 15));
    statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));
    // Use container variable to set layout and pack everything nicely
    Container cp = frame.getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(this, BorderLayout.CENTER);
    cp.add(statusBar, BorderLayout.SOUTH);
    frame.pack();

    board = new Symbol[ROWS][COLS];
    initialize();

    // Add the mouse listener.  Use MouseAdapter rather than implement it
    this.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            int currentCol = e.getX() / cellSize;
            int currentRow = e.getY() / cellSize;

            if (gameStatus == GameStatus.CONTINUE) {
              // If valid click, and spot is empty, make the move.  Then check
              // to see if game is won. If not, and facing AI, ai moves.
              // Otherwise switch X and O
              if (currentRow >= 0
                  && currentRow < ROWS
                  && currentCol >= 0
                  && currentCol < COLS
                  && board[currentRow][currentCol] == Symbol.EMPTY) {
                board[currentRow][currentCol] = currentPlayer;
                checkState(currentPlayer);

                if (multiPlayers) currentPlayer = (currentPlayer == Symbol.X) ? Symbol.O : Symbol.X;

                if (gameStatus == GameStatus.CONTINUE && !multiPlayers) aiMove();
              }
            } else {
              // Game is over, so re-initialize everything
              initialize();
            }
            repaint();
          }
        });
  }