java - 将模型添加到表数组中的每个表,但仅填充迭代中的最后一个表
问题描述
我有一个定制的(类似 Excel 的)表头。每个标题包括 2 个标签、一个列名和一个图标,按下该图标会打开一个过滤器面板。每个过滤器面板都应该有一个包含两列的表格。一个是布尔类型,另一个保存要过滤的列中的所有值。过滤器的外观:
当程序运行时,它会创建 13 个分层过滤面板。面板中的表格应使用其表格模型填充每个表格,但仅填充最后一个表格。前 12 个表的行数正确,但为空。谁能帮我理解我做错了什么?面板的显示方式:
public CustomTable(String sQLTableName,int sqlColumnCount, String[] sQLColumns,String[] sqlLabelNames,String whereClause) {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1600, 800);
this.setVisible(true);
mainPanel = new JLayeredPane();
this.setContentPane(mainPanel);
totalPanel= new JPanel();totalPanel.setLayout(new FlowLayout(FlowLayout.CENTER,30,5));
mainPanel.setLayout(new BorderLayout());
//setContentPane(mainPanel);
scroll= new JScrollPane();scroll.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
obtainMetadataInfo(sQLTableName,sqlColumnCount, sQLColumns, sqlLabelNames, whereClause);
setMaintable(createInternalTable());
getMaintable().getColumnModel().addColumnModelListener(this);
panelFilter = createFilterPanel();
scroll.setViewportView(getMaintable());
mainPanel.add(scroll);
columnMarginChanged(new ChangeEvent(getMaintable().getColumnModel()));
mainPanel.add(panelFilter, BorderLayout.NORTH);mainPanel.add(totalPanel,BorderLayout.SOUTH);
totalMinsTxt = new JTextField("£ 10000.00");totalLabourCostTxt= new JTextField("£ 10000.00"); totalMaterialCostTxt = new JTextField("£ 10000.00"); totalCostTxt = new JTextField("£ 10000.00");
totalMinsLb=new JLabel("Total Minutes");totalLabourCostLb= new JLabel("Total Labour Cost");totalMaterialCostLb= new JLabel("Total Material Cost");totalCostLb = new JLabel("Total Cost");
totalPanel.add(totalMinsLb);totalPanel.add(totalMinsTxt);
totalPanel.add(totalLabourCostLb);totalPanel.add(totalLabourCostTxt);
totalPanel.add(totalMaterialCostLb);totalPanel.add(totalMaterialCostTxt);
totalPanel.add(totalCostLb);totalPanel.add(totalCostTxt);
}
public JPanel createFilterPanel(){
JPanel panel = new JPanel(); // Panel to hold all the Column Header labels
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
Font font = new Font("New Times Romen", Font.BOLD, 12);
filterPanels =new Box[SQLTableImport.getColumnCount()];// containers to hold the name of the column and the filter icon
filterText = new JLabel[SQLTableImport.getColumnCount()];// an array to hold the column header labels
filterIcons =new JLabel[SQLTableImport.getColumnCount()]; //an array to hold the filter icons
models =new DefaultTableModel[SQLTableImport.getColumnCount()];// an array to hold the table models to be added to each table in the filter panel
allFilterPanels = new FilterPanel[SQLTableImport.getColumnCount()]; // an array to hold the object of the FilterPanel class
for(int i = 0;i<SQLTableImport.getColumnCount();i++){
filterPanels[i] = Box.createHorizontalBox(); // create one container for each number of SQL columns
filterText[i] = new JLabel(SQLTableImport.getColumnNames()[i]); // create a label for each number of SQL columns to hold the column name
filterText[i].setHorizontalAlignment(SwingConstants.RIGHT);
filterIcons[i] = new JLabel(new ImageIcon(Icons.EXPAND));// create a label for each number of SQL columns to hold the expand icons
setColumnIndex(i);
SQLTableImport.setSqlSelectedType(SQLTableImport.getSqlColumnType()[getColumnIndex()]); // set the SQL object type
SQLTableImport.setSqlColumnName(SQLTableImport.getSqlColumnNames()[CustomTable.getColumnIndex()]); // set the SQL column name
FilterPanel.setTableColumnName(SQLTableImport.getColumnNames()[getColumnIndex()]);// set the SQL lable column name
String iconDescriptionColumn ="CASE WHEN non_conformances.Status='Complete' THEN (select Name from `icons` where ID='1' )WHEN `Deadline`> DATE(NOW()) and `Status`<>'Complete' THEN (select Name from `icons`"
+ " where ID='3')ELSE (select Name from `icons` where ID='2')END ";
model = new SQLTableImport(iconDescriptionColumn).getFilterModelFromSqlTable(); // model to be added in the filter table
models[i] = model; //add all the model in an array
allFilterPanels[i]= new FilterPanel(SQLTableImport.getSqlColumnType()[i]);
//((AbstractTableModel) allFilterPanels[i].getTableSearch().getModel()).fireTableDataChanged();
mainPanel.add(allFilterPanels[i]);
mainPanel.setLayer(allFilterPanels[i],new Integer(i),0);
allFilterPanels[i].setVisible(false);
filterIcons[i].setBorder(new LineBorder(new Color(0, 0, 0)));filterIcons[i].setOpaque(true);filterIcons[i].setBackground(SystemColor.menu);
final int index=i;
filterPanels[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
filterPanels[index].setOpaque(true);
filterPanels[index].setBackground(new Color(51,98,140));
filterText[index].setForeground(Color.WHITE);
}
@Override
public void mouseExited(MouseEvent arg0) {
filterPanels[index].setOpaque(true);
filterPanels[index].setBackground(new Color(214,217,223));
filterText[index].setForeground(Color.BLACK);
}
@Override
public void mouseClicked(MouseEvent arg0) {
setFiltersInvisible(allFilterPanels);
filterIcons[index].setOpaque(true);
if(isSort){ //**************************************** create a map with index and true/false values to change the icons properly*******************
getMaintable().setModel(getMainModel().sortMainTable("ASC"));
filterIcons[index].setIcon(new ImageIcon(Icons.SELECTED_EXPAND));
isSort = false;
}
else{
getMaintable().setModel(getMainModel().sortMainTable("DESC"));
filterIcons[index].setIcon(new ImageIcon(Icons.EXPAND));
isSort = true;
}
}
});
filterIcons[i].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
filterIcons[index].setOpaque(true);
filterIcons[index].setBackground(new Color(51,98,140));
setxCoordonateOnScreen(filterPanels[index].getX()+filterPanels[index].getWidth()-250); //set the x coordinate where the filter frame will be positioned
setyCoordonateOnScreen(filterPanels[index].getY()+(filterPanels[index].getHeight()*2)-2);
setTableWidth(panel.getWidth());
allFilterPanels[index].setVisible(true);
allFilterPanels[index].setLocation(getxCoordonateOnScreen(), getyCoordonateOnScreen());
}
@Override
public void mouseReleased(MouseEvent arg0) {
filterIcons[index].setOpaque(true);
filterIcons[index].setBackground(SystemColor.menu);
}
});
filterText[i].setFont(font);
filterPanels[i].add(filterText[i]);
filterPanels[i].add(Box.createHorizontalGlue());
filterPanels[i].add(filterIcons[i]);
panel.add(filterPanels[i]);
}
return panel;
}
public class FilterPanel extends JPanel{
public FilterPanel(String sqlType) {
if(sqlType.equals("DATE")){ // if the column type is date it creates a specific panel for filtering dates
createBasicFrame(); //create the frame, set the Content Pane,set the background colour, set the GridBagLayout, sets the close button
addDatePanelComponents(); // create the panel and add all the components for date frame
addBasicComponents();
adjustBasicComponents();
adjustDatePanel();
}
else if(sqlType.equals("BLOB")|| sqlType.equals("TINYINT")){// creates a specific panel for filtering icons and check boxes
createBasicFrame();
addBasicComponents();
addSearchTable();
adjustBasicComponents();
adjustSearchTable();
}
else{// the default filter panel
createBasicFrame();
addBasicComponents();
adjustBasicComponents();
addSearchTable();
addSearchPanel();
adjustTheSearchPanel();
adjustSearchTable();
}
}
public void addSearchTable( ){
setTableSearch(new JTable());
getTableSearch().setModel(CustomTable.models[CustomTable.getColumnIndex()]);// set the model to the search table from the array of models which is obtain from SQLTableImport class
adjustTable();
searchScroll = new JScrollPane();
searchScroll.setViewportView(getTableSearch());
}
public void adjustSearchTable(){
/////////Third Row////////
addComp(this, searchScroll, 0, 3, 5,1, 0, 4.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH);
}
public void adjustBasicComponents(){
//////First Row//////
addComp(this, title, 0, 0, 5,1, 1, 0.1, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE);
addComp(this, closeLabel, 1, 0, 1,1, 1, 0.1, GridBagConstraints.FIRST_LINE_END, GridBagConstraints.NONE);
//////////Second Row//////////
addComp(this, cleareIcon, 0, 1, 1,1, 1, 0.1, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE);
addComp(this, clearTxt, 1, 1, 1,1, 2, 0.1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL);
/////Last Row//////
addComp(this, cancelBt, 0, 4, 2,1, 1, 0.1, GridBagConstraints.EAST, GridBagConstraints.NONE);
addComp(this, okBt, 1, 4, 1,1, 1, 0.1, GridBagConstraints.CENTER, GridBagConstraints.NONE);
}
private void addComp(JPanel thePanel, JComponent comp, int xPos, int yPos, int gridW, int gridH,double compWidth,double compHeight, int place, int stretch){
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = xPos;// Define the x position of the component
gridConstraints.gridy = yPos;// Define the y position of the component
gridConstraints.gridwidth = gridW;// Number of columns the component takes up
gridConstraints.gridheight = gridH;// Number of rows the component takes up
gridConstraints.weightx = compWidth;// Gives the layout manager a hint on how to adjust component width (0 equals fixed)
gridConstraints.weighty = compHeight;// Gives the layout manager a hint on how to adjust component height (0 equals fixed)
gridConstraints.insets = new Insets(5,5,5,5);// Defines padding top, left, bottom, right
gridConstraints.anchor = place;// Defines where to place components if they don't fill the space: CENTER, NORTH, SOUTH, EAST, WEST NORTHEAST, etc.
gridConstraints.fill = stretch;// How should the component be stretched to fill the space: NONE, HORIZONTAL, VERTICAL, BOTH
thePanel.add(comp, gridConstraints);
}
}
public class SQLTableImport {
//***********Constructor for Filter Table export (2 columns Check box and string)**********
public SQLTableImport(String descriptionColumn){
if(getSqlSelectedType().equals("BLOB")){
setSql("SELECT DISTINCT "+getSqlColumnName()+" , "+descriptionColumn+" FROM `"+ getTableName() +"`"+whereClause+"");
}
else{
setSql("SELECT DISTINCT "+getSqlColumnName()+" FROM `"+ getTableName() +"`"+whereClause+"");
}
}
//***********METHOD FOR RETURNING THE MODEL FOR A FILTER FRAME 1 COLUMN AND 1 CHECKBOX COLUMN
public DefaultTableModel getFilterModelFromSqlTable(){
if(getSqlSelectedType().equals("BLOB")){emptyHeaders= new Object[][]{null,null,null};}
DefaultTableModel dFilterTableModel = new DefaultTableModel(emptyrows, emptyHeaders){
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int column) {
return column == 0;
}
public Class <?> getColumnClass(int column) {
if(column==0){
return Boolean.class;
}
if(column==2){
return String.class;
}
switch (getSqlColumnType()[CustomTable.getColumnIndex()]) {
case "VARCHAR":
return String.class;
case "INT":
return Integer.class;
case "DECIMAL":
return Double.class;
case "DATE":
return Date.class;
case "TINYINT":
return String.class;
case "BLOB":
return Icon.class;
default:
return Object.class;
}
}
};
try {
setPst(Utilities.sqlConnnect().prepareStatement(getSql()));
setRs(getPst().executeQuery(getSql()));
java.sql.ResultSetMetaData tempResult = getPst().getMetaData();
int tempColumnCount = tempResult.getColumnCount();
Object[] tempRow= new Object[tempColumnCount+1];
while(getRs().next()){
// Gets the column values based on class type expected
tempRow[0]= false;
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("VARCHAR")){
tempRow[tempColumnCount]= getRs().getString(tempColumnCount);
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("INT")){
tempRow[tempColumnCount]= getRs().getInt(tempColumnCount);
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("DECIMAL")){
tempRow[tempColumnCount]= getRs().getDouble(tempColumnCount);
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].toString().equals("DATE")){
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("TINYINT")){
tempRow[tempColumnCount]= getRs().getBoolean(tempColumnCount);
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("BLOB")){
Blob blob = getRs().getBlob(tempColumnCount-1);
ImageIcon icon = null;
try (InputStream is = blob.getBinaryStream()) {
BufferedImage img = ImageIO.read(is);
icon = new ImageIcon(img.getScaledInstance(17, 17, Image.SCALE_SMOOTH));
}
tempRow[tempColumnCount-1] =icon;
tempRow[tempColumnCount]= getRs().getString(tempColumnCount);
}
// Adds the row of data to the end of the model
dFilterTableModel.addRow(tempRow);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,e);
}
finally {
try {
getPst().close();
getRs().close();
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null,e1);
}
}
return dFilterTableModel;}
}
解决方案
当程序运行时,它会创建 13 个分层过滤面板。面板中的表格应使用其表格模型填充每个表格,但仅填充最后一个表格。
searchScroll = new JScrollPane();
searchScroll.setViewportView(getTableSearch());
我看不到您将滚动窗格添加到面板的位置。
您不能只创建 13 个滚动窗格而不将每个滚动窗格单独添加到面板中。
“searchScroll”变量只能引用最后一个创建的变量,我猜你为什么只看到最后一个表。