2015-02-03 4 views
0

У меня есть приложение Java, которое показывает вещи из базы данных. Я хотел бы изменить цвет строк на основе содержимого ячейки. Я попытался вставить цикл if в процесс извлечения данных из базы данных с использованием свойства setBackground, но не преуспел в этом.Java - изменение цвета строки на основе содержимого ячеек

Здесь есть код. Что я делаю неправильно?

public class TableFrame2 extends JFrame { 

    private JPanel contentPane; 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       String user = "root"; 
       String password = ""; 
       TableFrame2 frame = new TableFrame2(user, password); 
       frame.setVisible(true);    


      } 
     }); 
    } 

    /** 
    * Create the frame. 
    * @return 
    */ 

    public TableFrame2(String user, String password) { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 399, 300); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     setContentPane(contentPane); 

     JScrollPane scrollPane = new JScrollPane(); 
     DefaultTableModel model = new DefaultTableModel(); 
     JTable table = new JTable(model); 
     table.setEditingColumn(0); 
     table.setEditingRow(0); 
     table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); 
     table.setFillsViewportHeight(true); 
     table.setBackground(Color.WHITE); 
     table.setRowSelectionAllowed(true); 
     model.addColumn("iD"); 
     model.addColumn("name"); 
     model.addColumn("type"); 
     table.setPreferredScrollableViewportSize(new Dimension(200, 200)); 
     scrollPane.setViewportView(table); 
     try { 
      String dateMerged = "2015-01-30";//yearField.getText() + "-" + monthField.getText() + "-" + dayField.getText(); 

      Connection connection = MysqlConnector.dbConnection(user, password); 
      String query = "SELECT * FROM booking, band WHERE room_idRoom = 2 AND idBand = band_idBand AND dateBooking BETWEEN '" +dateMerged+" 00:00:00' AND '" +dateMerged+" 23:59:59'"; 
      PreparedStatement pst = connection.prepareStatement(query); 
      ResultSet rs = pst.executeQuery(); 
      while (rs.next()){ 
       String bandName = rs.getString("nameBand"); 
       String bookingType = rs.getString("typeBooking"); 
       String bookingId = rs.getString("idBooking"); 
       model.addRow(new Object[] { bookingId, bandName,bookingType }); 

       if (bookingType == "Recording"){ 
        table.setBackground(Color.RED); 
       } 
      } 

     } catch (ClassNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (InstantiationException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     GroupLayout gl_contentPane = new GroupLayout(contentPane); 
     gl_contentPane.setHorizontalGroup(
      gl_contentPane.createParallelGroup(Alignment.TRAILING) 
       .addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup() 
        .addContainerGap() 
        .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 114, GroupLayout.PREFERRED_SIZE) 
        .addContainerGap(89, Short.MAX_VALUE)) 
     ); 
     gl_contentPane.setVerticalGroup(
      gl_contentPane.createParallelGroup(Alignment.TRAILING) 
       .addGroup(gl_contentPane.createSequentialGroup() 
        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
        .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) 
     ); 
    } 
} 
+3

Вам нужно использовать custorm 'TableCellRenderer', читайте больше в [tutoria] (http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender). – alex2410

+0

Для примера [http://stackoverflow.com/a/5799016/230513). – trashgod

+0

Спасибо большое, ребята! –

ответ

1

Заканчивать Table Row Rendering, который позволяет сделать, чтобы пользовательский рендеринг без создания нескольких пользовательских рендеров для различных типов данных в таблице.

+0

Спасибо большое! –

Смежные вопросы