JTable列标签无法打印

时间:2017-12-11 04:02:47

标签: java swing printing jtable

我有一个JTable,用于显示数据库中的数据作为打印预览。我可以让它打印出我想要的东西,除了列标题不会打印,无论我尝试什么。我将我的JTable添加到JScrollPane,我甚至将我的JScrollPane添加到另一个JPanel,它被添加到另一个JPanel中,包含所有内容.setVisible(true)。

在广泛浏览Google之后,我发现的唯一解决方案是here,但我已经按照他们所说的做了。到目前为止,这是我的代码:

public class PrintPreview extends JDialog implements ActionListener
{
private JTable infoTable;


private boolean printed;
private int windowWidth;
private int windowHeight;

JPanel scrollerPanel;
JPanel dataPanel;

private int[] idList;
private Connection conn;

private JScrollPane scroller;
private JButton printButton;


public PrintPreview(int[] tIds, Connection tConn)
{
    printed = false;

    idList = tIds;
    conn = tConn;

    setupFrame();
    setupScroller();
    setupButtons();

    this.pack();
    this.setVisible (true);
}

//returns true if printed, false otherwise
public boolean getCloseValue()
{
    return printed;
}

private void setupFrame()
{
    this.setTitle("Edit Data");
    this.setSize (800, 700); //Width, Height
    this.setLocationRelativeTo(null); //Centers the JFrame on the screen
    this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
    this.setResizable(false);
    this.setModalityType(APPLICATION_MODAL);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    //Gets the size of the contentPanel of the frame
    Insets inset = this.getInsets();
    windowWidth  = this.getSize().width  - (inset.left + inset.right);
    windowHeight = this.getSize().height - (inset.top  + inset.bottom);
}


private void setupScroller()
{
    scrollerPanel = new JPanel();

    scroller = new JScrollPane (setupTable(), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    infoTable.setFillsViewportHeight(true); 

    scroller.setSize(windowWidth, windowHeight - 120);
    scroller.setMinimumSize(new Dimension (windowWidth, windowHeight - 120));
    scroller.setMaximumSize(new Dimension (windowWidth, windowHeight - 120));
    scroller.setPreferredSize(new Dimension (windowWidth, windowHeight - 120));

    scroller.setVisible(true);//*********************************************************
    scroller.add (setupTable());


    this.add (scroller);
}


private void setupButtons()
{
    JPanel spacer1 = new JPanel();
    spacer1.setSize(100, 20);
    spacer1.setMaximumSize(new Dimension (100, 20));
    spacer1.setMinimumSize(new Dimension (100, 20));
    spacer1.setPreferredSize(new Dimension (100, 20));

    JPanel spacer2 = new JPanel();
    spacer2.setSize(100, 20);
    spacer2.setMaximumSize(new Dimension (100, 20));
    spacer2.setMinimumSize(new Dimension (100, 20));
    spacer2.setPreferredSize(new Dimension (100, 20));

    printButton = new JButton ("Print");
    printButton.setFont((new Font("", Font.BOLD, 14)));
    printButton.setSize(new Dimension (130, 35));
    printButton.setMaximumSize(new Dimension (130, 35));
    printButton.setMinimumSize(new Dimension (130, 35));
    printButton.setPreferredSize(new Dimension (130, 35));
    printButton.addActionListener(this);

    spacer1.setAlignmentX(Component.CENTER_ALIGNMENT);
    printButton.setAlignmentX(Component.CENTER_ALIGNMENT);


    this.add (spacer1);
    this.add (printButton);
    this.add (spacer2);
}


private JTable setupTable()
{
    infoTable = new JTable();

    DefaultTableModel dm = new DefaultTableModel(0, 0);
    String header[] = new String[] {"Case #", "Date", "Officer #", "Offence",
                                    "Description", "Report"};
    dm.setColumnIdentifiers(header);
    infoTable.setModel(dm);
    infoTable.setRowHeight(26);
    infoTable.setFocusable(false);//display only

    //Adds everything to the table
    int idSize = idList.length;
    for (int x = 0; x < idSize; x++)
    {
        try
        {
            String[] values = getInfo(idList[x]);
            values[4] = values[4].trim();
            values[4] = values[4].replaceAll("<html>", "");

            dm.addRow(values);
        }
        catch (SQLException e)
        {
            System.out.println ("Error: " + e);
            System.out.println ("Event-addObjects(): Problem with getting event info");
        }

        infoTable.setFont(new Font("Serif", Font.PLAIN, 10));
    }

    //Centers the values on the smaller columns
    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment(JLabel.CENTER);
    infoTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
    infoTable.getColumnModel().getColumn(1).setCellRenderer(centerRenderer);
    infoTable.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
    infoTable.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
    infoTable.getColumnModel().getColumn(5).setCellRenderer(centerRenderer);

    //Sets the sizes of the columns
    infoTable.getColumnModel().getColumn(0).setMinWidth(40);
    infoTable.getColumnModel().getColumn(1).setMinWidth(65);
    infoTable.getColumnModel().getColumn(2).setMinWidth(40);
    infoTable.getColumnModel().getColumn(3).setMinWidth(80);
    infoTable.getColumnModel().getColumn(4).setMinWidth(250);
    infoTable.getColumnModel().getColumn(5).setMinWidth(50);

    //Makes the Description column cells JTextFields
    infoTable.getColumnModel().getColumn(4).setCellRenderer(new VariableRowHeightRenderer());

    //Looks at the size each JTextField would like to be and changes the rows to accomidate
    int column = 4;
    for (int row = 0; row < infoTable.getRowCount(); row++)
    {
        int rowHeight = 26;

        Component comp = infoTable.prepareRenderer(infoTable.getCellRenderer(row, column), row, column);
        rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);

        if(rowHeight != infoTable.getRowHeight(row))
        {
            infoTable.setRowHeight(row, rowHeight);
        }
    }
    infoTable.setVisible(true);//***********************************************************************
    return infoTable;
}


private String[] getInfo(int id) throws SQLException
{
    String result[];
    ResultSet rs;
    String command = "SELECT * FROM Logs_Table where id = " + id;
    Statement stmt = conn.createStatement();

    rs = stmt.executeQuery(command);

    result = new String[] {rs.getString("Case_Num"), rs.getString("Event_Date"),
                           rs.getString("Officer_Num"), rs.getString("Offence"),
                           ("<html>" + rs.getString("Description") + "<html>"),
                           rs.getString("Report")};

    return result;
}

@Override
public void actionPerformed(ActionEvent e)
{
    String cmd = e.getActionCommand();

    switch (cmd)
    {
        case "Print":
            printed = true;

            try
            {

                infoTable.setSize(infoTable.getPreferredSize());

                //Makes the margins smaller
                PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                aset.add (new MediaPrintableArea((float)8.25, (float)10.0, (float)8.5, (float)11.0, MediaPrintableArea.INCH));

                MessageFormat empty = new MessageFormat ("");
                MessageFormat footerFormat = new MessageFormat("- {0} -");

                infoTable.print (PrintMode.FIT_WIDTH, empty, footerFormat, true, aset, false);
            }
            catch (PrinterException ex)
            {
                System.out.println ("Error: " + ex);
                System.out.println ("Built in table print didnt work");
            }

            //this.dispose();
            break;

        default:
            break;    
    }
}   

private class VariableRowHeightRenderer extends JTextArea implements TableCellRenderer
{
    public VariableRowHeightRenderer()
    {
        super();
        this.setEditable(false);
        this.setLineWrap(true);
        this.setWrapStyleWord(true);
        this.setWrapStyleWord(true);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                   boolean hasFocus, int row, int column)
    {
        this.setBackground(Color.WHITE);

        this.setText((String) (value));
        this.setSize(table.getColumnModel().getColumn(column).getWidth(),
                     Short.MAX_VALUE);

        return this;
    }
}
}

有人可以告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

好吧,经过多次拧紧后,我得到了一些东西&#34;上班。 &#34;核心&#34;问题似乎归结为

  • 创建JTable
  • 的多个实例
  • &#34;添加&#34; JTableJScrollPanescroller.add(setupTable());),将其设置为屏幕窗格的视口
  • 另外,需要使用不必要的UI元素,这使得理解代码变得更加困难

此示例只是将输出转储到文件中,但它应该可以正常打印。

Print

import java.awt.Color;
import java.awt.Component;
import static java.awt.Dialog.ModalityType.APPLICATION_MODAL;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.text.MessageFormat;
import javax.imageio.ImageIO;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class PrintPreview extends JDialog implements ActionListener {

    public static void main(String[] args) {
        new PrintPreview(new int[]{1, 2, 3, 4}, null);
    }

    private JTable infoTable;

    private boolean printed;
    private int windowWidth;
    private int windowHeight;
    JPanel container;
//    JPanel scrollerPanel;
    JPanel dataPanel;

    private int[] idList;
    private Connection conn;

    private JScrollPane scroller;
    private JButton printButton;

    JTable printable;

    public PrintPreview(int[] tIds, Connection tConn) {
        container = new JPanel();
        container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
        printed = false;

        idList = tIds;
        conn = tConn;

        setupFrame();
        setupScroller();
        setupButtons();

        this.setContentPane(container);
        this.pack();
        this.setVisible(true);
    }

//returns true if printed, false otherwise
    public boolean getCloseValue() {
        return printed;
    }

    private void setupFrame() {
        this.setTitle("Edit Data");
        this.setSize(800, 700); //Width, Height
        this.setLocationRelativeTo(null); //Centers the JFrame on the screen
        this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
//        this.setResizable(false);
        this.setModalityType(APPLICATION_MODAL);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        //Gets the size of the contentPanel of the frame
        Insets inset = this.getInsets();
        windowWidth = this.getSize().width - (inset.left + inset.right);
        windowHeight = this.getSize().height - (inset.top + inset.bottom);
    }

    private void setupScroller() {
//        scrollerPanel = new JPanel();

        scroller = new JScrollPane(setupTable());

//        scroller = new JScrollPane(setupTable(), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
//                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

//        infoTable.setFillsViewportHeight(true);

//        scroller.setSize(windowWidth, windowHeight - 120);
//        scroller.setMinimumSize(new Dimension(windowWidth, windowHeight - 120));
//        scroller.setMaximumSize(new Dimension(windowWidth, windowHeight - 120));
//        scroller.setPreferredSize(new Dimension(windowWidth, windowHeight - 120));

//        scroller.setVisible(true);//*********************************************************
//        scroller.add(setupTable());
//        scrollerPanel.add(scroller);
//        scrollerPanel.setVisible(true);//******************************************************
//        scrollerPanel.setOpaque(true);//*************************************************************

        container.add(scroller);
    }

    private void setupButtons() {
        JPanel spacer1 = new JPanel();
        spacer1.setSize(100, 20);
        spacer1.setMaximumSize(new Dimension(100, 20));
        spacer1.setMinimumSize(new Dimension(100, 20));
        spacer1.setPreferredSize(new Dimension(100, 20));

        JPanel spacer2 = new JPanel();
        spacer2.setSize(100, 20);
        spacer2.setMaximumSize(new Dimension(100, 20));
        spacer2.setMinimumSize(new Dimension(100, 20));
        spacer2.setPreferredSize(new Dimension(100, 20));

        printButton = new JButton("Print");
        printButton.setFont((new Font("", Font.BOLD, 14)));
        printButton.setSize(new Dimension(130, 35));
        printButton.setMaximumSize(new Dimension(130, 35));
        printButton.setMinimumSize(new Dimension(130, 35));
        printButton.setPreferredSize(new Dimension(130, 35));
        printButton.addActionListener(this);

        spacer1.setAlignmentX(Component.CENTER_ALIGNMENT);
        printButton.setAlignmentX(Component.CENTER_ALIGNMENT);

        container.add(spacer1);
        container.add(printButton);
        container.add(spacer2);
    }

    private JTable setupTable() {
        infoTable = new JTable();

        DefaultTableModel dm = new DefaultTableModel(0, 0);
        String header[] = new String[]{"Case #", "Date", "Officer #", "Offence",
            "Description", "Report"};
        dm.setColumnIdentifiers(header);
        infoTable.setModel(dm);
        infoTable.setRowHeight(26);
        infoTable.setFocusable(false);//display only

        //Adds everything to the table
        int idSize = idList.length;
        for (int row = 0; row < 10; row++) {
            String value = Integer.toString(row);
            String[] values = new String[]{value, value, value, value, value, value};
            dm.addRow(values);
        }

//        for (int x = 0; x < idSize; x++) {
//            try {
//                String[] values = getInfo(idList[x]);
//                values[4] = values[4].trim();
//                values[4] = values[4].replaceAll("<html>", "");
//
//                dm.addRow(values);
//            } catch (SQLException e) {
//                System.out.println("Error: " + e);
//                System.out.println("Event-addObjects(): Problem with getting event info");
//            }
//
//            infoTable.setFont(new Font("Serif", Font.PLAIN, 10));
//        }
        //Centers the values on the smaller columns
//        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
//        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
//        infoTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
//        infoTable.getColumnModel().getColumn(1).setCellRenderer(centerRenderer);
//        infoTable.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
//        infoTable.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
//        infoTable.getColumnModel().getColumn(5).setCellRenderer(centerRenderer);
//
//        //Sets the sizes of the columns
//        infoTable.getColumnModel().getColumn(0).setMinWidth(40);
//        infoTable.getColumnModel().getColumn(1).setMinWidth(65);
//        infoTable.getColumnModel().getColumn(2).setMinWidth(40);
//        infoTable.getColumnModel().getColumn(3).setMinWidth(80);
//        infoTable.getColumnModel().getColumn(4).setMinWidth(250);
//        infoTable.getColumnModel().getColumn(5).setMinWidth(50);

        //Makes the Description column cells JTextFields
//        infoTable.getColumnModel().getColumn(4).setCellRenderer(new VariableRowHeightRenderer());
        //Looks at the size each JTextField would like to be and changes the rows to accomidate
//        int column = 4;
//        for (int row = 0; row < infoTable.getRowCount(); row++) {
//            int rowHeight = 26;
//
//            Component comp = infoTable.prepareRenderer(infoTable.getCellRenderer(row, column), row, column);
//            rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
//
//            if (rowHeight != infoTable.getRowHeight(row)) {
//                infoTable.setRowHeight(row, rowHeight);
//            }
//        }
//        infoTable.setVisible(true);//***********************************************************************
        return infoTable;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();

        switch (cmd) {
            case "Print":
                printed = true;

                //Makes the margins smaller
                PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                aset.add(new MediaPrintableArea((float) 8.25, (float) 10.0, (float) 8.5, (float) 11.0, MediaPrintableArea.INCH));

                MessageFormat empty = new MessageFormat("");
                MessageFormat footerFormat = new MessageFormat("- {0} -");

//                    printable.print(PrintMode.FIT_WIDTH, empty, footerFormat, true, aset, false);
                Paper paper = new Paper();
                paper.setImageableArea(0, 0, 700, 890);
                paper.setSize(700, 890);

                PageFormat format = new PageFormat();
                format.setPaper(paper);
                format.setOrientation(PageFormat.PORTRAIT);

//        printjob.setPrintable(printable, format);
                BufferedImage img = new BufferedImage(700, 890, BufferedImage.TYPE_INT_RGB);
                Graphics2D g2d = img.createGraphics();
                g2d.setColor(Color.WHITE);
                g2d.fill(new Rectangle(0, 0, 890, 700));

                Printable printable = infoTable.getPrintable(JTable.PrintMode.FIT_WIDTH, null, null);
                try {
                    printable.print(g2d, format, 0);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
                g2d.dispose();

                try {
                    ImageIO.write(img, "png", new File("Print.png"));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

                //this.dispose();
                break;

            default:
                break;
        }

    }
}