コード例 #1
0
ファイル: Dlg_chat.java プロジェクト: yespickmeup/Synsoftech
 private void init_tbl_chats() {
   tbl_chats_ALM = new ArrayListModel();
   tbl_chats_M = new TblchatsModel(tbl_chats_ALM);
   tbl_chats.setModel(tbl_chats_M);
   tbl_chats.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
   int[] tbl_widths_chats = {58, 100, 0, 0, 0};
   for (int i = 0, n = tbl_widths_chats.length; i < n; i++) {
     if (i == 1) {
       continue;
     }
     TableWidthUtilities.setColumnWidth(tbl_chats, i, tbl_widths_chats[i]);
   }
   Dimension d = tbl_chats.getTableHeader().getPreferredSize();
   d.height = 0;
   tbl_chats.getTableHeader().setPreferredSize(d);
   tbl_chats.getTableHeader().setFont(new java.awt.Font("Arial", 0, 12));
   tbl_chats.setRowHeight(65);
   tbl_chats.setFont(new java.awt.Font("Arial", 0, 12));
   tbl_chats.getColumnModel().getColumn(0).setCellRenderer(new TableRender.set2());
   tbl_chats.getColumnModel().getColumn(1).setCellRenderer(new TableRender.set3());
   tbl_chats.getTableHeader().setResizingAllowed(true);
   tbl_chats.setShowGrid(false);
   tbl_chats.setShowHorizontalLines(true);
   tbl_chats.setShowVerticalLines(false);
   tbl_chats.getColumnModel().getColumn(1).setCellRenderer(new Html());
 }
コード例 #2
0
  private void init() {
    agents = new JComboBox(model);
    agents.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            stateChanged(event);
          }
        });
    agents.addActionListener(TextChangesListener.getInstance());
    ctm = new CreationTableModel();
    datatable = new JTable(ctm);
    datatable.setShowGrid(false);
    datatable.setEnabled(false);
    datatable.setTableHeader(null);
    datatable.setBorder(BorderFactory.createEmptyBorder(0, 3, 0, 3));
    JPanel apanel = new JPanel(new BorderLayout());
    apanel.add(new JLabel("Who took the photo: "), BorderLayout.WEST);
    apanel.add(agents, BorderLayout.CENTER);
    JPanel tablePanel = new JPanel(new BorderLayout());
    tablePanel.add(new JScrollPane(datatable), BorderLayout.CENTER);

    datatable.getColumnModel().getColumn(0).setMaxWidth(120);
    datatable.getColumnModel().getColumn(0).setMinWidth(80);

    datatable.addKeyListener(TextChangesListener.getInstance());

    this.add(
        ComponentFactory.createTitledPanel("Creator of the image:", apanel), BorderLayout.NORTH);
    this.add(
        ComponentFactory.createTitledPanel("Creation, EXIF & technical information:", tablePanel),
        BorderLayout.CENTER);
    this.add(new JSeparator(JSeparator.HORIZONTAL), BorderLayout.WEST);
  }
コード例 #3
0
  /**
   * Generates a JTable using results from Assessment data
   *
   * @param assessment - Assessment object
   */
  public void makeTable(Assessment assessment) {
    DefaultTableModel model =
        new DefaultTableModel() {
          @Override
          public boolean isCellEditable(int row, int column) {
            // Disables all cells from being editable
            return false;
          }
        };

    // Assigns column headings
    boolean isAnonymised = !assessment.getResults().get(0).getCandKey().contains("#");
    if (isAnonymised) {
      model.addColumn("Name");
      model.addColumn("Student Number");
    } else {
      model.addColumn("Anon Codes");
    }

    model.addColumn("#Ass");
    model.addColumn("Module Code");
    model.addColumn("Mark");
    model.addColumn("Grade");

    table = new JTable(model);
    table.setFont(new Font("Calibri", Font.BOLD, 14));

    // Sets column header look
    JTableHeader header = table.getTableHeader();
    header.setFont(new Font("Calibri", Font.BOLD, 16));
    header.setBackground(Color.black);
    header.setForeground(Color.WHITE);

    // Sets cell selection to single so only one cell is selected
    table.setCellSelectionEnabled(true);
    System.out.println("Making JTable");
    // Fetches first assessment and adds results data to model
    for (Result r : assessment.getResults()) {
      String name = r.getName();
      if (r.getName().equals("")) {
        name = r.getCandKey();
      }
      if (isAnonymised) {
        model.addRow(
            new Object[] {
              name, r.getCandKey(), r.getAssessment(), r.getModuleCode(), r.getMark(), r.getGrade()
            });
      } else {
        model.addRow(
            new Object[] {
              r.getCandKey(), r.getAssessment(), r.getModuleCode(), r.getMark(), r.getGrade()
            });
      }
    }

    table.setPreferredScrollableViewportSize(new Dimension(200, 300));
    table.setFillsViewportHeight(true);
    table.setShowGrid(false);
  }
コード例 #4
0
 /** Creates and displays the main GUI This GUI has the list and the main * buttons */
 public void showGUI() {
   final JScrollPane scrollPane = new JScrollPane();
   table =
       new JTable(
           new DefaultTableModel(
               new Object[][] {}, new String[] {"Username", "Password", "Pin", "Reward"}));
   AccountManager.loadAccounts();
   if (AccountManager.hasAccounts()) {
     for (Account account : AccountManager.getAccounts()) {
       ((DefaultTableModel) table.getModel())
           .addRow(
               new Object[] {
                 account.getUsername(), account.getReward(), account.getPin(), account.getReward()
               });
     }
   }
   final JToolBar bar = new JToolBar();
   bar.setMargin(new Insets(1, 1, 1, 1));
   bar.setFloatable(false);
   removeButton = new JButton("Remove");
   final JButton newButton = new JButton("Add");
   final JButton doneButton = new JButton("Save");
   table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   table.getSelectionModel().addListSelectionListener(new TableSelectionListener());
   table.setShowGrid(true);
   final TableColumnModel cm = table.getColumnModel();
   cm.getColumn(cm.getColumnIndex("Password")).setCellRenderer(new PasswordCellRenderer());
   cm.getColumn(cm.getColumnIndex("Password")).setCellEditor(new PasswordCellEditor());
   cm.getColumn(cm.getColumnIndex("Pin")).setCellRenderer(new PasswordCellRenderer());
   cm.getColumn(cm.getColumnIndex("Pin")).setCellEditor(new PasswordCellEditor());
   cm.getColumn(cm.getColumnIndex("Reward")).setCellEditor(new RandomRewardEditor());
   scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
   scrollPane.setViewportView(table);
   add(scrollPane, BorderLayout.CENTER);
   newButton.setFocusable(false);
   newButton.setToolTipText(newButton.getText());
   newButton.setText("+");
   bar.add(newButton);
   removeButton.setFocusable(false);
   removeButton.setToolTipText(removeButton.getText());
   removeButton.setText("-");
   bar.add(removeButton);
   bar.add(Box.createHorizontalGlue());
   doneButton.setToolTipText(doneButton.getText());
   bar.add(doneButton);
   newButton.addActionListener(this);
   removeButton.addActionListener(this);
   doneButton.addActionListener(this);
   add(bar, BorderLayout.SOUTH);
   final int row = table.getSelectedRow();
   removeButton.setEnabled(row >= 0 && row < table.getRowCount());
   table.clearSelection();
   doneButton.requestFocus();
   setPreferredSize(new Dimension(600, 300));
   pack();
   setLocationRelativeTo(getOwner());
   setResizable(false);
 }
コード例 #5
0
 public void createTable(int numRows) {
   hypListTableModel = new HypListTableModel(numRows);
   sorter = new TableSorter(hypListTableModel);
   hypsTable = new JTable(sorter);
   hypsTable.setShowGrid(true);
   hypsTable.setGridColor(Color.BLACK);
   sorter.setTableHeader(hypsTable.getTableHeader());
   hypsScrollPane = new JScrollPane(hypsTable);
   this.add(hypsScrollPane, BorderLayout.CENTER);
 }
コード例 #6
0
  /* Magic Happens */
  public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    /* If what we're displaying isn't an array of values we
    return the normal renderer*/

    if (value == null || (!value.getClass().isArray())) {
      return table
          .getDefaultRenderer(value.getClass())
          .getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    } else {
      final Object[][] passed = (Object[][]) value;
      /* We calculate the row's height to display data
       * THis is not complete and has some bugs that
       * will be analyzed in further articles */
      if (tbl_row_height == -1) {
        tbl_row_height = table.getRowHeight();
      }
      if (curr_height != tbl_row_height) {
        curr_height = (passed.length * passed.length + 20) + tbl_row_height;

        table.setRowHeight(row, curr_height);
      }

      /* We create the table that will hold the multi value
       *fields and that will be embedded in the main table */

      JTable tbl =
          new JTable(
              new AbstractTableModel() {

                private static final long serialVersionUID = 1L;

                public int getColumnCount() {
                  return 2;
                }

                public int getRowCount() {
                  return passed.length;
                }

                public Object getValueAt(int rowIndex, int columnIndex) {

                  return passed[rowIndex][columnIndex];
                }

                public boolean isCellEditable(int row, int col) {
                  return true;
                }
              });

      tbl.setShowGrid(false);

      return tbl;
    }
  }
コード例 #7
0
 public AttributesView() {
   super();
   _errorListeners = new LinkedList<ErrorOccurredListener>();
   _listeners = new ArrayList<AttributesViewListener>();
   setLayout(new BorderLayout());
   _table = new JTable();
   initEmptyTable();
   _table.setShowGrid(true);
   _table.setFillsViewportHeight(true);
   add(new JScrollPane(_table), BorderLayout.CENTER);
 }
コード例 #8
0
ファイル: JTableDemo.java プロジェクト: noikiy/Jtest
 public static void main(String[] args) {
   /*
   构造函数有很多下面先介绍几个:
   JTable()
   JTable(int numRows, int numColumns)
   JTable(Object[][] rowData, Object[] columnNames)
   */
   JTable example1 = new JTable(); // 看不到但存在
   JTable example2 = new JTable(8, 6);
   final Object[] columnNames = {
     "姓名", "性别", "家庭地址", // 列名最好用final修饰
     "电话号码", "生日", "工作", "收入", "婚姻状况", "恋爱状况"
   };
   Object[][] rowData = {
     {"ddd", "男", "江苏南京", "1378313210", "03/24/1985", "学生", "寄生中", "未婚", "没"},
     {"eee", "女", "江苏南京", "13645181705", "xx/xx/1985", "家教", "未知", "未婚", "好象没"},
     {"fff", "男", "江苏南京", "13585331486", "12/08/1985", "汽车推销员", "不确定", "未婚", "有"},
     {"ggg", "女", "江苏南京", "81513779", "xx/xx/1986", "宾馆服务员", "确定但未知", "未婚", "有"},
     {"hhh", "男", "江苏南京", "13651545936", "xx/xx/1985", "学生", "流放中", "未婚", "无数次分手后没有"}
   };
   JTable friends = new JTable(rowData, columnNames);
   friends.setPreferredScrollableViewportSize(new Dimension(600, 100)); // 设置表格的大小
   friends.setRowHeight(30); // 设置每行的高度为20
   friends.setRowHeight(0, 20); // 设置第1行的高度为15
   friends.setRowMargin(5); // 设置相邻两行单元格的距离
   friends.setRowSelectionAllowed(true); // 设置可否被选择.默认为false
   friends.setSelectionBackground(Color.white); // 设置所选择行的背景色
   friends.setSelectionForeground(Color.red); // 设置所选择行的前景色
   friends.setGridColor(Color.black); // 设置网格线的颜色
   friends.selectAll(); // 选择所有行
   friends.setRowSelectionInterval(0, 2); // 设置初始的选择行,这里是1到3行都处于选择状态
   friends.clearSelection(); // 取消选择
   friends.setDragEnabled(false); // 不懂这个
   friends.setShowGrid(false); // 是否显示网格线
   friends.setShowHorizontalLines(false); // 是否显示水平的网格线
   friends.setShowVerticalLines(true); // 是否显示垂直的网格线
   friends.setValueAt("tt", 0, 0); // 设置某个单元格的值,这个值是一个对象
   friends.doLayout();
   friends.setBackground(Color.lightGray);
   JScrollPane pane1 = new JScrollPane(example1); // JTable最好加在JScrollPane上
   JScrollPane pane2 = new JScrollPane(example2);
   JScrollPane pane3 = new JScrollPane(friends);
   JPanel panel = new JPanel(new GridLayout(0, 1));
   panel.setPreferredSize(new Dimension(600, 400));
   panel.setBackground(Color.black);
   panel.add(pane1);
   panel.add(pane2);
   panel.add(pane3);
   JFrame frame = new JFrame("JTableDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(panel);
   frame.pack();
   frame.show();
 }
コード例 #9
0
  public AppointmentGUI() {
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setBounds(100, 100, 500, 600); // window size
    setTitle("Appointment List"); // window title
    contentPane = new JPanel();
    contentPane.setBorder(
        new EmptyBorder(3, 6, 3, 6)); // distance the plane is from the edges of the window
    setContentPane(contentPane);
    contentPane.setLayout(new BorderLayout(0, 0));
    scrollPane = new JScrollPane();
    contentPane.add(scrollPane, BorderLayout.CENTER);

    table =
        new JTable(
            new DefaultTableModel(new Object[] {"Doctor's Name", "Location", "Date", "Time"}, 60)) {
          public boolean isCellEditable(
              int row,
              int column) { // prevents user from editing cells; there apparently is not a cleaner
            // way of doing this
            return false;
          }
        };
    table.setShowHorizontalLines(false);
    table.setShowVerticalLines(false);
    table.setShowGrid(false);
    table.getTableHeader().setReorderingAllowed(false); // prevent user from swapping columns
    table.getTableHeader().setResizingAllowed(false); // prevent user from resizing columns
    table.setSelectionMode(
        ListSelectionModel
            .SINGLE_INTERVAL_SELECTION); // prevent user from selecting multiple doctors
    table.setAutoCreateColumnsFromModel(
        false); // forgot why I have this here; it's probably important

    scrollPane.setViewportView(table); // lets table be scroll able

    btnPane = new JPanel();
    btnPane.setLayout(new GridLayout(0, 2, 0, 0));
    contentPane.add(btnPane, BorderLayout.SOUTH);

    btnViewAppointment = new JButton("View Appointment");
    btnPane.add(btnViewAppointment);

    btnCancelAppointment = new JButton("Cancel Appointment");
    btnPane.add(btnCancelAppointment);

    btnUpdateAppointment = new JButton("Update Appointment");
    btnPane.add(btnUpdateAppointment);

    btnGoBack = new JButton("Go Back");
    btnPane.add(btnGoBack);
  }
コード例 #10
0
ファイル: ClauseOrder.java プロジェクト: jdhuayta/libertya
  ClauseOrder(QueryClauses clauses) {
    super(new GridLayout(1, 2));

    this.clauses = clauses;

    DefaultPanel pnl;
    JToolBar bar;
    JScrollPane scroll;

    DefaultTableModel model =
        new DefaultTableModel(0, 2) {
          public boolean isCellEditable(int row, int column) {
            return column == 0;
          }
        };

    this.add(pnl = new DefaultPanel());
    pnl.setCenterComponent(
        scroll = new JScrollPane(availableExpressions = new JList(new DefaultListModel())));
    pnl.setEastComponent(bar = new JToolBar(JToolBar.VERTICAL));
    bar.add(createButton("put >", PUT));
    bar.add(createButton("< push", PUSH));
    bar.setFloatable(false);

    this.add(pnl = new DefaultPanel());
    pnl.setCenterComponent(scroll = new JScrollPane(selectedExpressions = new JTable(model)));
    pnl.setEastComponent(bar = new JToolBar(JToolBar.VERTICAL));
    bar.add(createButton("up", UP));
    bar.add(createButton("down", DOWN));
    bar.setFloatable(false);
    scroll.getViewport().setBackground(selectedExpressions.getBackground());

    TableColumn tableColumn = selectedExpressions.getColumn(selectedExpressions.getColumnName(0));
    tableColumn.setCellEditor(new CheckBoxCellRenderer());
    tableColumn.setCellRenderer(new CheckBoxCellRenderer());
    tableColumn.setPreferredWidth(15);
    tableColumn.setMaxWidth(15);
    tableColumn.setResizable(false);

    selectedExpressions.setIntercellSpacing(new Dimension(0, 0));
    selectedExpressions.setShowGrid(false);
    selectedExpressions.setColumnSelectionAllowed(false);
    selectedExpressions.setDefaultRenderer(Boolean.class, new CheckBoxCellRenderer());
    selectedExpressions.getTableHeader().setPreferredSize(new Dimension(0, 0));
    selectedExpressions.getTableHeader().setVisible(false);
  }
コード例 #11
0
  /**
   * Constructs a Panel with a line-number, breakpoint, source-text
   *
   * @param dataComm the datacomm object for interaction with the ToolBus
   * @param scriptName the name of the script that is used by the ToolBus
   * @param source the source of an toolbus file
   */
  public SourceFilePanel(DataComm dataComm, String scriptName, String source) {
    super();

    m_dataComm = dataComm;
    setLayout(new BorderLayout());
    m_scriptName = scriptName;
    m_sourceModel = new SourceFileTableModel(source);
    m_sourceCode = new JTable(m_sourceModel);
    m_sourceCode.setSelectionBackground(SELECTED_ROW_COLOR);
    m_sourceCode.setSelectionForeground(Color.BLACK);
    m_sourceCode.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    // to set the background color back to default
    m_sourceCode.addMouseListener(
        new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            if (e.getClickCount() == MouseEvent.BUTTON1) {
              m_sourceCode.setSelectionBackground(SELECTED_ROW_COLOR);
            }
          }
        });

    m_sourceCode.getModel().addTableModelListener(this);
    m_sourceCode.setShowGrid(false);
    m_sourceCode.setColumnSelectionAllowed(false);
    m_sourceCode.setRowSelectionAllowed(true);

    m_sourceCode.getColumnModel().getColumn(0).setCellRenderer(new CheckBoxCellRenderer());
    m_sourceCode.getColumnModel().getColumn(0).setCellEditor(new CheckBoxCellRenderer());

    TableColumn firstColumn = m_sourceCode.getColumnModel().getColumn(FIRST_COLUMN_INDEX);
    firstColumn.setMaxWidth(FIRST_COLUMN_WIDTH);

    TableColumn secondColumn = m_sourceCode.getColumnModel().getColumn(SECOND_COLUMN_INDEX);
    DefaultTableCellRenderer tcrColumn = new DefaultTableCellRenderer();
    tcrColumn.setHorizontalAlignment(SwingConstants.LEFT);
    secondColumn.setCellRenderer(tcrColumn);
    secondColumn.setMaxWidth(SECOND_COLUMN_WIDTH);

    JScrollPane sourceScrollPane = new JScrollPane(m_sourceCode);
    sourceScrollPane.getViewport().setBackground(Color.WHITE);
    add(sourceScrollPane, BorderLayout.CENTER);
    setVisible(true);
  }
コード例 #12
0
  public LinearRegressionPanel(Application app, StatDialog statDialog) {

    this.app = app;
    kernel = app.getKernel();
    this.statDialog = statDialog;

    this.setOpaque(true);
    this.setBackground(Color.WHITE);
    this.setLayout(new BorderLayout());

    // north panel with regression equation
    Box northPanel = Box.createVerticalBox();
    northPanel.add(new JLabel(" ---- regresion equation ----"));
    northPanel.add(new JLabel(" ----------------------------"));

    // south panel with additional statistics
    Box southPanel = Box.createVerticalBox();
    southPanel.add(new JLabel(" ---- regresion equation ----"));
    southPanel.add(new JLabel(" ----------------------------"));

    // set up table
    model = new DefaultTableModel();
    headerModel = new DefaultListModel();
    JTable table = new JTable(model);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setGridColor(GeoGebraColorConstants.TABLE_GRID_COLOR);
    table.setShowGrid(true);

    // table row header
    JList rowHeader = new JList(headerModel);
    rowHeader.setFixedCellWidth(50);
    rowHeader.setFixedCellHeight(table.getRowHeight() + table.getRowMargin());
    rowHeader.setCellRenderer(new RowHeaderRenderer(table));

    // add table to scroll pane
    JScrollPane scroll = new JScrollPane(table);
    scroll.setRowHeaderView(rowHeader);

    this.add(scroll, BorderLayout.CENTER);
  }
コード例 #13
0
  private JComponent getPersonnelTable() {
    personnelTable = new JTable(personnelModel);
    personnelTable.setCellSelectionEnabled(false);
    personnelTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

    for (int i = PersonnelTableModel.N_COL - 1; i >= 0; --i) {
      TableColumn column = personnelTable.getColumnModel().getColumn(i);
      if (personnelColumns.contains(Integer.valueOf(i))) {
        column.setPreferredWidth(personnelModel.getColumnWidth(i));
        column.setCellRenderer(new CellRenderer());
      } else {
        personnelTable.removeColumn(column);
      }
    }
    personnelTable.setIntercellSpacing(new Dimension(1, 0));
    personnelTable.setShowGrid(false);
    personnelTable.setRowSorter(personnelSorter);

    JScrollPane pane = new JScrollPane(personnelTable);
    pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    return pane;
  }
コード例 #14
0
  /**
   * Renders the JTable of the students being avoided given a student.
   *
   * @param student Student to render the avoiding list of
   * @return JTable of the students being avoided.
   */
  public JTable makeTable(Student student) {
    String[] columns = {"Student ID", "First Name", "Last Name"};
    ArrayList<Student> avoidingList = student.getAvoiding();
    String[][] names = new String[avoidingList.size()][];

    for (int i = 0; i < avoidingList.size(); i++) {
      Student avoiding = avoidingList.get(i);
      for (Student j : window.currentClass.getStudents()) {
        if (j.getStudentID() == avoiding.getStudentID()) {
          avoiding = j;
        }
      }
      names[i] =
          new String[] {
            Integer.toString(avoiding.getStudentID()),
            avoiding.getFirstName(),
            avoiding.getLastName()
          };
    }

    JTable avoidingTable = new JTable(new CustomTableModel(names, columns));

    /*
     * Shrinking size of table
     */
    avoidingTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    for (int i = 0; i < 3; i++) {
      avoidingTable.getColumnModel().getColumn(i).setMaxWidth(250);
    }

    /*
     * Appearance Options
     */
    avoidingTable.setDefaultRenderer(Object.class, new CustomTableRenderer());
    avoidingTable.setShowGrid(false);

    return avoidingTable;
  }
コード例 #15
0
ファイル: UI.java プロジェクト: bkdwei/DBViewer
  // 设置UI元素的属性
  public void compose() {
    frame.setSize(954, 750);
    frame.setLocation(200, 50);
    frame.setResizable(true);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    // 工具栏
    toolBar.add(btDeleteTableData);
    toolBar.add(tfSqlCommand);
    toolBar.add(btExecuteSql);
    toolBar.add(btAbout);
    frame.add("North", toolBar);

    // 数据管理层

    westJPanel.setLayout(new BorderLayout());
    westJPanel.add("North", search);
    westJPanel.add("Center", awtList);
    frame.add("West", westJPanel);

    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setShowGrid(true);
    table.setAutoscrolls(true);
    table.setDragEnabled(true);
    table.setCellSelectionEnabled(true);
    table.setSelectionBackground(new Color(233, 223, 233));
    scrollPane.setViewportView(table);

    frame.add("Center", scrollPane);

    statusBar.setAlignmentX(JLabel.RIGHT);
    frame.add("South", statusBar);

    frame.setVisible(true);
  }
コード例 #16
0
  /**
   * Create the panel
   *
   * @throws Exception if error occures during creation of the panel
   */
  private void init() throws Exception {

    // create objects to display
    this.setLayout(new BorderLayout());
    model = new MyTableModel();
    table = new JTable(model);
    table.setShowGrid(true);
    table.setAutoscrolls(true);
    table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollpane = new JScrollPane(table);
    table.setPreferredScrollableViewportSize(new Dimension(800, 200));
    table.setFont(GuiFactory.defaultTableFont);
    table.getTableHeader().setFont(GuiFactory.defaultTableHeaderFont);

    table.addMouseListener(
        new MouseAdapter() {
          public void mouseClicked(MouseEvent event) {
            if (event.getClickCount() == 2) {
              try {
                ExplorerUtil.getSyncAdminController()
                    .getPrincipalsController()
                    .startLastTimestampsProcess(getSelectedPrincipal());

              } catch (AdminException e) {
                String description = Bundle.getMessage(Bundle.EDITING);
                Log.error(
                    MessageFormat.format(
                        Bundle.getMessage(Bundle.ERROR_HANDLING_PRINCIPAL),
                        new String[] {description}),
                    e);
              }
            }
          }
        });

    this.add(scrollpane, BorderLayout.CENTER);
  }
コード例 #17
0
  public void initTableVente() {
    // Desactivation de l'edition d'un cellule lors d'un double click
    tableVente =
        new JTable() {
          public boolean isCellEditable(int row, int column) {
            boolean temp = false;
            if (column == 4) {
              temp = true;
            }

            return temp;
          }
        };
    tableVente.setName("tableVente");
    tableVente.setBackground(new Color(201, 241, 253));
    tableVente.setShowGrid(false);
    MAJTableVente();

    // ajout d'une scrollbare au tableau
    JScrollPane scrollPane = new JScrollPane(tableVente);
    scrollPane.getViewport().setBackground(new Color(201, 241, 253));

    paneVente.add(scrollPane, BorderLayout.CENTER);
  }
コード例 #18
0
  /** Initialize the contents of the frame. */
  private void initialize() {
    JFrame frmEditdeleteAuciton = new JFrame();
    frmEditdeleteAuciton.setResizable(false);
    frmEditdeleteAuciton.setTitle("Edit/Delete Auciton");
    frmEditdeleteAuciton.setBounds(100, 100, 712, 467);
    frmEditdeleteAuciton.setLocationRelativeTo(null);
    frmEditdeleteAuciton.getContentPane().setLayout(null);
    frmEditdeleteAuciton.setLocationRelativeTo(null);
    frmEditdeleteAuciton.setVisible(true);

    JButton btnSearch = new JButton("SHOW AUCTIONS CREATED BY YOU");
    btnSearch.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent arg0) {
            AuctionMethods.showmyauction(table);
          }
        });
    btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 15));
    btnSearch.setBounds(170, 11, 346, 33);
    frmEditdeleteAuciton.getContentPane().add(btnSearch);

    textField_1 = new JTextField();
    textField_1.setColumns(10);
    textField_1.setBounds(164, 262, 166, 30);
    frmEditdeleteAuciton.getContentPane().add(textField_1);

    textField_2 = new JTextField();
    textField_2.setColumns(10);
    textField_2.setBounds(164, 302, 166, 30);
    frmEditdeleteAuciton.getContentPane().add(textField_2);

    textField_3 = new JTextField();
    textField_3.setColumns(10);
    textField_3.setBounds(164, 341, 166, 30);
    frmEditdeleteAuciton.getContentPane().add(textField_3);

    JLabel lblNewCategory = new JLabel("New Category");
    lblNewCategory.setFont(new Font("Tahoma", Font.PLAIN, 15));
    lblNewCategory.setBounds(10, 341, 144, 30);
    frmEditdeleteAuciton.getContentPane().add(lblNewCategory);

    JLabel lblNewStartingBid = new JLabel("New Starting Bid");
    lblNewStartingBid.setFont(new Font("Tahoma", Font.PLAIN, 15));
    lblNewStartingBid.setBounds(10, 302, 144, 28);
    frmEditdeleteAuciton.getContentPane().add(lblNewStartingBid);

    JLabel lblNewAuctionName = new JLabel("New Auction Name");
    lblNewAuctionName.setFont(new Font("Tahoma", Font.PLAIN, 15));
    lblNewAuctionName.setBounds(10, 262, 144, 29);
    frmEditdeleteAuciton.getContentPane().add(lblNewAuctionName);

    table = new JTable();
    table.setShowVerticalLines(false);
    table.setShowHorizontalLines(false);
    table.setShowGrid(false);
    table.setRowSelectionAllowed(false);
    table.setFont(new Font("Tahoma", Font.PLAIN, 12));
    table.setEnabled(false);
    table.setBounds(119, 76, 450, 82);
    frmEditdeleteAuciton.getContentPane().add(table);

    JTextPane txtpnAuctionName = new JTextPane();
    txtpnAuctionName.setText("Auction Name");
    txtpnAuctionName.setForeground(Color.WHITE);
    txtpnAuctionName.setFont(new Font("Tahoma", Font.PLAIN, 13));
    txtpnAuctionName.setEditable(false);
    txtpnAuctionName.setBackground(Color.DARK_GRAY);
    txtpnAuctionName.setBounds(119, 55, 150, 19);
    frmEditdeleteAuciton.getContentPane().add(txtpnAuctionName);

    JTextPane txtpnCategory = new JTextPane();
    txtpnCategory.setText("Category");
    txtpnCategory.setForeground(Color.WHITE);
    txtpnCategory.setFont(new Font("Tahoma", Font.PLAIN, 13));
    txtpnCategory.setEditable(false);
    txtpnCategory.setBackground(Color.DARK_GRAY);
    txtpnCategory.setBounds(269, 55, 150, 19);
    frmEditdeleteAuciton.getContentPane().add(txtpnCategory);

    JTextPane txtpnStaringBid = new JTextPane();
    txtpnStaringBid.setText("Staring Bid");
    txtpnStaringBid.setForeground(Color.WHITE);
    txtpnStaringBid.setFont(new Font("Tahoma", Font.PLAIN, 13));
    txtpnStaringBid.setEditable(false);
    txtpnStaringBid.setBackground(Color.DARK_GRAY);
    txtpnStaringBid.setBounds(419, 55, 150, 19);
    frmEditdeleteAuciton.getContentPane().add(txtpnStaringBid);

    JButton btnEdit = new JButton("EDIT");
    btnEdit.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String name = textField.getText();
            String newname = textField_1.getText();
            String bid = textField_2.getText();
            String category = textField_3.getText();
            AuctionMethods.editauction(name, newname, bid, category);

            frmEditdeleteAuciton.dispose();
          }
        });
    btnEdit.setFont(new Font("Tahoma", Font.PLAIN, 15));
    btnEdit.setBounds(93, 382, 137, 33);
    frmEditdeleteAuciton.getContentPane().add(btnEdit);

    JSeparator separator = new JSeparator();
    separator.setOrientation(SwingConstants.VERTICAL);
    separator.setBounds(340, 262, 38, 153);
    frmEditdeleteAuciton.getContentPane().add(separator);

    JLabel lblAreYouSure = new JLabel("Are you sure you want to delete the Auction?");
    lblAreYouSure.setHorizontalAlignment(SwingConstants.CENTER);
    lblAreYouSure.setFont(new Font("Tahoma", Font.PLAIN, 15));
    lblAreYouSure.setBounds(340, 262, 346, 33);
    frmEditdeleteAuciton.getContentPane().add(lblAreYouSure);

    JLabel label = new JLabel("This option CANNOT be undone!!");
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
    label.setBounds(358, 322, 328, 31);
    frmEditdeleteAuciton.getContentPane().add(label);

    JButton button = new JButton("YES");
    button.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String name = textField.getText();
            AuctionMethods.deleteauction(name);

            textField.setText(null);
          }
        });
    button.setFont(new Font("Tahoma", Font.BOLD, 20));
    button.setBounds(358, 364, 127, 51);
    frmEditdeleteAuciton.getContentPane().add(button);

    JButton button_1 = new JButton("NO");
    button_1.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            textField.setText(null);
          }
        });
    button_1.setFont(new Font("Tahoma", Font.BOLD, 20));
    button_1.setBounds(559, 364, 127, 51);
    frmEditdeleteAuciton.getContentPane().add(button_1);

    JSeparator separator_1 = new JSeparator();
    separator_1.setBounds(55, 169, 578, 19);
    frmEditdeleteAuciton.getContentPane().add(separator_1);

    JLabel lblEnterNameOf_1 = new JLabel("Enter name of Auction you want to edit or delete");
    lblEnterNameOf_1.setHorizontalAlignment(SwingConstants.CENTER);
    lblEnterNameOf_1.setFont(new Font("Tahoma", Font.PLAIN, 15));
    lblEnterNameOf_1.setBounds(91, 189, 328, 33);
    frmEditdeleteAuciton.getContentPane().add(lblEnterNameOf_1);

    textField = new JTextField();
    textField.setColumns(10);
    textField.setBounds(432, 189, 174, 33);
    frmEditdeleteAuciton.getContentPane().add(textField);
  }
コード例 #19
0
ファイル: ParametersPanel.java プロジェクト: sprig/MPS
  private void initPanel() {
    this.setLayout(new GridBagLayout());

    final JTable parametersTable = new JBTable(this.myTableModel);

    JPanel buttonsPanel = new JPanel(new GridBagLayout());
    final JButton upButton =
        this.createParametersRowMoveButton(parametersTable, "Move up", -1, 0, buttonsPanel);
    final JButton downButton =
        this.createParametersRowMoveButton(parametersTable, "Move down", 1, 1, buttonsPanel);

    parametersTable.setShowGrid(false);
    parametersTable.setCellSelectionEnabled(false);
    parametersTable.setRowSelectionAllowed(true);
    parametersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    parametersTable.setIntercellSpacing(new Dimension(0, 0));
    parametersTable.setTableHeader(null);
    parametersTable
        .getSelectionModel()
        .addListSelectionListener(
            new ListSelectionListener() {
              @Override
              public void valueChanged(ListSelectionEvent p0) {
                int s = parametersTable.getSelectedRow();
                upButton.setEnabled(s > 0);
                downButton.setEnabled(
                    s != 0
                        && s
                            < ListSequence.fromList(ParametersPanel.this.myModel.getParameters())
                                    .count()
                                - 1);
              }
            });
    this.fitTableColumns(parametersTable);
    parametersTable.getColumnModel().getColumn(1).setCellEditor(this.createCellEditor());
    parametersTable
        .getColumnModel()
        .getColumn(0)
        .setMaxWidth(new JCheckBox().getPreferredSize().width);
    this.myTableModel.addTableModelListener(
        new TableModelListener() {
          @Override
          public void tableChanged(TableModelEvent p0) {
            ParametersPanel.this.fitTableColumns(parametersTable);
          }
        });
    parametersTable.setPreferredScrollableViewportSize(
        new Dimension(
            parametersTable.getPreferredScrollableViewportSize().width,
            parametersTable.getRowHeight() * 7));
    JScrollPane scrollPane =
        new JScrollPane(
            parametersTable,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    GridBagConstraints c =
        new GridBagConstraints(
            0,
            0,
            1,
            1,
            1,
            1,
            GridBagConstraints.NORTHWEST,
            GridBagConstraints.BOTH,
            new Insets(0, 0, 0, 0),
            0,
            0);

    this.add(scrollPane, c);

    c.gridx = 1;
    c.weightx = 0;
    c.fill = GridBagConstraints.NONE;
    this.add(buttonsPanel, c);
  }
コード例 #20
0
ファイル: MainFrame.java プロジェクト: gaurav/taxref
  /**
   * 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);
                  }
                }
              }
            }));
  }
コード例 #21
0
  public BookmarkSheet(Container c) {

    // set the layout of the data sheet
    c.setLayout(new BorderLayout());
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    /** Create a toolbar. */
    JMenuBar toolbar = new JMenuBar();
    toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.X_AXIS));
    c.add(toolbar, BorderLayout.NORTH);

    JButton previousButton = new JButton();
    previousButton.setIcon(
        SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.UP));
    previousButton.setToolTipText("Go to previous bookmark [ Ctrl+( ]");
    previousButton.putClientProperty("JButton.buttonType", "segmentedRoundRect");
    previousButton.putClientProperty("JButton.segmentPosition", "first");
    previousButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            goToPreviousBookmark();
          }
        });
    toolbar.add(previousButton);

    JButton nextButton = new JButton();
    nextButton.setIcon(
        SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.DOWN));
    nextButton.setToolTipText("Go to next bookmark [ Ctrl+) ]");
    nextButton.putClientProperty("JButton.buttonType", "segmentedRoundRect");
    nextButton.putClientProperty("JButton.segmentPosition", "last");
    nextButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            goToNextBookmark();
          }
        });
    toolbar.add(nextButton);

    JButton goButton = new JButton("Go");
    goButton.setToolTipText("Go to selected bookmark");
    goButton.putClientProperty("JButton.buttonType", "segmentedRoundRect");
    goButton.putClientProperty("JButton.segmentPosition", "only");
    goButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            goToSelectedBookmark();
          }
        });
    toolbar.add(goButton);

    toolbar.add(Box.createGlue());

    addButton = new JButton();
    addButton.setIcon(
        SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.BKMK_ADD));
    addButton.setToolTipText("Add bookmark for current range");
    addButton.putClientProperty("JButton.buttonType", "segmentedRoundRect");
    addButton.putClientProperty("JButton.segmentPosition", "first");
    addButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            BookmarkController fc = BookmarkController.getInstance();
            fc.addCurrentRangeToBookmarks();
          }
        });
    toolbar.add(addButton);

    JButton deleteButton = new JButton();
    deleteButton.setIcon(
        SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.BKMK_RM));
    deleteButton.setToolTipText("Delete selected bookmarks");
    deleteButton.putClientProperty("JButton.buttonType", "segmentedRoundRect");
    deleteButton.putClientProperty("JButton.segmentPosition", "last");
    deleteButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            BookmarkController fc = BookmarkController.getInstance();
            int[] selectedRows = table.getSelectedRows();
            Arrays.sort(selectedRows);
            boolean delete = false;

            if (selectedRows.length > 0 && confirmDelete) {
              Object[] options = {"Yes", "No", "Yes, don't ask again"};
              JLabel message =
                  new JLabel(
                      "Are you sure you want to delete " + selectedRows.length + " item(s)?");
              message.setPreferredSize(new Dimension(300, 20));
              int confirmDeleteDialog =
                  JOptionPane.showOptionDialog(
                      DialogUtils.getMainWindow(),
                      message,
                      "Confirm Delete",
                      JOptionPane.YES_NO_CANCEL_OPTION,
                      JOptionPane.QUESTION_MESSAGE,
                      null,
                      options,
                      options[0]);

              if (confirmDeleteDialog == 0) {
                delete = true;
              } else if (confirmDeleteDialog == 2) {
                delete = true;
                confirmDelete = false;
              }
            } else if (selectedRows.length > 0 && !confirmDelete) {
              delete = true;
            }

            if (delete) {
              for (int i = selectedRows.length - 1; i >= 0; i--) {
                fc.removeBookmark(selectedRows[i]);
              }
            }
          }
        });
    toolbar.add(deleteButton);

    toolbar.add(Box.createGlue());

    JButton loadButton = new JButton();
    loadButton.setIcon(
        SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.OPEN));
    loadButton.setToolTipText("Load bookmarks from file");
    loadButton.putClientProperty("JButton.buttonType", "segmentedRoundRect");
    loadButton.putClientProperty("JButton.segmentPosition", "first");
    loadButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            loadBookmarks(table);
          }
        });
    toolbar.add(loadButton);

    JButton saveButton = new JButton();
    saveButton.setIcon(
        SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.SAVE));
    saveButton.setToolTipText("Save bookmarks to file");
    saveButton.putClientProperty("JButton.buttonType", "segmentedRoundRect");
    saveButton.putClientProperty("JButton.segmentPosition", "last");
    saveButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            saveBookmarks(table);
          }
        });
    toolbar.add(saveButton);

    // create a table (the most important component)
    table = new JTable(new BookmarksTableModel());
    table.setAutoCreateRowSorter(true);
    table.setFillsViewportHeight(true);
    table.setShowGrid(true);
    table.setGridColor(Color.gray);
    // table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

    // add the table and its header to the subpanel
    c.add(table.getTableHeader());

    add(table);

    final JScrollPane sp =
        new JScrollPane(
            table,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    sp.setWheelScrollingEnabled(false);
    sp.addMouseWheelListener(
        new MouseWheelListener() {
          @Override
          public void mouseWheelMoved(MouseWheelEvent e) {
            sp.getVerticalScrollBar()
                .setValue(sp.getVerticalScrollBar().getValue() + e.getUnitsToScroll() * 2);
          }
        });

    c.add(sp);

    // add glue to fill the remaining space
    add(Box.createGlue());
  }
  public TableViewComponent() {
    super();

    setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(12, 12, 12, 12),
            BorderFactory.createLoweredBevelBorder()));

    table = new JTable();

    table.setRowSelectionAllowed(false);
    table.setColumnSelectionAllowed(false);
    table.setCellSelectionEnabled(true);
    table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionListener selectionListener =
        new ListSelectionListener() {
          @Override
          public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
              return;
            }

            ListSelectionModel rowSelections = table.getSelectionModel();
            ListSelectionModel columnSelections = table.getColumnModel().getSelectionModel();
            if (rowSelections.isSelectionEmpty() || columnSelections.isSelectionEmpty()) {
              // no new selection -> nothing has changed
              return;
            }

            int rowIndex = rowSelections.getLeadSelectionIndex();
            int columnIndex = columnSelections.getLeadSelectionIndex();
            int modelRowIndex = table.convertRowIndexToModel(rowIndex);
            int modelColumnIndex = table.convertColumnIndexToModel(columnIndex);

            if (selectedNode != null) {
              selectedNode.setHereTooSelected(false);
            }

            final NodeWrapper newSelection =
                (NodeWrapper) table.getModel().getValueAt(modelRowIndex, modelColumnIndex);
            newSelection.setHereTooSelected(true);

            selectedNode = newSelection;

            table.invalidate();
            SwingUtilities.invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    table.repaint();
                  }
                });
          }
        };
    table.getSelectionModel().addListSelectionListener(selectionListener);
    table.getColumnModel().getSelectionModel().addListSelectionListener(selectionListener);

    table.setAutoCreateRowSorter(false);

    table.setFillsViewportHeight(true);

    table.setGridColor(COLOR_GRID_LINES);
    table.setShowGrid(false);
    table.setShowHorizontalLines(true);

    // 0px between cells in the same row; 1px between rows
    table.setIntercellSpacing(new Dimension(0, 1));

    FontMetrics metrics = table.getFontMetrics(table.getFont());
    int rowHeight = 2 * metrics.getMaxAscent() + 2 * metrics.getMaxDescent() + metrics.getLeading();
    table.setRowHeight(rowHeight);

    setViewportView(table);

    // context menus + double-click for chain nav
    table.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() != 2) {
              return;
            }
            NodeWrapper node = getNodeWrapperAtPoint(e);
            if (node != null) {
              fireNodeSelected(node);
            }
          }

          @Override
          public void mousePressed(MouseEvent e) {
            handlePopup(e);
          }

          @Override
          public void mouseReleased(MouseEvent e) {
            handlePopup(e);
          }

          private void handlePopup(MouseEvent e) {
            if (!e.isPopupTrigger()) {
              return;
            }
            NodeWrapper node = getNodeWrapperAtPoint(e);
            if (node != null) {
              popup.setNodeWrapper(node);
              popup.show(table, e.getX(), e.getY());
            }
          }

          private NodeWrapper getNodeWrapperAtPoint(MouseEvent e) {
            int viewColumn = table.columnAtPoint(e.getPoint());
            int viewRow = table.rowAtPoint(e.getPoint());
            if (viewColumn == -1 || viewRow == -1) {
              // this means that we have an invalid point
              return null;
            }
            NodeWrapper node = (NodeWrapper) table.getValueAt(viewRow, viewColumn);
            return node;
          }
        });
  }
コード例 #23
0
  @NotNull
  private JBPopup createUsagePopup(
      @NotNull final List<Usage> usages,
      @NotNull final UsageInfoToUsageConverter.TargetElementsDescriptor descriptor,
      @NotNull Set<UsageNode> visibleNodes,
      @NotNull final FindUsagesHandler handler,
      final Editor editor,
      @NotNull final RelativePoint popupPosition,
      final int maxUsages,
      @NotNull final UsageViewImpl usageView,
      @NotNull final FindUsagesOptions options,
      @NotNull final JTable table,
      @NotNull final UsageViewPresentation presentation,
      @NotNull final AsyncProcessIcon processIcon,
      boolean hadMoreSeparator) {
    table.setRowHeight(PlatformIcons.CLASS_ICON.getIconHeight() + 2);
    table.setShowGrid(false);
    table.setShowVerticalLines(false);
    table.setShowHorizontalLines(false);
    table.setTableHeader(null);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    table.setIntercellSpacing(new Dimension(0, 0));

    PopupChooserBuilder builder = new PopupChooserBuilder(table);
    final String title = presentation.getTabText();
    if (title != null) {
      String result = getFullTitle(usages, title, hadMoreSeparator, visibleNodes.size() - 1, true);
      builder.setTitle(result);
      builder.setAdText(getSecondInvocationTitle(options, handler));
    }

    builder.setMovable(true).setResizable(true);
    builder.setItemChoosenCallback(
        new Runnable() {
          @Override
          public void run() {
            int[] selected = table.getSelectedRows();
            for (int i : selected) {
              Object value = table.getValueAt(i, 0);
              if (value instanceof UsageNode) {
                Usage usage = ((UsageNode) value).getUsage();
                if (usage == MORE_USAGES_SEPARATOR) {
                  appendMoreUsages(editor, popupPosition, handler, maxUsages);
                  return;
                }
                navigateAndHint(usage, null, handler, popupPosition, maxUsages, options);
              }
            }
          }
        });
    final JBPopup[] popup = new JBPopup[1];

    KeyboardShortcut shortcut = UsageViewImpl.getShowUsagesWithSettingsShortcut();
    if (shortcut != null) {
      new DumbAwareAction() {
        @Override
        public void actionPerformed(AnActionEvent e) {
          popup[0].cancel();
          showDialogAndFindUsages(handler, popupPosition, editor, maxUsages);
        }
      }.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table);
    }
    shortcut = getShowUsagesShortcut();
    if (shortcut != null) {
      new DumbAwareAction() {
        @Override
        public void actionPerformed(AnActionEvent e) {
          popup[0].cancel();
          searchEverywhere(options, handler, editor, popupPosition, maxUsages);
        }
      }.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table);
    }

    InplaceButton settingsButton =
        createSettingsButton(
            handler,
            popupPosition,
            editor,
            maxUsages,
            new Runnable() {
              @Override
              public void run() {
                popup[0].cancel();
              }
            });

    ActiveComponent spinningProgress =
        new ActiveComponent() {
          @Override
          public void setActive(boolean active) {}

          @Override
          public JComponent getComponent() {
            return processIcon;
          }
        };
    builder.setCommandButton(new CompositeActiveComponent(spinningProgress, settingsButton));

    DefaultActionGroup toolbar = new DefaultActionGroup();
    usageView.addFilteringActions(toolbar);

    toolbar.add(UsageGroupingRuleProviderImpl.createGroupByFileStructureAction(usageView));
    toolbar.add(
        new AnAction(
            "Open Find Usages Toolwindow",
            "Show all usages in a separate toolwindow",
            AllIcons.Toolwindows.ToolWindowFind) {
          {
            AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_FIND_USAGES);
            setShortcutSet(action.getShortcutSet());
          }

          @Override
          public void actionPerformed(AnActionEvent e) {
            hideHints();
            popup[0].cancel();
            FindUsagesManager findUsagesManager =
                ((FindManagerImpl) FindManager.getInstance(usageView.getProject()))
                    .getFindUsagesManager();

            findUsagesManager.findUsages(
                handler.getPrimaryElements(),
                handler.getSecondaryElements(),
                handler,
                options,
                FindSettings.getInstance().isSkipResultsWithOneUsage());
          }
        });

    ActionToolbar actionToolbar =
        ActionManager.getInstance()
            .createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR, toolbar, true);
    actionToolbar.setReservePlaceAutoPopupIcon(false);
    final JComponent toolBar = actionToolbar.getComponent();
    toolBar.setOpaque(false);
    builder.setSettingButton(toolBar);

    popup[0] = builder.createPopup();
    JComponent content = popup[0].getContent();

    myWidth =
        (int)
            (toolBar.getPreferredSize().getWidth()
                + new JLabel(
                        getFullTitle(
                            usages, title, hadMoreSeparator, visibleNodes.size() - 1, true))
                    .getPreferredSize()
                    .getWidth()
                + settingsButton.getPreferredSize().getWidth());
    myWidth = -1;
    for (AnAction action : toolbar.getChildren(null)) {
      action.unregisterCustomShortcutSet(usageView.getComponent());
      action.registerCustomShortcutSet(action.getShortcutSet(), content);
    }

    return popup[0];
  }
コード例 #24
0
  public PantallaPuntaje() {
    setBounds(100, 100, 590, 432);
    this.setLocationRelativeTo(PantallaPrincipal.getInstance());
    this.setResizable(false);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().setLayout(null);
    JLabel label_1 = new JLabel(""); // Boton atras
    label_1.addMouseListener(
        new MouseAdapter() {
          public void mouseClicked(MouseEvent e) {
            PantallaPrincipal.getInstance().setLocationRelativeTo(PantallaPuntaje.this);
            setVisible(false);
            PantallaPrincipal.getInstance().setVisible(true);
          }
        });

    Font font = null;
    try {
      font =
          Font.createFont(
              Font.TRUETYPE_FONT,
              getClass().getResourceAsStream("/res/fuente/VCR_OSD_MONO_1.001.ttf"));
    } catch (FontFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    genv.registerFont(font);
    font = font.deriveFont(12f);

    label_1.setIcon(new ImageIcon(PantallaAyuda.class.getResource("/res/flecha_final.png")));
    label_1.setBounds(16, 17, 52, 52);
    getContentPane().add(label_1);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.BLACK));
    scrollPane.setBounds(81, 82, 450, 231);
    getContentPane().add(scrollPane);

    Object[][] datos = new Object[MainJuego.getTopFive().size()][2];
    for (int i = 0; i < MainJuego.getTopFive().size(); i++) {
      datos[i][0] = MainJuego.getTopFive().get(i).getNombre();
      datos[i][1] = MainJuego.getTopFive().get(i).getPuntos();
    }

    String[] columnas = {"NOMBRE", " PUNTAJE"};

    DefaultTableCellRenderer Alinear = new DefaultTableCellRenderer();
    Alinear.setHorizontalAlignment(SwingConstants.CENTER);
    DefaultTableModel dtm = new DefaultTableModel(datos, columnas);

    table = new JTable(dtm);
    scrollPane.setViewportView(table);
    scrollPane.setBackground(Color.black);

    table.setBackground(Color.black);
    table.getTableHeader().setFont(font.deriveFont(Font.PLAIN, 40f));
    table.getTableHeader().setForeground(Color.YELLOW);
    table.getTableHeader().setBackground(Color.BLACK);
    table.setRowHeight(37);
    table.setFont(font.deriveFont(Font.PLAIN, 23f));
    table.setBorder(null);
    table.setForeground(Color.WHITE);
    table.setShowGrid(false);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);
    table.getColumnModel().getColumn(1).setCellRenderer(Alinear);
    table.setFocusable(false);
    table.setEnabled(false);

    JLabel lblNewLabel = new JLabel("New label");
    lblNewLabel.setIcon(new ImageIcon(PantallaPuntaje.class.getResource("/res/fondo puntaje.jpg")));
    lblNewLabel.setBounds(0, 0, 590, 410);
    getContentPane().add(lblNewLabel);
    this.setResizable(false);
  }
コード例 #25
0
  private void initComponents() {

    ResourceBundle resourceMap = ResourceBundle.getBundle("mekhq.resources.PartsStoreDialog");
    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setName("Form"); // NOI18N
    setTitle(resourceMap.getString("Form.title"));

    getContentPane().setLayout(new BorderLayout());

    partsTable = new JTable(partsModel);
    partsTable.setName("partsTable"); // NOI18N
    partsSorter = new TableRowSorter<PartsTableModel>(partsModel);
    partsSorter.setComparator(PartsTableModel.COL_TARGET, new TargetSorter());
    partsSorter.setComparator(PartsTableModel.COL_COST, new FormattedNumberSorter());
    partsSorter.setComparator(PartsTableModel.COL_DETAIL, new PartsDetailSorter());
    partsTable.setRowSorter(partsSorter);
    TableColumn column = null;
    for (int i = 0; i < PartsTableModel.N_COL; i++) {
      column = partsTable.getColumnModel().getColumn(i);
      column.setPreferredWidth(partsModel.getColumnWidth(i));
      column.setCellRenderer(partsModel.getRenderer());
    }
    partsTable.setIntercellSpacing(new Dimension(0, 0));
    partsTable.setShowGrid(false);
    scrollPartsTable = new JScrollPane();
    scrollPartsTable.setName("scrollPartsTable"); // NOI18N
    scrollPartsTable.setViewportView(partsTable);
    getContentPane().add(scrollPartsTable, BorderLayout.CENTER);

    GridBagConstraints c = new GridBagConstraints();
    panFilter = new JPanel();
    lblPartsChoice = new JLabel(resourceMap.getString("lblPartsChoice.text")); // NOI18N
    DefaultComboBoxModel<String> partsGroupModel = new DefaultComboBoxModel<String>();
    for (int i = 0; i < SG_NUM; i++) {
      partsGroupModel.addElement(getPartsGroupName(i));
    }
    choiceParts = new JComboBox<String>(partsGroupModel);
    choiceParts.setName("choiceParts"); // NOI18N
    choiceParts.setSelectedIndex(0);
    choiceParts.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            filterParts();
          }
        });
    panFilter.setLayout(new GridBagLayout());
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 0.0;
    c.anchor = java.awt.GridBagConstraints.WEST;
    c.insets = new Insets(5, 5, 5, 5);
    panFilter.add(lblPartsChoice, c);
    c.gridx = 1;
    c.weightx = 1.0;
    panFilter.add(choiceParts, c);

    lblFilter = new JLabel(resourceMap.getString("lblFilter.text")); // NOI18N
    lblFilter.setName("lblFilter"); // NOI18N
    c.gridx = 0;
    c.gridy = 1;
    c.weightx = 0.0;
    panFilter.add(lblFilter, c);
    txtFilter = new javax.swing.JTextField();
    txtFilter.setText(""); // NOI18N
    txtFilter.setMinimumSize(new java.awt.Dimension(200, 28));
    txtFilter.setName("txtFilter"); // NOI18N
    txtFilter.setPreferredSize(new java.awt.Dimension(200, 28));
    txtFilter
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              public void changedUpdate(DocumentEvent e) {
                filterParts();
              }

              public void insertUpdate(DocumentEvent e) {
                filterParts();
              }

              public void removeUpdate(DocumentEvent e) {
                filterParts();
              }
            });
    c.gridx = 1;
    c.gridy = 1;
    c.weightx = 1.0;
    panFilter.add(txtFilter, c);
    getContentPane().add(panFilter, BorderLayout.PAGE_START);

    panButtons = new JPanel();
    if (addToCampaign) {
      btnAdd = new JButton(resourceMap.getString("btnAdd.text"));
      btnAdd.addActionListener(
          new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
              addPart(false, false);
            }
          });
      btnAdd.setEnabled(campaign.isGM());
      btnBuyBulk = new JButton(resourceMap.getString("btnBuyBulk.text"));
      btnBuyBulk.addActionListener(
          new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
              addPart(true, true);
              partsModel.fireTableCellUpdated(
                  partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                  PartsTableModel.COL_TARGET);
              partsModel.fireTableCellUpdated(
                  partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                  PartsTableModel.COL_TRANSIT);
              partsModel.fireTableCellUpdated(
                  partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                  PartsTableModel.COL_SUPPLY);
              partsModel.fireTableCellUpdated(
                  partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                  PartsTableModel.COL_QUEUE);
            }
          });
      btnBuy = new JButton(resourceMap.getString("btnBuy.text"));
      btnBuy.addActionListener(
          new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
              addPart(true, false);
              partsModel.fireTableCellUpdated(
                  partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                  PartsTableModel.COL_TARGET);
              partsModel.fireTableCellUpdated(
                  partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                  PartsTableModel.COL_TRANSIT);
              partsModel.fireTableCellUpdated(
                  partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                  PartsTableModel.COL_SUPPLY);
              partsModel.fireTableCellUpdated(
                  partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                  PartsTableModel.COL_QUEUE);
            }
          });
      btnUseBonusPart = new JButton();
      if (campaign.getCampaignOptions().getUseAtB()) {
        int numBonusParts = campaign.totalBonusParts();
        btnUseBonusPart.setText("Use Bonus Part (" + numBonusParts + ")");
        btnUseBonusPart.addActionListener(
            new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
                addPart(true, false, true);
                partsModel.fireTableCellUpdated(
                    partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                    PartsTableModel.COL_TARGET);
                partsModel.fireTableCellUpdated(
                    partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                    PartsTableModel.COL_TRANSIT);
                partsModel.fireTableCellUpdated(
                    partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                    PartsTableModel.COL_SUPPLY);
                partsModel.fireTableCellUpdated(
                    partsTable.convertRowIndexToModel(partsTable.getSelectedRow()),
                    PartsTableModel.COL_QUEUE);
                int numBonusParts = campaign.totalBonusParts();
                btnUseBonusPart.setText("Use Bonus Part (" + numBonusParts + ")");
                btnUseBonusPart.setVisible(numBonusParts > 0);
              }
            });
        btnUseBonusPart.setVisible(numBonusParts > 0);
      }
      btnClose = new JButton(resourceMap.getString("btnClose.text"));
      btnClose.addActionListener(
          new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
              setVisible(false);
            }
          });
      panButtons.setLayout(new GridBagLayout());
      panButtons.add(btnBuyBulk, new GridBagConstraints());
      panButtons.add(btnBuy, new GridBagConstraints());
      if (campaign.getCampaignOptions().getUseAtB()) {
        panButtons.add(btnUseBonusPart, new GridBagConstraints());
      }
      panButtons.add(btnAdd, new GridBagConstraints());
      panButtons.add(btnClose, new GridBagConstraints());
    } else {
      // if we arent adding the unit to the campaign, then different buttons
      btnAdd = new JButton("Add");
      btnAdd.addActionListener(
          new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
              setSelectedPart();
              setVisible(false);
            }
          });
      panButtons.add(btnAdd, new GridBagConstraints());

      btnClose = new JButton("Cancel"); // NOI18N
      btnClose.addActionListener(
          new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
              selectedPart = null;
              setVisible(false);
            }
          });
      panButtons.add(btnClose, new GridBagConstraints());
    }
    getContentPane().add(panButtons, BorderLayout.PAGE_END);
    this.setPreferredSize(new Dimension(700, 600));
    pack();
  }
コード例 #26
0
  private DetailsView() {
    resultsPanel = (CytoPanelImp) Cytoscape.getDesktop().getCytoPanel(SwingConstants.EAST);
    this.kamService = KAMServiceFactory.getInstance().getKAMService();

    // build node details panel and add to results panel
    nodeDetailPanel = new JPanel();
    nodeDetailPanel.setName("KAM Node Info");

    JScrollPane tblScroll = new JScrollPane();
    JTable termTbl = new JTable();
    termTbl.setShowGrid(true);
    termTbl.setShowHorizontalLines(true);
    termTbl.setShowVerticalLines(true);

    nodeDetailPanel.setLayout(new BorderLayout());

    JLabel nodeLbl = new JLabel("Supporting BEL Terms");
    nodeDetailPanel.add(nodeLbl, BorderLayout.NORTH);

    termTableModel = new TermTableModel();
    termTbl.setModel(termTableModel);
    tblScroll.setViewportView(termTbl);

    nodeDetailPanel.add(tblScroll, BorderLayout.CENTER);
    resultsPanel.add(nodeDetailPanel);

    // build edge details panel and add to results panel
    edgeDetailPanel = new JPanel(new GridLayout(3, 1));
    edgeDetailPanel.setName("KAM Edge Info");

    TextAreaCellRenderer textRenderer = new TextAreaCellRenderer();

    // statement panel
    JPanel stmtPanel = new JPanel();
    stmtPanel.setLayout(new BorderLayout());
    JLabel edgeLbl = new JLabel("Supporting BEL Statements");
    stmtPanel.add(edgeLbl, BorderLayout.NORTH);
    JScrollPane stmtScroll = new JScrollPane();
    JTable stmtTbl = new JTable();
    stmtTbl.setShowGrid(true);
    stmtTbl.setShowHorizontalLines(true);
    stmtTbl.setShowVerticalLines(true);
    stmtTableModel = new StatementTableModel();
    stmtTbl.setModel(stmtTableModel);
    stmtTbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    stmtTbl.getSelectionModel().addListSelectionListener(new StatementSelectionListener());
    stmtScroll.setViewportView(stmtTbl);
    stmtPanel.add(stmtScroll, BorderLayout.CENTER);
    edgeDetailPanel.add(stmtPanel);

    // annotation panel
    JPanel annPanel = new JPanel();
    annPanel.setLayout(new BorderLayout());
    JLabel annLbl = new JLabel("Statement Annotations");
    annPanel.add(annLbl, BorderLayout.NORTH);
    JScrollPane annScroll = new JScrollPane();
    JTable annTbl = new JTable();
    annTbl.setShowGrid(true);
    annTbl.setShowHorizontalLines(true);
    annTbl.setShowVerticalLines(true);
    annTableModel = new AnnotationTableModel();
    annTbl.setModel(annTableModel);
    annTbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    annTbl.getColumnModel().getColumn(1).setCellRenderer(textRenderer);

    annScroll.setViewportView(annTbl);
    annPanel.add(annScroll, BorderLayout.CENTER);
    edgeDetailPanel.add(annPanel);

    // citation panel
    JPanel citPanel = new JPanel();
    citPanel.setLayout(new BorderLayout());
    JLabel citLbl = new JLabel("Citation");
    citPanel.add(citLbl, BorderLayout.NORTH);
    JScrollPane citScroll = new JScrollPane();
    JTable citTbl = new JTable();
    citTbl.setShowGrid(true);
    citTbl.setShowHorizontalLines(true);
    citTbl.setShowVerticalLines(true);
    citTableModel = new CitationTableModel();
    citTbl.setModel(citTableModel);
    citTbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    citTbl.getColumnModel().getColumn(0).setCellRenderer(textRenderer);
    citTbl.getColumnModel().getColumn(1).setCellRenderer(textRenderer);
    citTbl.getColumnModel().getColumn(2).setCellRenderer(textRenderer);
    citTbl.getColumnModel().getColumn(3).setCellRenderer(textRenderer);
    citScroll.setViewportView(citTbl);
    citPanel.add(citScroll, BorderLayout.CENTER);
    edgeDetailPanel.add(citPanel);

    // add edge details to Results Panel (cytoscape)
    resultsPanel.add(edgeDetailPanel);

    // delay showing panels
    nodeDetailPanel.setVisible(false);
    edgeDetailPanel.setVisible(false);
  }
コード例 #27
0
  // {{{ InstallPanel constructor
  InstallPanel(PluginManager window, boolean updates) {
    super(new BorderLayout(12, 12));

    this.window = window;
    this.updates = updates;

    setBorder(new EmptyBorder(12, 12, 12, 12));

    final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    split.setResizeWeight(0.75);
    /* Setup the table */
    table = new JTable(pluginModel = new PluginTableModel());
    table.setShowGrid(false);
    table.setIntercellSpacing(new Dimension(0, 0));
    table.setRowHeight(table.getRowHeight() + 2);
    table.setPreferredScrollableViewportSize(new Dimension(500, 200));
    table.setDefaultRenderer(
        Object.class,
        new TextRenderer((DefaultTableCellRenderer) table.getDefaultRenderer(Object.class)));
    table.addFocusListener(new TableFocusHandler());
    InputMap tableInputMap = table.getInputMap(JComponent.WHEN_FOCUSED);
    ActionMap tableActionMap = table.getActionMap();
    tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tabOutForward");
    tableActionMap.put("tabOutForward", new KeyboardAction(KeyboardCommand.TAB_OUT_FORWARD));
    tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK), "tabOutBack");
    tableActionMap.put("tabOutBack", new KeyboardAction(KeyboardCommand.TAB_OUT_BACK));
    tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "editPlugin");
    tableActionMap.put("editPlugin", new KeyboardAction(KeyboardCommand.EDIT_PLUGIN));
    tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "closePluginManager");
    tableActionMap.put(
        "closePluginManager", new KeyboardAction(KeyboardCommand.CLOSE_PLUGIN_MANAGER));

    TableColumn col1 = table.getColumnModel().getColumn(0);
    TableColumn col2 = table.getColumnModel().getColumn(1);
    TableColumn col3 = table.getColumnModel().getColumn(2);
    TableColumn col4 = table.getColumnModel().getColumn(3);
    TableColumn col5 = table.getColumnModel().getColumn(4);

    col1.setPreferredWidth(30);
    col1.setMinWidth(30);
    col1.setMaxWidth(30);
    col1.setResizable(false);

    col2.setPreferredWidth(180);
    col3.setPreferredWidth(130);
    col4.setPreferredWidth(70);
    col5.setPreferredWidth(70);

    JTableHeader header = table.getTableHeader();
    header.setReorderingAllowed(false);
    header.addMouseListener(new HeaderMouseHandler());
    header.setDefaultRenderer(
        new HeaderRenderer((DefaultTableCellRenderer) header.getDefaultRenderer()));

    scrollpane = new JScrollPane(table);
    scrollpane.getViewport().setBackground(table.getBackground());
    split.setTopComponent(scrollpane);

    /* Create description */
    JScrollPane infoPane = new JScrollPane(infoBox = new PluginInfoBox());
    infoPane.setPreferredSize(new Dimension(500, 100));
    split.setBottomComponent(infoPane);

    EventQueue.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            split.setDividerLocation(0.75);
          }
        });

    final JTextField searchField = new JTextField();
    searchField.addKeyListener(
        new KeyAdapter() {
          @Override
          public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_UP) {
              table.dispatchEvent(e);
              table.requestFocus();
            }
          }
        });
    searchField
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              void update() {
                pluginModel.setFilterString(searchField.getText());
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                update();
              }

              @Override
              public void insertUpdate(DocumentEvent e) {
                update();
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                update();
              }
            });
    table.addKeyListener(
        new KeyAdapter() {
          @Override
          public void keyPressed(KeyEvent e) {
            int i = table.getSelectedRow(), n = table.getModel().getRowCount();
            if (e.getKeyCode() == KeyEvent.VK_DOWN && i == (n - 1)
                || e.getKeyCode() == KeyEvent.VK_UP && i == 0) {
              searchField.requestFocus();
              searchField.selectAll();
            }
          }
        });
    Box filterBox = Box.createHorizontalBox();
    filterBox.add(new JLabel("Filter : "));
    filterBox.add(searchField);
    add(BorderLayout.NORTH, filterBox);
    add(BorderLayout.CENTER, split);

    /* Create buttons */
    Box buttons = new Box(BoxLayout.X_AXIS);

    buttons.add(new InstallButton());
    buttons.add(Box.createHorizontalStrut(12));
    buttons.add(new SelectallButton());
    buttons.add(chooseButton = new ChoosePluginSet());
    buttons.add(new ClearPluginSet());
    buttons.add(Box.createGlue());
    buttons.add(new SizeLabel());

    add(BorderLayout.SOUTH, buttons);
    String path = jEdit.getProperty(PluginManager.PROPERTY_PLUGINSET, "");
    if (!path.isEmpty()) {
      loadPluginSet(path);
    }
  } // }}}
コード例 #28
0
  // Método construtor da Tela que contem os Tabuleiros
  // public BoardWindow(int[][] tabuleiro, String gameType, Server server, Client client){
  public BoardWindow(String gameType, Server server, Client client) {
    // Determina nome Janela
    super("Batalha Naval XP");

    // Cria um Container
    bwFrame = this.getContentPane();

    // Guarda qual o modo que está rodando
    setType(gameType);

    // Cria um Painel
    panel = new JPanel();

    // Cria uma Tabela
    table = new JTable(11, 11);
    tableEnemy = new JTable(11, 11);
    tableScore = new JTable(3, 4);

    // Determina a cor das bordas da tabela
    Color c = Color.BLACK;
    table.setGridColor(c);
    tableEnemy.setGridColor(c);
    tableScore.setGridColor(c);

    // Colorir coluna
    // Color index = Color.GREEN;
    // io_rd_renderer.setBackground(index);
    // table.getColumnModel().getColumn(0).setCellRenderer(io_rd_renderer);

    // Retira o cabeçalho da tabela
    table.setTableHeader(null);
    tableEnemy.setTableHeader(null);
    tableScore.setTableHeader(null);

    // Exibe as bordas da tabela
    table.setShowGrid(true);
    tableEnemy.setShowGrid(true);
    tableScore.setShowGrid(true);

    // Númera a primeira coluna e linha
    setFirstColumn(table);
    setFirstRow(table);

    setFirstColumn(tableEnemy);
    setFirstRow(tableEnemy);

    mountTableScore(tableScore);

    // Cria um frame para colocar a tabela e ajusta o seu tamanho

    // Tabela "Seu tabuleiro"
    pane = new JScrollPane(table);
    pane.getViewport().setPreferredSize(table.getPreferredSize());

    // Tabela "Respostas"
    paneEnemy = new JScrollPane(tableEnemy);
    paneEnemy.getViewport().setPreferredSize(tableEnemy.getPreferredSize());

    // Tabela de Pontuação
    paneScore = new JScrollPane(tableScore);
    paneScore.getViewport().setPreferredSize(tableScore.getPreferredSize());

    // Botão para Iniciar Disparo
    btShot = new JButton("Iniciar Disparo");
    btShot.setSize(50, 50);
    btShot.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // Instancia Objeto a ser enviado por Socket
            Shot shot = new Shot();

            int check = 1;
            int error = 0;

            // Enquanto não foi apertado o botão certo e os dados não estiverem corretos, o
            // aplicativo irá solicitar coordenadas
            while (check != 0) {

              // Limpa possíveis rastros nos JTexts
              tf1c.setText(null);
              tf1r.setText(null);

              // Cria campos para Inserção
              message = new Object[] {"Coordenadas do Tiro", "Coluna", tf1c, "Linha", tf1r};

              // Cria Mensagem de Erro
              errorMessage =
                  new Object[] {
                    "Verifique os coordenadas inseridos, pois existem coordenadas inválidas.\n"
                        + "Coordenadas válidas são de 1 a 10. Letras não são válidas\n"
                        + "Coordenadas repetidas."
                  };

              // Solicita dados aos usuário
              check =
                  JOptionPane.showConfirmDialog(
                      null, message, "Inserir coordenada do Tiro", JOptionPane.OK_OPTION);

              // Se o botão pressionado for Sim
              if (check == 0) {

                // Faz validação do tiro. Se for válidado envia tiro pelo Socket. Se não exibe
                // mensagem de erro
                if (validateShot(tf1r.getText(), tf1c.getText(), shots)) {

                  // Cria Objeto a ser enviado
                  shot.createShot(tf1r.getText(), tf1c.getText(), board);

                  try {

                    // Verifica se é Cliente ou Servidor. Desabilita o Botão para não enviar mais de
                    // um tiro e envia objeto por Socket
                    if (type.equals("Server")) {
                      btShot.setEnabled(false);
                      socketServer.sendObject.flush();
                      socketServer.sendObject.writeObject(shot);
                      socketServer.sendObject.flush();
                    }

                    if (type.equals("Client")) {
                      btShot.setEnabled(false);
                      socketClient.sendObject.flush();
                      socketClient.sendObject.writeObject(shot);
                      socketClient.sendObject.flush();
                    }
                  } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                  }
                } else {
                  // Mensagem de erro
                  error =
                      JOptionPane.showConfirmDialog(
                          null,
                          errorMessage,
                          "Erro ao inserir Coordenadas",
                          JOptionPane.CANCEL_OPTION);
                  check = 1;
                }
              }
            }
          }
        });

    // Adiciona frame ao painel
    panel.add(player1);
    panel.add(pane);
    panel.add(player2);
    panel.add(paneEnemy);
    panel.add(paneScore);
    panel.add(btShot);
    panel.setAlignmentX(CENTER_ALIGNMENT);

    // Adiciona o painel ao container
    bwFrame.add(panel);

    // Instancia Objeto Board
    board = new Board();

    // Inicia o jogo pelo Servidor
    if (type.equals("Client")) {
      btShot.setEnabled(false);
    }

    // Adiciona as referências aos objetos que serão usados pelas Classes na thread
    if (getType().equals("Server")) {
      socketServer = server;
      socketServer.setServerTable(table);
      socketServer.setServerScore(tableScore);
      socketServer.setServerButton(btShot);
      socketServer.setServerTableAnswer(tableEnemy);
    } else {
      socketClient = client;
      socketClient.setClientTable(table);
      socketClient.setClientScore(tableScore);
      socketClient.setClientButton(btShot);
      socketClient.setClientTableAnswer(tableEnemy);
    }

    // Configura detalhes do Frame
    // 1. Encerrar Applicação ao Fechar
    // 2. Setar Frame como Visível
    // 3. Setar as dimensões do Frame
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 1
    this.setVisible(true); // 2
    this.setSize(1024, 460); // 3	

    btHorizontal.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (btHorizontal.isSelected()) {
              btVertical.setSelected(false);
            }
          }
        });

    btVertical.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (btVertical.isSelected()) {
              btHorizontal.setSelected(false);
            }
          }
        });

    mountBoard(table);

    // Percorre matriz do tabuleiro preenchida com valores dos barcos posicionados pelo usuario
    /*for( int linha = 1; linha < 10; linha++ )
    {
    	for( int coluna = 1; coluna < 10; coluna++ )
    	{
    		// Se houver algum barco na posicao corrente, exibe na celula da tabela
    		if ( tabuleiro[linha][coluna] > 0 )
    		{
    			// Coloca as Iniciais dos Barcos(P, Q, T, D e S)
    			switch (tabuleiro[linha][coluna]){
     			case 1:
     			{
     				table.setValueAt("S", linha, coluna);
     				break;
     			}
     			case 2:
     			{
     				table.setValueAt("D", linha, coluna);
     				break;
     			}
     			case 3:
     			{
     				table.setValueAt("T", linha, coluna);
     				break;
     			}
     			case 4:
     			{
     				table.setValueAt("Q", linha, coluna);
     				break;
     			}
     			case 5:
     			{
     				table.setValueAt("P", linha, coluna);
     				break;
     			}
    			}

    		}
    	}
    }*/

  }
コード例 #29
0
  private void createTicker() {
    setBackground(ColorAndFontConstants.BACKGROUND_COLOR);
    setLayout(new GridBagLayout());
    setOpaque(false);
    setFocusable(false);

    setToolTipText(
        HelpContentsPanel.createMultilineTooltipText(
            new String[] {
              controller.getLocaliser().getString("tickerTablePanel.tooltip"),
              "\n ",
              controller.getLocaliser().getString("tickerTablePanel.tooltip.clickToConfigure")
            }));

    // on mouse click - view the exchanges tab
    MouseListener viewPreferencesMouseListener =
        new MouseAdapter() {
          @Override
          public void mouseReleased(MouseEvent arg0) {
            controller.displayView(View.PREFERENCES_VIEW);
          }
        };

    String tickerTooltipText =
        HelpContentsPanel.createMultilineTooltipText(
            new String[] {
              controller.getLocaliser().getString("tickerTablePanel.tooltip"),
              "\n ",
              controller.getLocaliser().getString("tickerTablePanel.tooltip.clickToConfigure")
            });

    addMouseListener(viewPreferencesMouseListener);

    GridBagConstraints constraints = new GridBagConstraints();

    tickerTableModel = new TickerTableModel(this.exchangeController);

    table = new JTable(tickerTableModel);
    table.setOpaque(true);
    table.setShowGrid(true);
    table.setGridColor(Color.lightGray);
    table.setBackground(ColorAndFontConstants.BACKGROUND_COLOR);
    table.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, SystemColor.windowBorder));

    table.setComponentOrientation(
        ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
    table.setRowHeight(getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()).getHeight());

    table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    table.setRowSelectionAllowed(false);
    table.setColumnSelectionAllowed(false);
    table.getTableHeader().setReorderingAllowed(false);

    table.setToolTipText(tickerTooltipText);
    table.addMouseListener(viewPreferencesMouseListener);
    table.getTableHeader().addMouseListener(viewPreferencesMouseListener);
    table.getTableHeader().setToolTipText(tickerTooltipText);
    table.getTableHeader().setFont(FontSizer.INSTANCE.getAdjustedDefaultFontWithDelta(-1));

    int tableHeaderHeight =
        fontMetrics.getHeight()
            + table.getTableHeader().getInsets().top
            + table.getTableHeader().getInsets().bottom;

    // Windows 8 has slightly taller headers so add a tweak for that.
    if (System.getProperty("os.name", "unknown").startsWith("Win")) {
      tableHeaderHeight = tableHeaderHeight + WINDOWS_TABLE_HEADER_HEIGHT_TWEAK;
    }

    int tickerWidth = setupColumnWidths();
    setupTableHeaders();

    idealHeight =
        (fontMetrics.getHeight() + table.getRowMargin()) * tickerTableModel.getRowCount()
            + tableHeaderHeight
            + tickerTableModel.getRowCount()
            + 10;

    setPreferredSize(new Dimension(tickerWidth, idealHeight));

    scrollPane =
        new JScrollPane(
            table,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    scrollPane.setComponentOrientation(
        ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    scrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
    scrollPane.addMouseListener(viewPreferencesMouseListener);

    setupScrollPane(tickerWidth);

    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.gridwidth = 1;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.anchor = GridBagConstraints.CENTER;

    add(scrollPane, constraints);
  }
コード例 #30
0
ファイル: ReplCacheDemo.java プロジェクト: kookse/bboss-rpc
  private void start(
      String props,
      String cluster_name,
      long rpc_timeout,
      long caching_time,
      boolean migrate_data,
      boolean use_l1_cache,
      int l1_max_entries,
      long l1_reaping_interval,
      int l2_max_entries,
      long l2_reaping_interval)
      throws Exception {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    cache = new ReplCache<String, String>(props, cluster_name);
    cache.setCallTimeout(rpc_timeout);
    cache.setCachingTime(caching_time);
    cache.setMigrateData(migrate_data);
    JmxConfigurator.register(cache, server, BASENAME + ":name=cache");
    JmxConfigurator.register(cache.getL2Cache(), server, BASENAME + ":name=l2-cache");

    if (use_l1_cache) {
      Cache<String, String> l1_cache = new Cache<String, String>();
      cache.setL1Cache(l1_cache);
      if (l1_reaping_interval > 0) l1_cache.enableReaping(l1_reaping_interval);
      if (l1_max_entries > 0) l1_cache.setMaxNumberOfEntries(l1_max_entries);
      JmxConfigurator.register(cache.getL1Cache(), server, BASENAME + ":name=l1-cache");
    }

    if (l2_max_entries > 0 || l2_reaping_interval > 0) {
      Cache<String, ReplCache.Value<String>> l2_cache = cache.getL2Cache();
      if (l2_max_entries > 0) l2_cache.setMaxNumberOfEntries(l2_max_entries);
      if (l2_reaping_interval > 0) l2_cache.enableReaping(l2_reaping_interval);
    }

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                cache.stop();
              }
            });

    cache.start();

    model = new MyTableModel<String, String>();
    model.setMap(cache.getL2Cache().getInternalMap());
    cache.addChangeListener(model);

    frame = new JFrame("ReplCacheDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    table = new MyTable(model);
    table.setPreferredScrollableViewportSize(new Dimension(500, 200));
    // table.setFillsViewportHeight(true); // JDK 6 specific
    table.setShowGrid(false);
    table.setFont(table.getFont().deriveFont(Font.BOLD));
    add(new JScrollPane(table));

    JPanel key = new JPanel(new FlowLayout(FlowLayout.LEFT));
    key.add(new JLabel("Key  "));
    key.add(key_field);
    add(key);

    JPanel value = new JPanel(new FlowLayout(FlowLayout.LEFT));
    value.add(new JLabel("Value"));
    value.add(value_field);
    add(value);

    JPanel repl_count = new JPanel(new FlowLayout(FlowLayout.LEFT));
    repl_count.add(new JLabel("Replication count"));
    repl_count.add(repl_count_field);
    add(repl_count);

    JPanel timeout = new JPanel(new FlowLayout(FlowLayout.LEFT));
    timeout.add(new JLabel("Timeout"));
    timeout.add(timeout_field);
    add(timeout);

    JPanel buttons = new JPanel();
    JButton put_button = createButton("Put");
    buttons.add(createButton("Put"));
    buttons.add(createButton("Remove"));
    buttons.add(createButton("Clear"));
    buttons.add(createButton("Rebalance"));
    buttons.add(createButton("Exit"));
    buttons.add(num_elements);
    add(buttons);
    setOpaque(true);

    root_pane.addTab("Data", this);
    JPanel perf_panel = new JPanel();
    perf_panel.setLayout(new BoxLayout(perf_panel, BoxLayout.Y_AXIS));
    perf_panel.setOpaque(true);
    root_pane.addTab("Perf test", perf_panel);

    perf_panel.add(status);
    status.setForeground(Color.BLUE);

    JPanel prefix = new JPanel(new FlowLayout(FlowLayout.LEFT));
    prefix.add(new JLabel("Key prefix"));
    prefix.add(perf_key_prefix);
    perf_panel.add(prefix);

    JPanel keys = new JPanel(new FlowLayout(FlowLayout.LEFT));
    keys.add(new JLabel("Number of keys to insert"));
    keys.add(perf_num_keys);
    perf_panel.add(keys);

    JPanel size = new JPanel(new FlowLayout(FlowLayout.LEFT));
    size.add(new JLabel("Size of each key (bytes)"));
    size.add(perf_size);
    size.add(new JLabel("    (ignored for now)"));
    perf_panel.add(size);

    JPanel perf_repl_count = new JPanel(new FlowLayout(FlowLayout.LEFT));
    perf_repl_count.add(new JLabel("Replication count"));
    perf_repl_count.add(perf_repl_count_field);
    perf_panel.add(perf_repl_count);

    JPanel perf_timeout = new JPanel(new FlowLayout(FlowLayout.LEFT));
    perf_timeout.add(new JLabel("Timeout"));
    perf_timeout.add(perf_timeout_field);
    perf_panel.add(perf_timeout);

    JPanel perf_buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
    perf_buttons.add(createButton("Start"));
    perf_buttons.add(createButton("Stop"));
    perf_buttons.add(createButton("Reset"));
    perf_buttons.add(createButton("Exit"));
    perf_panel.add(perf_buttons);

    frame.setContentPane(root_pane);
    frame.pack();
    frame.getRootPane().setDefaultButton(put_button);
    frame.setVisible(true);
    setTitle("ReplCacheDemo");

    cache.addMembershipListener(
        new MembershipListenerAdapter() {
          public void viewAccepted(View new_view) {
            setTitle("ReplCacheDemo");
          }
        });
  }