Java Code Examples for javax.swing.table.DefaultTableModel

The following are top voted examples for showing how to use javax.swing.table.DefaultTableModel. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Java_Swing_Programming   File: Soru3.java   View source code 11 votes vote down vote up
public Soru3() {
    initComponents();

    dtm = new DefaultTableModel();
    dtm.setColumnIdentifiers(new Object[]{"ID", "ADI", "SOYADI", "MAAS"});
    jTable1.setModel(dtm);
    try {
        // bağlantı için
        Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/PERSONELDB", "sa", "as");
        // iletişimi acıyor
        Statement stmt = con.createStatement();
        // veritabanında sorgu çalıştırıp bize geri tablo döndürüyor.
        ResultSet rs = stmt.executeQuery("SELECT * FROM PERSONEL");

        while (rs.next()) {
            int id = rs.getInt("ID");
            String adi = rs.getString("ADI");
            String soyadi = rs.getString("SOYADI");
            int maas = rs.getInt("MAAS");
            dtm.addRow(new Object[]{id, adi, soyadi, maas});
        }

    } catch (SQLException ex) {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 2
Project: flight-management-system-java   File: AfficherAvions.java   View source code 9 votes vote down vote up
public void loadTableBD(int num) {
    Result res = db.execute("MATCH (n:`Avion`{numero:"+num+"}) RETURN n.numero, n.type, n.capacite");
    DefaultTableModel dtm = new DefaultTableModel(0,0);
    String header[] = {"Numero", "Type", "Capacite"};
    String test[] = {"n.numero", "n.type", "n.capacite"};
    dtm.setColumnIdentifiers(header);
    jTable1.setModel(dtm);
    while(res.hasNext()) {
        Map<String, Object> row = res.next();
        Map<String, Object> obj = new LinkedHashMap();
        for (String t:test) {
            obj.put(t, null);
        }
        for(Map.Entry<String, Object> col : row.entrySet()) {
             obj.put(col.getKey(),col.getValue());   
        }
        
        dtm.addRow(obj.values().toArray());
}
}
 
Example 3
Project: projetomcdonalds   File: ControlerHistorico.java   View source code 6 votes vote down vote up
public ControlerHistorico(Historico historico) {
    this.historico = historico;

    this.historico.getTbl_Historico().getColumnModel().getColumn(2).setPreferredWidth(170);
    this.historico.getTbl_Historico().getColumnModel().getColumn(4).setPreferredWidth(485);
    dtm = (DefaultTableModel) this.historico.getTbl_Historico().getModel();

    this.historico.getBtn_Cancelar().addActionListener(this);
    this.historico.getBtn_Ok().addActionListener(this);
    this.historico.getRbt_Data().addActionListener(this);
    this.historico.getRbt_Todas().addActionListener(this);

    getDados();
    preencheTabela();

    this.historico.setVisible(true);
}
 
Example 4
Project: JITRAX   File: QueryResultViewer.java   View source code 6 votes vote down vote up
public QueryResultViewer() {
	resultSet = null;
	tableModel = new DefaultTableModel();
	emptyResultLabel = new JLabel(EMPTY_RESULT_MSG);
	mainContainer = new JPanel();
	
	setLayout(new BorderLayout());
	tableSP = new JScrollPane(graphicTable,
			JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
			JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
	tableSP.setBorder(BorderFactory.createEmptyBorder());
	
	graphicTable.setModel(tableModel);
	graphicTable.setFillsViewportHeight(true);
	graphicTable.setEnabled(false);
	
	addComponentListener(new ComponentAdapter() {
	    public void componentResized(ComponentEvent e) {
	        resizeColumnWidth(COL_MIN_WIDTH);          
	    }
	});
	
	mainContainer.add(tableSP);
	setLayout(new GridLayout(1,1));
	add(tableSP);
}
 
Example 5
Project: Hotel-Properties-Management-System   File: RoomWindow.java   View source code 6 votes vote down vote up
private void populatePostPayTable(DefaultTableModel model) {

		// import all customers from database
		final PostingDaoImpl postingDaoImpl = new PostingDaoImpl();
		List<Posting> postingList = postingDaoImpl.getAllPostingsByRoomNumber(roomNumber, hotelSystemStatus.getDateTime().toString());

		final PaymentDaoImpl paymentDaoImpl = new PaymentDaoImpl();
		List<Payment> paymentlist = paymentDaoImpl.getAllPaymentsByRoomNumber(roomNumber, hotelSystemStatus.getDateTime().toString());

		// clean table model
		model.setRowCount(0);

		for (Posting pos : postingList) {

			model.addRow(new Object[] { pos.getId(), pos.getPostType(), pos.getTitle(), pos.getPrice(),
					pos.getCurrency(), pos.getExplanation(), pos.getDateTime() });
		}

		for (Payment pay : paymentlist) {

			model.addRow(new Object[] { pay.getId(), pay.getPaymentType(), pay.getTitle(), pay.getPrice(),
					pay.getCurrency(), pay.getExplanation(), pay.getDateTime() });
		}
	}
 
Example 6
Project: CodeGen   File: VariableUI.java   View source code 6 votes vote down vote up
private void addAction() {
    VariableEditDialog dialog = new VariableEditDialog();
    dialog.setTitle("Create New Variable");
    dialog.getButtonOK().addActionListener(it -> {
        String key = dialog.getKeyTextField().getText().trim();
        String value = dialog.getValueTextField().getText().trim();
        DefaultTableModel tableModel = (DefaultTableModel) varTable.getModel();
        String[] rowValues = {key, value};
        tableModel.addRow(rowValues);
        dialog.setVisible(false);
    });

    dialog.setSize(300, 150);
    dialog.setAlwaysOnTop(true);
    dialog.setLocationRelativeTo(rootPanel);
    dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
    dialog.setResizable(false);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setVisible(true);
}
 
Example 7
Project: projetomcdonalds   File: ControlerCadastroLanche.java   View source code 6 votes vote down vote up
@Override
public void preencheTabela() {
    dtm = (DefaultTableModel) this.cadastroLanche.getjTable1().getModel();

    if (this.lanches != null) {
        for (Lanche lan : lanches) {
            dtm.insertRow(dtm.getRowCount(), new Object[]{
                lan.getNome(),
                lan.getPreco()
            });
        }
    }
    this.cadastroLanche.getLista_ingredientes().setModel(dlmIng);
    this.cadastroLanche.getLista_lanche().setModel(dlmLan);

    for (int i = 0; i < this.ingredientes.size(); i++) {
        dlmIng.add(i, this.ingredientes.get(i).getNome());
    }

}
 
Example 8
Project: 20170612-NotaFIscalEletronica   File: FrameIndicadores.java   View source code 6 votes vote down vote up
private void construtorPanelIndicador(){

		Object[] colunas = new String[]{"Pesquisa","Resultado"};

		Object[][] dados = new Object[][]{
		};

		model = new DefaultTableModel(dados , colunas ){
			public boolean isCellEditable(int row, int col){
				return false;
			}
		};
		tabela = new JTable();
		tabela.setModel(model);
		tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		painelTabela = new JScrollPane();
		painelTabela.setViewportView(tabela);
		
		// busca e inserção dos resultados na tabela
		this.consultaIndicadores();
		
	}
 
Example 9
Project: flight-management-system-java   File: MainWindow.java   View source code 6 votes vote down vote up
public void loadTableBD(String dateAuj) {
    Result res = db.execute("MATCH (a:Avion)-[r:Affecter]->(d:Depart)<-[c:Constituer]-(v:Vol) WHERE d.date='"+dateAuj+"' RETURN d.numero, d.date, v.villeDep, v.villeArr,  a.type, a.capacite, v.numero, v.heureDep, v.heureArr");
    DefaultTableModel dtm = new DefaultTableModel(0,0);
    String header[] = {"Numero", "Date","Depart", "Arriveé", "Type", "Capacite", "NumVol", "Heure De Depart", "Heure d'arrive"};
    String test[] = {"d.numero", "d.date","v.villeDep", "v.villeArr", "a.type", "a.capacite", "v.numero", "v.heureDep", "v.heureArr"};
    dtm.setColumnIdentifiers(header);
    jTable1.setModel(dtm);
    while(res.hasNext()) {
        Map<String, Object> row = res.next();
        Map<String, Object> obj = new LinkedHashMap();
        for (String t:test) {
            obj.put(t, null);
        }
        for(Map.Entry<String, Object> col : row.entrySet()) {
             obj.put(col.getKey(),col.getValue());   
        }
        
        dtm.addRow(obj.values().toArray());
}
}
 
Example 10
Project: mindroid   File: MindroidServerFrame.java   View source code 6 votes vote down vote up
public void addContentLine(ServerLogMessage deseriaLogMessage) {
    try {
        DefaultTableModel model = (DefaultTableModel) this.table.getModel();
        String timeStamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
        model.addRow(new String[]{timeStamp, deseriaLogMessage.getSource().getValue(),
                deseriaLogMessage.getLogLevel().toString(), deseriaLogMessage.getContent()});
    } catch (ArrayIndexOutOfBoundsException e) {
        //Tries again n times, error was caused by 2 threads accessing the table at the same time
        int n = 10;
        int i=0;
        while (!retryAddContentLine(deseriaLogMessage) && i<n) {
            i++;

        }
        if (i==n) {
            //retrying failed
            throw e;
        }

         }
}
 
Example 11
Project: java-swing-template   File: Preferences.java   View source code 6 votes vote down vote up
private void loadUsersTable() {
    ArrayList<User> usersList = UserController.getUsersList();
    if (usersList.size() > 0) {
        DefaultTableModel def = (DefaultTableModel) users_table.getModel();
        def.setNumRows(0);

        for (User user : usersList) {
            String userName = user.getUserName();
            String userDisplayName = user.getUserDisplayName();
            UserLevel userLevel = user.getUserLevel();
            Integer userType = user.getUserType();
            Integer userStatus = user.getUserStatus();

            Vector v = new Vector();
            v.add(user);
            v.add(userDisplayName);
            v.add(userLevel.getLevelDisplayName());
            v.add(userType == 1 ? "Permanent" : "Temporary");
            v.add((userStatus == 1));
            def.addRow(v);
        }
    }
}
 
Example 12
Project: flight-management-system-java   File: AfficherVols.java   View source code 6 votes vote down vote up
public void loadTableBD() {
    Result res = db.execute("MATCH (n:`Vol`) RETURN n.numero, n.villeDep, n.villeArr, n.heureDep, n.heureArr, n.distance, n.frequence ORDER BY n.numero");
    DefaultTableModel dtm = new DefaultTableModel(0,0);
    String header[] = {"n.numero", "Depart", "Arrivee", "Heure Depart", "Heure Arrivee", "Distance", "Frequence"};
    String test[] = {"n.numero", "n.villeDep", "n.villeArr", "n.heureDep", "n.heureArr", "n.distance", "n.frequence"};
    dtm.setColumnIdentifiers(header);
    jTable1.setModel(dtm);
    while(res.hasNext()) {
        Map<String, Object> row = res.next();
        Map<String, Object> obj = new LinkedHashMap();
        for (String t:test) {
            obj.put(t, null);
        }
        for(Entry<String, Object> col : row.entrySet()) {
             obj.put(col.getKey(),col.getValue());   
        }
        
        dtm.addRow(obj.values().toArray());
}
}
 
Example 13
Project: projetomcdonalds   File: ControlerPedidos.java   View source code 6 votes vote down vote up
public ControlerPedidos(Pedidos pedidos) {
    this.pedidos = pedidos;

    this.pedidos.getTbl_Pedidos().getColumnModel().getColumn(0).setPreferredWidth(240);
    this.pedidos.getTbl_Pedidos().getColumnModel().getColumn(1).setPreferredWidth(585);

    this.pedidos.getBtn_Anterior().addActionListener(this);
    this.pedidos.getBtn_Cancelar().addActionListener(this);
    this.pedidos.getBtn_Entregue().addActionListener(this);
    this.pedidos.getBtn_Primeiro().addActionListener(this);
    this.pedidos.getBtn_Proximo().addActionListener(this);
    this.pedidos.getBtn_Ultimo().addActionListener(this);
    this.pedidos.getMnu_atualizar_pedidos().addActionListener(this);

    getDados();
    this.dtm = (DefaultTableModel) this.pedidos.getTbl_Pedidos().getModel();
    preencheTabela();

    this.pedidos.setVisible(true);

}
 
Example 14
Project: Cognizant-Intelligent-Test-Scripter   File: JtableUtils.java   View source code 6 votes vote down vote up
/**
 * Reads clipboard data and converts it into supported format and fills the
 * tmodel cells
 *
 * @param table the target tmodel
 */
private static void pasteFromClipboard(JTable table) {
    int startRow = table.getSelectedRows()[0];
    int startCol = table.getSelectedColumns()[0];
    String pasteString;
    try {
        pasteString = (String) (CLIPBOARD.getContents(CLIPBOARD).getTransferData(DataFlavor.stringFlavor));
    } catch (UnsupportedFlavorException | IOException ex) {
        Logger.getLogger(JtableUtils.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    String[] lines = pasteString.split(LINE_BREAK);
    for (int i = 0; i < lines.length; i++) {
        String[] cells = lines[i].split(CELL_BREAK);
        if (table.getRowCount() <= startRow + i) {
            ((DefaultTableModel) table.getModel()).addRow(nullRow);
        }
        for (int j = 0; j < cells.length; j++) {
            if (table.getColumnCount() > startCol + j) {
                if (table.isCellEditable(startRow + i, startCol + j)) {
                    table.setValueAt(cells[j], startRow + i, startCol + j);
                }
            }
        }
    }
}
 
Example 15
Project: tcc-rpg   File: DAO.java   View source code 6 votes vote down vote up
public void listarItensNPC() {
    final String sql = ("SELECT * FROM item WHERE fk_personagem = (?)");
    try {
        PreparedStatement stmt = c.prepareStatement(sql);
        stmt.setInt(1, pegarPk_personagem(nomePersonagem));
        ResultSet rs = stmt.executeQuery();
        DefaultTableModel model = (DefaultTableModel) TelaNPC.tabela.getModel();
        while (rs.next()) {
            int id = rs.getInt("pk_item");
            String nomeIcon = rs.getString("icone_ite");
            ImageIcon icon = (new ImageIcon(getClass().getResource("/ItemIcons/" + nomeIcon)));
            String nome = rs.getString("nome_ite");
            String atibutos = rs.getString("atributos_ite");
            String descricao = rs.getString("descricao_ite");
            int quantidade = rs.getInt("quantidade_ite");
            Object[] item = {id, quantidade, icon, nome, null, atibutos, descricao};
            model.addRow(item);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Project: incubator-netbeans   File: PropertyEditorPanel.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void updateTableFromEditor() {
    synchronized (this) {
        if (updateing) {
            return;
        }
        updateing = true;
        DefaultTableModel dtm = (DefaultTableModel) propertyTable.getModel();
        Vector columns = new Vector(2);
        Vector values = new Vector();
        columns.add(dtm.getColumnName(0));
        columns.add(dtm.getColumnName(1));
        if (value != null) {
            for (String key : value.stringPropertyNames()) {
                Vector row = new Vector(2);
                row.add(key);
                row.add(value.getProperty(key, ""));
                values.add(row);
            }
        }
        dtm.setDataVector(values, columns);
        updateing = false;
    }
}
 
Example 17
Project: incubator-netbeans   File: J2SEProjectProperties.java   View source code 6 votes vote down vote up
private void storeRoots( SourceRoots roots, DefaultTableModel tableModel ) throws MalformedURLException {
    Vector data = tableModel.getDataVector();
    URL[] rootURLs = new URL[data.size()];
    String []rootLabels = new String[data.size()];
    final LinkedList<URL> oldRootURLs = new LinkedList<URL>(Arrays.asList (roots.getRootURLs (false)));
    final LinkedList<String> oldRootLabels = new LinkedList<String>(Arrays.asList(roots.getRootNames()));
    final LinkedList<String> oldRootProps = new LinkedList<String>(Arrays.asList (roots.getRootProperties()));
    boolean rootsAreSame = true;
    for (int i=0; i<data.size();i++) {
        File f = (File) ((Vector)data.elementAt(i)).elementAt(0);
        rootURLs[i] = Utilities.toURI(f).toURL();
        if (!rootURLs[i].toExternalForm().endsWith("/")) {  //NOI18N
            rootURLs[i] = new URL(rootURLs[i]+"/");
        }
        validateURL(rootURLs[i],f);
        rootLabels[i] = (String) ((Vector)data.elementAt(i)).elementAt(1);
        rootsAreSame &= !oldRootURLs.isEmpty() &&
                        oldRootURLs.removeFirst().equals(rootURLs[i]) &&
                        roots.getRootDisplayName(oldRootLabels.removeFirst(), oldRootProps.removeFirst()).equals(rootLabels[i]);
    }
    if (!rootsAreSame || !oldRootURLs.isEmpty ()) {
        roots.putRoots(rootURLs,rootLabels);
    }
}
 
Example 18
Project: Java_Swing_Programming   File: Soru1.java   View source code 6 votes vote down vote up
public Soru1() {
    initComponents();

    ///SORGULAMA
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("BP2_LAB2PU");
    EntityManager em = emf.createEntityManager();

    Query q = em.createQuery("SELECT d FROM Doktor d");
    doktorlar = q.getResultList();
    for (Doktor dr : doktorlar) {
        cmb_doktorlar.addItem(dr.getAdi() + " " + dr.getSoyadi());
    }

    dtm = new DefaultTableModel();
    dtm.setColumnIdentifiers(new Object[]{"ID", "ADI", "SOYADI", "DOkTOR ID"});
    q = em.createQuery("SELECT h FROM Hasta h");
    List<Hasta> hastalar = q.getResultList();
    for (Hasta hs : hastalar) {
        dtm.addRow(new Object[]{hs.getId(), hs.getAdi(), hs.getSoyadi(), hs.getIdDoktor()});
    }
    tbl_hastalar.setModel(dtm);
    /////
}
 
Example 19
Project: my-diploma-work   File: KnowledgeBaseFrame.java   View source code 6 votes vote down vote up
private void setDataToTable(List<Eat> eats) {
    DefaultTableModel df = (DefaultTableModel) jTable1.getModel();
    df.getDataVector().removeAllElements();
    df.fireTableDataChanged();
    for (Eat eat : eats) {
        List<String> foods = new ArrayList<>();
        for (Food food : eat.getFoods()) {
            foods.add(food.getFood());
        }
        Object[] row = new Object[]{
            eat.getId(),
            eat.getName(),
            foods.toString()
        };
        df.addRow(row);
    }
    df.fireTableDataChanged();
}
 
Example 20
Project: tcc-rpg   File: DAO.java   View source code 6 votes vote down vote up
public void listarArmasNPC() {
    final String sql = ("SELECT * FROM itemWeapon WHERE fk_personagem = (?)");
    try {
        PreparedStatement stmt = c.prepareStatement(sql);
        stmt.setInt(1, pegarPk_personagem(nomePersonagem));
        ResultSet rs = stmt.executeQuery();
        DefaultTableModel model = (DefaultTableModel) TelaNPC.tabela.getModel();
        while (rs.next()) {
            int id = rs.getInt("pk_itemWeapon");
            String nomeIcon = rs.getString("icone_itWea");
            ImageIcon icon = (new ImageIcon(getClass().getResource("/WeaponIcons/" + nomeIcon)));
            String nome = rs.getString("nome_itWea");
            int dano = rs.getInt("danoBase_itWea");
            String atibutos = rs.getString("atributos_itWea");
            String descricao = rs.getString("descricao_itWea");
            int quantidade = rs.getInt("quantidade_itWea");
            Object[] arma = {id, quantidade, icon, nome, dano, atibutos, descricao};
            model.addRow(arma);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 21
Project: Cognizant-Intelligent-Test-Scripter   File: TMSettings.java   View source code 5 votes vote down vote up
private void loadModuleInTable(TestMgModule testModule) {
    DefaultTableModel model = (DefaultTableModel) moduleTable.getModel();
    model.setRowCount(0);
    List<Option> option = testModule.getOptions();
    for (Option op : option) {
        model.addRow(new Object[]{op.getName(), op.getValue()});
    }
}
 
Example 22
Project: ProyectoPacientes   File: Paciente.java   View source code 5 votes vote down vote up
public void BuscarPaciente(DefaultTableModel modelo, String Apellidos) {
        Conexion nuevaConexion = new Conexion();
        Connection conex;
        ResultSet Consulta = null;
        try {
            nuevaConexion.Conectar();
            conex = nuevaConexion.getConexion();
            Statement comando = conex.createStatement();
           
            Consulta = comando.executeQuery("select pacientes.idPaciente, pacientes.Nombre, pacientes.Apellidos, pacientes.DIreccion, pacientes.Telefono from pacientes where pacientes.Apellidos='"+Apellidos+"'");
                String pacientes[] = new String[5];
            while(Consulta.next()==true){
                pacientes[0]=Consulta.getString("idPaciente");
                pacientes[1]=Consulta.getString("Nombre");
                pacientes[2]=Consulta.getString("Apellidos");
                pacientes[3]=Consulta.getString("DIreccion");
                pacientes[4]=Consulta.getString("Telefono");
                modelo.addRow(pacientes);
            }
            
            {
                JDBuscarPacientes.jtPacientes.setModel(modelo);
            }
           
      } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"error"+ e);
      } 
}
 
Example 23
Project: LOSY   File: ListProyects.java   View source code 5 votes vote down vote up
private void jTableProyectsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableProyectsMouseClicked
    int row = jTableProyects.rowAtPoint(evt.getPoint());
    DefaultTableModel tablaproyect = (DefaultTableModel) jTableProyects.getModel();
    String dato=String.valueOf(tablaproyect.getValueAt(jTableProyects.getSelectedRow(), 0));
    select = dato;
    //select = Integer.toString(row+1);

    //JOptionPane.showMessageDialog(null, dato);
    //select = (String)jTableEquipment.getValueAt(row, 1);
    //select = (String)jTableEquipment.getValueAt(row, 0);
    modificar();
}
 
Example 24
Project: PPRCarTrade   File: TelaBuscarVeiculo.java   View source code 5 votes vote down vote up
private void jrb_ModeloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrb_ModeloActionPerformed
    // TODO add your handling code here:        
    ArrayList<VendaVeiculo> aux = NegocioFacade.listaVeiculos();        
    Collections.sort(aux, new ModeloVeiculoComparator());
    
    DefaultTableModel model = (DefaultTableModel)jtb_Veiculos.getModel();
    model.setRowCount(0);
    for(VendaVeiculo a : aux){
        model.addRow(new Object[]{ a.getVeiculo().getMarca(), a.getVeiculo().getModelo(),
                               a.getVeiculo().getCor(), a.getVeiculo().getAno(), a.getPreco()});
    }
    
    jtb_Veiculos.setModel(model);
    
}
 
Example 25
Project: pharamacy-management   File: Manager.java   View source code 5 votes vote down vote up
private void checksActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checksActionPerformed
         String url="jdbc:mysql://localhost:3306/pharmacy?zeroDateTimeBehavior=convertToNull";
         String user="root";
         String pass="root";       
         String l="select * from revenue";
         
        try (Connection con=DriverManager.getConnection(url,user,pass);
                 PreparedStatement stmt=con.prepareStatement(l))
         {                   
        ResultSet rs=stmt.executeQuery();             
        DefaultTableModel model = new DefaultTableModel(new String[]{"BILL NO", "Total"}, 0);
         
        while(rs.next())
        {
           String d = rs.getString("bill_no");
           String n = rs.getString("total");
          
           model.addRow(new Object[]{d, n});  
             //JTable ta=new JTable(data,column);  
              sales.setModel(model); 
            // ta.setBounds(30,40,200,300); 
            //JScrollPane sp=new JScrollPane(add_table);
            //setVisible(true);
         }
         }
     catch(Exception e)
         {
             System.err.println(e.getMessage());
         }

    
}
 
Example 26
Project: Cognizant-Intelligent-Test-Scripter   File: JtableUtils.java   View source code 5 votes vote down vote up
/**
 * Loads the Data Array into the tmodel
 *
 * @param table to be populated
 * @param header column header
 * @param rows nullRoww data
 * @return populated tmodel
 */
public static JTable populatetable(JTable table, String[] header, List<String[]> rows) {
    removeRowSelection(table);
    DefaultTableModel tablemodel = (DefaultTableModel) table.getModel();
    tablemodel.setRowCount(0);
    for (String col : header) {
        tablemodel.addColumn(col);
    }
    for (String[] row : rows) {
        tablemodel.addRow(row);
    }
    table.setModel(tablemodel);
    return table;
}
 
Example 27
Project: Equella   File: AbstractTableMapping.java   View source code 5 votes vote down vote up
private void init()
{
	model = new DefaultTableModel()
	{
		private static final long serialVersionUID = 1L;

		@Override
		public Class<?> getColumnClass(int c)
		{
			Object value = getValueAt(0, c);
			Class<?> cs = null;
			if( value != null )
			{
				cs = value.getClass();
			}
			else
			{
				cs = super.getColumnClass(c);
			}
			return cs;
		}
	};
	model.setColumnIdentifiers(getColumnNames());
	table = new JTable(model);
	table.getSelectionModel().addListSelectionListener(this);
	table.setRowHeight(20);

	int count = model.getColumnCount();
	for( int i = 0; i < count; i++ )
	{
		TableColumn column = table.getColumnModel().getColumn(i);
		processTableColumn(column, i);
	}
	table.doLayout();

	this.setLayout(new BorderLayout());
	this.add(new JScrollPane(table), BorderLayout.CENTER);
	this.add(createBottom(), BorderLayout.SOUTH);
}
 
Example 28
Project: EVE   File: RSSContentPanel.java   View source code 5 votes vote down vote up
public RSSContentPanel(){
    setLayout(new BorderLayout());
    stories = new ArrayList<>();
    String[] columns = {"Title", "Author", "Description", "Date", "Feed"};
    model = new DefaultTableModel(null, columns);
    table = new JTable(model);
    table.addMouseListener(new Listener());
    pane = new JScrollPane(table);
    //article = new JPanel();
    add(pane, BorderLayout.NORTH);
    //add(article, BorderLayout.SOUTH);
}
 
Example 29
Project: stuManager   File: ScoreManager.java   View source code 5 votes vote down vote up
public void UpdateRecord() {
	Object[][] arrTmp = {}; // �趨�����ֶ�
	Vector vec = new Vector(1, 1);
	model = new DefaultTableModel(arrTmp, arrField);
	jTable1 = new JTable(model);
	jScrollPane1.getViewport().add(jTable1, null);
	try {
		ResultSet rs = sta.getRs(sql);
		int i = 1;
		while (rs.next()) {
			vec = new Vector();
			vec.add(String.valueOf(rs.getString("scoreId")));
			vec.add(String.valueOf(rs.getString("stuNumber")));
			ResultSet rsTemp = sta.getRs("select stuName from tb_student where stuNumber='"
					+ String.valueOf(rs.getString("stuNumber")) + "'");
			while (rsTemp.next()) {
				vec.add(String.valueOf(rsTemp.getString("stuName")));
			}
			vec.add(String.valueOf(rs.getString("courceName")));
			vec.add(String.valueOf(rs.getString("score")));
			model.addRow(vec);
		}
		rs.close();
	} catch (Exception ce) {
		System.out.println(ce);
	}
	jScrollPane1.getHorizontalScrollBar();
	jTable1.setGridColor(Color.blue);
	jTable1.setDragEnabled(true);
	jTable1.setSelectionForeground(Color.red);
	jTable1.setSelectionBackground(Color.green);
	jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	jTable1.setRowSelectionAllowed(true);
	jTable1.setShowVerticalLines(true);
}
 
Example 30
Project: burp-vulners-scanner   File: VulnersService.java   View source code 5 votes vote down vote up
/**
 * Check out rules for matching
 */
public void loadRules() {
    Unirest.get(BURP_API_URL)
            .routeParam("path", "rules")
            .asJsonAsync(new VulnersRestCallback(callbacks) {

                @Override
                public void onSuccess(JSONObject data) {
                    JSONObject rules = data.getJSONObject("rules");
                    Iterator<String> ruleKeys = rules.keys();

                    DefaultTableModel ruleModel = tabComponent.getRulesTable().getDefaultModel();
                    ruleModel.setRowCount(0); //reset table
                    while (ruleKeys.hasNext()) {
                        String key = ruleKeys.next();
                        final JSONObject v = rules.getJSONObject(key);

                        ruleModel.addRow(new Object[]{key, v.getString("regex"), v.getString("alias"), v.getString("type")});

                        try {
                            Pattern pattern = Pattern.compile(v.getString("regex"));
                            System.out.println("[NEW] " + pattern);

                            burpExtender.getMatchRules().put(key, new HashMap<String, String>() {{
                                put("regex", v.getString("regex"));
                                put("alias", v.getString("alias"));
                                put("type", v.getString("type"));
                            }});
                            // Match group 1 - is important
                            burpExtender.addMatchRule(new MatchRule(pattern, 1, key, ScanIssueSeverity.LOW, ScanIssueConfidence.CERTAIN));
                        } catch (PatternSyntaxException pse) {
                            callbacks.printError("Unable to compile pattern: " + v.getString("regex") + " for: " + key);
                            burpExtender.printStackTrace(pse);
                        }
                    }

                }
            });
}
 
Example 31
Project: stuManager   File: ClassManager.java   View source code 5 votes vote down vote up
public void UpdateRecord() {
	Object[][] arrTmp = {};
	Vector vec = new Vector(1, 1);
	model = new DefaultTableModel(arrTmp, arrField);
	jTable1 = new JTable(model);
	jScrollPane1.getViewport().add(jTable1, null);
	try {
		ResultSet rs3 = conn.getRs(sql);
		while (rs3.next()) {
			vec = new Vector();
			vec.add(String.valueOf(rs3.getInt("classId")));
			vec.add(rs3.getString("departName").trim());
			vec.add(rs3.getString("specName"));
			vec.add(rs3.getString("className"));
			model.addRow(vec);
		}
		rs3.close();
	} catch (Exception e) {
		System.out.println(e.getMessage());
	}
	jScrollPane1.getHorizontalScrollBar();
	jTable1.setGridColor(Color.blue);
	jTable1.setDragEnabled(true);
	jTable1.setSelectionForeground(Color.red);
	jTable1.setSelectionBackground(Color.green);
	jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	jTable1.setRowSelectionAllowed(true);
	jTable1.setShowVerticalLines(true);

}
 
Example 32
Project: incubator-netbeans   File: JFXJavaScriptCallbacksPanel.java   View source code 5 votes vote down vote up
private static TableModel createModel(final Map<String,String> callbacks) {
    final Object[][] data = new Object[callbacks.size()][];
    final Iterator<Map.Entry<String,String>> it = callbacks.entrySet().iterator();
    for (int i=0; it.hasNext(); i++) {
        final Map.Entry<String,String> entry = it.next();
        data[i] = new Object[] {entry.getKey(),entry.getValue()};
    }
    return new DefaultTableModel(
        data,
        new String[] {
            NbBundle.getMessage(JFXDownloadModePanel.class, "JFXJavaScriptCallbacksPanel.tableCallbacks.columnModel.title0"), //NOI18N
            NbBundle.getMessage(JFXDownloadModePanel.class, "JFXJavaScriptCallbacksPanel.tableCallbacks.columnModel.title1") //NOI18N
        }) {
        @Override
        public boolean isCellEditable(int row, int column) {
            return column != 0;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            switch (columnIndex) {
                case 0:
                    return String.class;
                case 1:
                    return String.class;
                default:
                    throw new IllegalStateException();
            }
        }
        
    };
}
 
Example 33
Project: Java_Swing_Programming   File: Soru3.java   View source code 5 votes vote down vote up
public Soru3() {
        try {
            initComponents();

            dtm = new DefaultTableModel();
            dtm.setColumnIdentifiers(new Object[]{"ID", "MUSTERİ ID", "MUSTERİ ADI", "MALZEME ID", "MALZEME ADI", "SATIS", "ADET", "TUTAR"});
            tbl_liste.setModel(dtm);
// bağlantı için
            Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/DEPO", "sa", "as");
            // iletişimi acıyor
            Statement stmt = con.createStatement();
            // veritabanında sorgu çalıştırıp bize geri tablo döndürüyor.
            ResultSet rs = stmt.executeQuery("SELECT * FROM MALZEME");
            while (rs.next()) {

                String malzemeadi = rs.getString("ADI");
                malzemeid.add(rs.getInt("ID"));
                cmb_malzeme.addItem(malzemeadi);
            }

            rs = stmt.executeQuery("SELECT * FROM MUSTERI");
            while (rs.next()) {

                String adi = rs.getString("ADI");
                musteriid.add(rs.getInt("ID"));
                cmb_musteri.addItem(adi);
            }

        } catch (SQLException ex) {
            Logger.getLogger(Soru3.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
 
Example 34
Project: incubator-netbeans   File: CategoryPanelStepFilters.java   View source code 5 votes vote down vote up
private void filtersUncheckAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filtersUncheckAllButtonActionPerformed
    DefaultTableModel model = (DefaultTableModel) filterClassesTable.getModel();
    for (int i = 0; i < model.getRowCount(); i++) {
        model.setValueAt(Boolean.FALSE, i, 0);
    }
    filterClassesTable.repaint();
}
 
Example 35
Project: Cognizant-Intelligent-Test-Scripter   File: FileUtils.java   View source code 5 votes vote down vote up
public static void loadFileinTable(File file, JTable table) {
    if (file.exists()) {
        try (Reader in = new FileReader(file)) {
            CSVParser parser = CSVFormat.EXCEL.withHeader().withSkipHeaderRecord().withIgnoreEmptyLines().parse(in);
            if (!parser.getHeaderMap().isEmpty()) {
                DefaultTableModel model = (DefaultTableModel) table.getModel();
                for (String columnHeader : parser.getHeaderMap().keySet()) {
                    if (!columnHeader.trim().isEmpty()) {
                        model.addColumn(columnHeader);
                    }
                }
                List<CSVRecord> records = parser.getRecords();
                for (CSVRecord record : records) {
                    Object[] row = new Object[record.size()];
                    for (int i = 0; i < record.size(); i++) {
                        row[i] = record.get(i);
                    }
                    model.addRow(row);
                }
            }
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
        }
    } else {
        LOGGER.log(Level.SEVERE, "File [{0}] doesn''t exist", file.getAbsolutePath());
    }
}
 
Example 36
Project: incubator-netbeans   File: VariableFormatterEditPanel.java   View source code 5 votes vote down vote up
private void moveDownVarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownVarButtonActionPerformed
    int index = childrenVariablesTable.getSelectedRow();
    if (index < 0) return ;
    DefaultTableModel model = (DefaultTableModel) childrenVariablesTable.getModel();
    if (index >= (model.getRowCount() - 1)) return ;
    Object[] row = new Object[] { model.getValueAt(index, 0), model.getValueAt(index, 1) };
    model.removeRow(index);
    model.insertRow(index + 1, row);
    childrenVariablesTable.getSelectionModel().setSelectionInterval(index + 1, index + 1);
}
 
Example 37
Project: incubator-netbeans   File: BuildOptionsVisual.java   View source code 5 votes vote down vote up
private void deleteVariableButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteVariableButtonActionPerformed
    DefaultTableModel model = (DefaultTableModel) buildargsTable.getModel();
    int selectedRowId = buildargsTable.getSelectedRow();
    if (selectedRowId != -1) {
        model.removeRow(selectedRowId);
    }
}
 
Example 38
Project: projetomcdonalds   File: ControlerCadastroFuncionario.java   View source code 5 votes vote down vote up
@Override
public void preencheTabela() {

    dtm = (DefaultTableModel) this.cadastroFuncionario.getjTable1().getModel();
    for (Funcionarios func : funcionarios) {
        dtm.insertRow(dtm.getRowCount(), new Object[]{
            func.getNome(),
            func.getCpf(),
            func.getTelefone(),
            (func.getNivel_acesso() == 1) ? "Vendedor" : "Gerente"
        });
    }

}
 
Example 39
Project: AgentWorkbench   File: ChartSettingsTab.java   View source code 5 votes vote down vote up
/**
 * Sets the chart setting model data to the form.
 */
public void setChartSettingModelData() {
	
	this.getTfChartTitle().setText(this.chartSettingModel.getChartTitle());
	this.getTfXAxisLabel().setText(this.chartSettingModel.getChartXAxisLabel());
	this.getTfYAxisLabel().setText(this.chartSettingModel.getChartYAxisLabel());
	this.getCbRendererType().setSelectedItem(this.chartSettingModel.getRenderType());
	
	DefaultTableModel tbModel = this.chartSettingModel.getTableModelSeriesSettings();
	if (tbModel!=this.getTblSeriesSettings().getModel()) {
		this.getTblSeriesSettings().setModel(tbModel);
		this.refreshRenderEditorTblSeriesSettings();	
	}
}
 
Example 40
Project: incubator-netbeans   File: ShortcutPopupPanel.java   View source code 5 votes vote down vote up
private void addAlternative() {
    String category = (String) table.getValueAt(row, 2);
    ShortcutAction action = ((ActionHolder) table.getValueAt(row, 0)).getAction();
    Object[] newRow = new Object[]{new ActionHolder(action, true), "", category, ""};
    ((DefaultTableModel) ((TableSorter) table.getModel()).getTableModel()).insertRow(row + 1, newRow);
    pm.setVisible(false);
    table.editCellAt(row + 1, 1);
}