将日期定位在JTable中的单元格中

时间:2015-03-25 17:19:24

标签: java swing jtable

在我的表中,我有三行代码,除了最后一列之外,它还输入了JTable中的所有数据。但是我不确定为什么。

   `DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment( SwingConstants.CENTER );
    myTable.setDefaultRenderer(Object.class, centerRenderer);`

Shows centered columns

我认为这是因为我使用单独的“DefaultTableCellRenderer”来排序我的日期,但我不确定。

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
import java.awt.event.*;
///////////
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import javax.swing.text.Document;
import javax.swing.table.TableRowSorter;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
///////////
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.table.*;

public class JtableIe
{
    JFrame myMainWindow = new JFrame("Compare Tables");

    JPanel  firstPanel = new JPanel();

    JScrollPane myScrollTable;
    JTable myTable;
    JTextField srchFld1;
    JTextField srchFld2;
    TableRowSorter sorter;
    JLabel srchLbl1 = new JLabel();
    JLabel srchLbl2 = new JLabel();
    DefaultTableModel model;

    public void runGUI()
    {
        myMainWindow.setBounds(10, 10, 1296, 756);

        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        myMainWindow.setLayout(new GridLayout(1,1));

        createFirstPanel();

        myMainWindow.getContentPane().add(firstPanel);

        myMainWindow.setVisible(true);
    }

    public void createFirstPanel()
    {
        firstPanel.setLayout(null);

        srchLbl1.setLocation(0,0);
        srchLbl1.setSize(150,26);
        srchLbl1.setText("Name Search:");
        firstPanel.add(srchLbl1);

        srchLbl2.setLocation(660,0);
        srchLbl2.setSize(150,26);
        srchLbl2.setText("ID Search:");
        firstPanel.add(srchLbl2);

        String[] aHeaders = {"Name","ID","Number 1","Number 2","Time","Date"};
        Object[][] aData = new Object[15][6];

        ///////Data////////
        aData[0][0] = "John";
        aData[0][1] = "JS96";
        aData[0][2] = "1";
        aData[0][3] = "186";
        aData[0][4] = "1h 23m";
        aData[0][5] = getJavaDate("12-11-2015");

        aData[1][0] = "David";
        aData[1][1] = "DB36";
        aData[1][2] = "2";
        aData[1][3] = "111852";
        aData[1][4] = "2h 55m";
        aData[1][5] = getJavaDate("12-11-2020");

        aData[2][0] = "Daniel";
        aData[2][1] = "DK73";
        aData[2][2] = "3";
        aData[2][3] = "2921";
        aData[2][4] = "1h 55m";
        aData[2][5] = getJavaDate("12-11-2014");

        aData[3][0] = "Janis";
        aData[3][1] = "JW84";
        aData[3][2] = "4";
        aData[3][3] = "6512";
        aData[3][4] = "12h 26m";
        aData[3][5] = getJavaDate("13-11-2015");

        aData[4][0] = "Adam";
        aData[4][1] = "AF98";
        aData[4][2] = "5";
        aData[4][3] = "7524";
        aData[4][4] = "5h 47m";
        aData[4][5] = getJavaDate("11-11-2015");

        aData[5][0] = "Matthew";
        aData[5][1] = "MB55";
        aData[5][2] = "6";
        aData[5][3] = "4989";
        aData[5][4] = "80h 30m";
        aData[5][5] = getJavaDate("11-11-2015");

        aData[6][0] = "Lewis";
        aData[6][1] = "LS23";
        aData[6][2] = "7";
        aData[6][3] = "56321";
        aData[6][4] = "880h 20m";
        aData[6][5] = getJavaDate("11-11-2015");

        aData[7][0] = "Mark";
        aData[7][1] = "ML49";
        aData[7][2] = "8";
        aData[7][3] = "97456";
        aData[7][4] = "8h 42m";
        aData[7][5] = getJavaDate("11-11-2015");

        aData[8][0] = "Josh";
        aData[8][1] = "JT67";
        aData[8][2] = "9";
        aData[8][3] = "82135";
        aData[8][4] = "56h 13m";
        aData[8][5] = getJavaDate("11-11-2015");

        aData[9][0] = "Oliver";
        aData[9][1] = "OC98";
        aData[9][2] = "10";
        aData[9][3] = "152";
        aData[9][4] = "9h 9m";
        aData[9][5] = getJavaDate("11-11-2015");

        aData[10][0] = "Tom";
        aData[10][1] = "TS97";
        aData[10][2] = "11";
        aData[10][3] = "100";
        aData[10][4] = "0h 0m";
        aData[10][5] = getJavaDate("11-11-2015");

        aData[11][0] = "Emma";
        aData[11][1] = "EBS74";
        aData[11][2] = "12";
        aData[11][3] = "200";
        aData[11][4] = "0h 30m";
        aData[11][5] = getJavaDate("11-11-2015");

        aData[12][0] = "Lucy";
        aData[12][1] = "LK02";
        aData[12][2] = "13";
        aData[12][3] = "256";
        aData[12][4] = "7h 00m";
        aData[12][5] = getJavaDate("10001-11-2015");

        aData[13][0] = "Patrick";
        aData[13][1] = "PM38";
        aData[13][2] = "14";
        aData[13][3] = "258";
        aData[13][4] = "2h 00m";
        aData[13][5] = getJavaDate("31-02-2016");

        aData[14][0] = "Nicola";
        aData[14][1] = "NB70";
        aData[14][2] = "15";
        aData[14][3] = "987";
        aData[14][4] = "100h 56m";
        aData[14][5] = getJavaDate("31-02-2015");
        //////////////
        model = new DefaultTableModel(aData, aHeaders)
        {
            @Override
            public Class<?> getColumnClass(int column) 
            {
                switch (column)
                {
                    case 5: return Date.class;
                    default: return Object.class;
                }
            }

            @Override
            public boolean isCellEditable(int row, int column) 
            {
               //all cells false
               return false;
            }
        };

        myTable = new JTable(model);

        myTable.setAutoCreateRowSorter(true);

        sorter = new TableRowSorter(myTable.getModel());
        List sortKeys = new ArrayList();
        sortKeys.add(new RowSorter.SortKey(5, SortOrder.ASCENDING));
        sorter.setSortKeys(sortKeys);
        sorter.setComparator(2, new AlphanumComparator());
        sorter.setComparator(3, new AlphanumComparator());
        sorter.setComparator(4, new AlphanumComparator());
        setRenderers();
        myTable.setRowSorter(sorter);

        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( SwingConstants.CENTER );
        myTable.setDefaultRenderer(Object.class, centerRenderer);

        DefaultRowSorter sorter = (DefaultRowSorter) myTable.getRowSorter();

        myTable.getColumnModel().getColumn(0).setMinWidth(50);
        myTable.getColumnModel().getColumn(0).setMaxWidth(100);
        myTable.getColumnModel().getColumn(0).setPreferredWidth(75);



        myScrollTable = new JScrollPane(myTable); 
        myScrollTable.setSize(1296,756); 
        myScrollTable.setLocation(0,25); 
        System.out.println("Creating compare table");

        srchFld1 = new JTextField(10);
        srchFld1.setSize(550,26); 
        srchFld1.setLocation(100,0);
        srchFld1.setToolTipText("Enter Name");
        firstPanel.add(srchFld1);

        srchFld2 = new JTextField(10);
        srchFld2.setSize(550,26); 
        srchFld2.setLocation(740,0);
        srchFld2.setToolTipText("Enter ID");
        firstPanel.add(srchFld2);

        //////////////////////
        Document doc = srchFld1.getDocument();
        DocumentListener listener = new DocumentListener() 
        {

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

            @Override
            public void removeUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void changedUpdate(DocumentEvent e) 
            {
                newFilter();
            }
        };
        doc.addDocumentListener(listener);

        ///////////////
        Document docb = srchFld2.getDocument();
        DocumentListener listenerb = new DocumentListener() {

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

            @Override
            public void removeUpdate(DocumentEvent e) 
            {
                newFilter();
            }

            @Override
            public void changedUpdate(DocumentEvent e) 
            {
                newFilter();
            }
        };
        docb.addDocumentListener(listenerb);
        ///////////////

        firstPanel.add(myScrollTable);
    }

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");

    private void setRenderers() 
    {
        myTable.setDefaultRenderer(Date.class, new DateRenderer());
    }

    private Date getJavaDate(String s) 
    {
        try 
        {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            Date d = sdf.parse(s);
            return d;
        } 

        catch (ParseException ex) 
        {
            Logger.getLogger(TableBasic.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    private void newFilter()
    {
        RowFilter rf = null;
        try 
        {
            List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
            filters.add(RowFilter.regexFilter(srchFld1.getText(), 0));
            filters.add(RowFilter.regexFilter(srchFld2.getText(), 1));
            rf = RowFilter.andFilter(filters);
        } 
        catch (java.util.regex.PatternSyntaxException e) 
        {
            return;
        }
        sorter.setRowFilter(rf);
    }

    public static void main(String[] args)
    {
        JtableIe ji = new JtableIe();
        ji.runGUI();
    }

    private class DateRenderer extends DefaultTableCellRenderer 
    {

        private static final long serialVersionUID = 1L;

        @Override
        public Component getTableCellRendererComponent(JTable myTable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(myTable, value, isSelected, hasFocus, row, column);
            if (!(value instanceof Date)) {
                return this;
            }
            setText(DATE_FORMAT.format((Date) value));
            return this;
        }
    }
}

我尝试使用此代码

来解决此问题

DefaultTableCellRenderer centerRendererd = new DefaultTableCellRenderer(); centerRendererd.setHorizontalAlignment( JLabel.CENTER ); myTable.getColumnModel().getColumn(5).setCellRenderer( centerRendererd );

然而,它删除了日期的格式,我不想发生。

我将非常感谢您在修复此错误并将“日期”列置于中心而不会丢失任何指定的格式时提供任何帮助。感谢。

2 个答案:

答案 0 :(得分:2)

您尚未在用于日期列的DateRenderer上设置水平对齐方式。例如,在setRenderers方法中:

DateRenderer dr = new DateRenderer();
dr.setHorizontalAlignment(JLabel.CENTER);
myTable.setDefaultRenderer(Date.class, dr);

答案 1 :(得分:1)

对我来说很好:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.awt.geom.*;

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        JTable table = new JTable(5, 5);
        table.setValueAt("Center", 0, 0);

        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( JLabel.CENTER );
        table.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );

        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new SSCCE() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}

我发布了更多内容作为SSCCE应该是什么的示例。