背景排序JTable后,特定值的颜色不会改变
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了背景排序JTable后,特定值的颜色不会改变相关的知识,希望对你有一定的参考价值。
请建议更改我的代码。背景排序JTable
后,特定值的颜色不会改变。
Java表单代码
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author HP
*/
public class Technicain_Report extends javax.swing.JFrame {
Connection con=null;
ResultSet rs = null;
ResultSet rs1 = null;
PreparedStatement pst=null;
location Location = new location();
String loc = Location.url;
String user = Location.user;
String pass = Location.pass ;
String Serpass = null ;
String userlogger ;
TableModel model ;
public Technicain_Report() {
initComponents();
}
public Technicain_Report(String pass) {
initComponents();
mob.setSelected(true);
comp.setSelected(false);
userlogger = pass ;
model = techrprt.getModel();
this.setTitle("Technician Report - " + userlogger);
((DefaultTableCellRenderer)techrprt.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
filler();
TableColumnModel columnModel = techrprt.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(15);
columnModel.getColumn(1).setPreferredWidth(200);
columnModel.getColumn(2).setPreferredWidth(30);
columnModel.getColumn(3).setPreferredWidth(20);
columnModel.getColumn(4).setPreferredWidth(130);
columnModel.getColumn(5).setPreferredWidth(20);
sort();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
techrprt = new javax.swing.JTable()
{
@Override
public Component prepareRenderer (TableCellRenderer renderer, int rowIndex, int columnIndex){
Component componenet = super.prepareRenderer(renderer, rowIndex, columnIndex);
// int selrow = techrprt.getSelectedRow();
// int index = techrprt.getRowSorter().convertRowIndexToModel(selrow);
Object value = getModel().getValueAt(rowIndex,columnIndex);
if(columnIndex == 5){
if(value.equals("NEW"))
{
componenet.setBackground(Color.RED);
componenet.setForeground(Color.WHITE);
}
}
else {
componenet.setBackground(Color.WHITE);
componenet.setForeground(Color.BLACK);
}
return componenet;
}
}
;
mobsrch = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
mob = new javax.swing.JRadioButton();
comp = new javax.swing.JRadioButton();
shwdlvd = new javax.swing.JCheckBox();
table.setBackground(new java.awt.Color(255, 204, 204));
table.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"SL NO.", "NAME", "MOBILE NO.", "SELECT"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class
};
boolean[] canEdit = new boolean [] {
false, false, false, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table.setColumnSelectionAllowed(true);
table.setRowHeight(20);
table.setRowMargin(2);
table.setRowSelectionAllowed(false);
table.setSelectionForeground(new java.awt.Color(204, 204, 255));
table.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(table);
setTitle("Technician Report");
techrprt.setBackground(new java.awt.Color(255, 204, 204));
techrprt.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
techrprt.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"SER. NO.", "CUSTOMER NAME", "MOBILE NO.", "CATEGORY", "MODEL", "STATUS"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
techrprt.setRowHeight(20);
techrprt.setRowMargin(2);
techrprt.setSelectionForeground(new java.awt.Color(204, 204, 255));
techrprt.getTableHeader().setReorderingAllowed(false);
techrprt.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
servicepass(evt);
}
});
jScrollPane2.setViewportView(techrprt);
techrprt.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
if (techrprt.getColumnModel().getColumnCount() > 0) {
techrprt.getColumnModel().getColumn(0).setResizable(false);
techrprt.getColumnModel().getColumn(1).setResizable(false);
techrprt.getColumnModel().getColumn(2).setResizable(false);
techrprt.getColumnModel().getColumn(3).setResizable(false);
techrprt.getColumnModel().getColumn(4).setResizable(false);
techrprt.getColumnModel().getColumn(5).setResizable(false);
}
mobsrch.addInputMethodListener(new java.awt.event.InputMethodListener() {
public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
mobsrchCaretPositionChanged(evt);
}
public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
mobsrchInputMethodTextChanged(evt);
}
});
mobsrch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mobsrchActionPerformed(evt);
}
});
mobsrch.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
mobsrchKeyReleased(evt);
}
});
jButton1.setText("Search");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
mob.setText("Mobile");
mob.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
mobMouseClicked(evt);
}
});
comp.setText("Company Name");
comp.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
compMouseClicked(evt);
}
});
shwdlvd.setText("Show Delivered Items");
shwdlvd.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
shwdlvdMouseClicked(evt);
}
});
shwdlvd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
shwdlvdActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 883, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(18, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(shwdlvd)
.addGap(18, 18, 18)
.addComponent(mob)
.addGap(55, 55, 55)
.addComponent(comp))
.addComponent(mobsrch, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(36, 36, 36))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(mob)
.addComponent(comp)
.addComponent(shwdlvd))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(mobsrch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 541, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setSize(new java.awt.Dimension(927, 650));
setLocationRelativeTo(null);
}// </editor-fold>
private void mobsrchActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
filtercheck();
}
private void compMouseClicked(java.awt.event.MouseEvent evt) {
mob.setSelected(false);
}
private void mobMouseClicked(java.awt.event.MouseEvent evt) {
comp.setSelected(false);
}
private void mobsrchKeyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode()==KeyEvent.VK_ENTER){
filtercheck();
}
}
private void shwdlvdActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void shwdlvdMouseClicked(java.awt.event.MouseEvent evt) {
filler();
}
private void mobsrchInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
buttonclicker();
}
private void mobsrchCaretPositionChanged(java.awt.event.InputMethodEvent evt) {
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
jButton1.doClick();
}
},
1000
);
}
private void servicepass(java.awt.event.MouseEvent evt) {
int selrow = techrprt.getSelectedRow();
int index = techrprt.getRowSorter().convertRowIndexToModel(selrow);
String value1 = model.getValueAt(index, 0).toString();
new Service_Details( user, value1).setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Technicain_Report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Technicain_Report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Technicain_Report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Technicain_Report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Technicain_Report().setVisible(true);
}
});
}
public void filler(){
String sql ;
try {
if("admin".equals(userlogger) )
{
if(shwdlvd.isSelected())
{
sql ="select * from tbl_serviceInvoice ";
}
else
{
sql ="select * from tbl_serviceInvoice where contactNo <> 'd' ";
}
}
else
{
if(shwdlvd.isSelected())
{
sql ="select * from tbl_serviceInvoice where SalesMan = '"+userlogger+"' ";
}
else
{
sql ="select * from tbl_serviceInvoice where SalesMan = '"+userlogger+"' and contactNo <> 'd' ";
}
}
DefaultTableModel model = (DefaultTableModel) techrprt.getModel();
model.setRowCount(0);
con =DriverManager.getConnection( loc , user, pass);
pst =con.prepareStatement(sql);
rs=pst.executeQuery();
while(rs.next()){
String data1 = rs.getString("No");
String data2 = rs.getString("customerName");
String data4 = rs.getString("makeAndModel");
String data5 = rs.getString("imeiNo");
String data6 = rs.getString("contactNo");
String data21 ;
String data23;
String ctn = data2;
String sql123;
sql123 ="select * from tblaccountmaster WHERE AccountCode = '"+ctn+"' ";
con =DriverManager.getConnection( loc , user, pass);
pst =con.prepareStatement(sql123);
rs1=pst.executeQuery();
while(rs1.next()){
data21 = rs1.getString("AccountName");
data23 = rs1.getString("ContactNumber");
Object[] row = { data1 ,data21,data23,data4,data5,data6};
model.addRow(row);
}
}
con.close();
}catch(SQLException Ex){
Logger.getLogger(login.classgetName()).log(Level.SEVERE,null,Ex);
}
}
public void filtercheck()
{
String text1 = mobsrch.getText();
String sql ;
try {
if("admin".equals(userlogger) )
{
if(shwdlvd.isSelected())
{
sql ="select * from tbl_serviceInvoice ";
}
else
{
sql ="select * from tbl_serviceInvoice where contactNo <> 'd' ";
}
}
else
{
if(shwdlvd.isSelected())
{
sql ="select * from tbl_serviceInvoice where SalesMan = '"+userlogger+"' ";
}
else
{
sql ="select * from tbl_serviceInvoice where SalesMan = '"+userlogger+"' and contactNo <> 'd' ";
}
}
DefaultTableModel model = (DefaultTableModel) techrprt.getModel();
model.setRowCount(0);
con =DriverManager.getConnection( loc , user, pass);
pst =con.prepareStatement(sql);
rs=pst.executeQuery();
while(rs.next()){
String data1 = rs.getString("No");
String data2 = rs.getString("customerName");
String data4 = rs.getString("makeAndModel");
String data5 = rs.getString("imeiNo");
String data6 = rs.getString("contactNo");
String data21 ;
String data23;
String ctn = data2;
String sql123 ;
if("".equals(text1))
{
sql123 ="select * from tblaccountmaster WHERE AccountCode = '"+ctn+"' ";
}
else
{
if(mob.isSelected())
{
sql123 ="select * from tblaccountmaster WHERE AccountCode = '"+ctn+"' and ContactNumber like '%"+text1+"%' ";
}
else
{
sql123 ="select * from tblaccountmaster WHERE AccountCode = '"+ctn+"' and AccountName like '%"+text1+"%' ";
}
}
con =DriverManager.getConnection( loc , user, pass);
pst =con.prepareStatement(sql123);
rs1=pst.executeQuery();
while(rs1.next()){
data21 = rs1.getString("AccountName");
data23 = rs1.getString("ContactNumber");
Object[] row = { data1 ,data21,data23,data4,data5,data6};
model.addRow(row);
}
}
con.close();
}catch(SQLException Ex){
Logger.getLogger(login.classgetName()).log(Level.SEVERE,null,Ex);
}
}
public void sort()
{
DefaultTableModel dm = (DefaultTableModel) techrprt.getModel();
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(dm);
techrprt.setRowSorter(sorter);
}
public void buttonclicker()
{
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
jButton1.doClick();
}
},
1000
);
}
public void coloring()
{}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JRadioButton comp;
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JRadioButton mob;
private javax.swing.JTextField mobsrch;
private javax.swing.JCheckBox shwdlvd;
private javax.swing.JTable table;
private javax.swing.JTable techrprt;
// End of variables declaration
}
JTable
的自定义代码
techrprt = new javax.swing.JTable()
{
@Override
public Component prepareRenderer (TableCellRenderer renderer, int rowIndex, int columnIndex){
Component componenet = super.prepareRenderer(renderer, rowIndex, columnIndex);
// int selrow = techrprt.getSelectedRow();
// int index = techrprt.getRowSorter().convertRowIndexToModel(selrow);
Object value = getModel().getValueAt(rowIndex,columnIndex);
if(columnIndex == 5){
if(value.equals("NEW"))
{
componenet.setBackground(Color.RED);
componenet.setForeground(Color.WHITE);
}
}
else {
componenet.setBackground(Color.WHITE);
componenet.setForeground(Color.BLACK);
}
return componenet;
}
};
当我对列进行排序时,值“new”的背景颜色处于相同的初始位置。当我对列进行排序时,它没有得到更新。
答案
Object value = getModel().getValueAt(rowIndex,columnIndex);
模型中的数据从不排序,只对视图进行排序。
所以你应该使用:
Object value = getValueAt(rowIndex, columnIndex);
那是从视图中获取数据。视图知道排序顺序并返回正确的值。
以上是关于背景排序JTable后,特定值的颜色不会改变的主要内容,如果未能解决你的问题,请参考以下文章