如何创建不同的JTable模型?

时间:2013-01-21 07:07:30

标签: java swing jtable tablecellrenderer

我想在我的系统上添加JTable的另一个设计/模型。这是一个简单的设计,但对我来说(作为一个新手)我很难设置这种表。我希望表格看起来像这样: table design with bold last column

是否可以在Java中设计这样的表格?请分享你有任何想法。

3 个答案:

答案 0 :(得分:9)

有很多不同的方法可以达到这个结果......

enter image description here

在这里,我用自己的实现替换了标头,将类型Double的默认单元格渲染器设置为我自己的TableCellRenderer并调整表格的一些内置属性。

public class FancyTable {

    public static void main(String[] args) {
        new FancyTable();
    }

    public FancyTable() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTable table = new JTable(new LoanModel());
                table.setTableHeader(new SingleColumnTableHeader());
                table.setFillsViewportHeight(true);
                table.setShowHorizontalLines(true);
                table.setShowVerticalLines(false);
                table.setGridColor(Color.LIGHT_GRAY);
                table.setDefaultRenderer(Double.class, new CurrencyRenderer());

                JScrollPane scrollPane = new JScrollPane(table);

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(scrollPane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class LoanModel extends AbstractTableModel {

        private List<Loan> loans;

        public LoanModel() {
            loans = new ArrayList<Loan>(25);
            loans.add(new Loan("Davies S.J", 2500000));
            loans.add(new Loan("Lucas M.M", 1700000));
            loans.add(new Loan("Smith R.B", 600000));
            loans.add(new Loan("Jones T.T", 435000));
            loans.add(new Loan("Brown R.B", 600000));
            loans.add(new Loan("Walls T.T", 435000));
            loans.add(new Loan("Healy R.B", 600000));
            loans.add(new Loan("Taylor T.T", 435000));
            loans.add(new Loan("Ginns R.B", 600000));
            loans.add(new Loan("Murphy H", 435000));
        }

        @Override
        public int getRowCount() {
            return loans.size();
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            Class clazz = String.class;
            switch (columnIndex) {
                case 1:
                    clazz = Double.class;
                    break;
            }
            return clazz;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object value = null;
            Loan loan = loans.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    value = loan.getName();
                    break;
                case 1:
                    value= loan.getAmount();
                    break;
            }
            return value;
        }

    }

    public class Loan {

        private String name;
        private double amount;

        public Loan(String name, double amount) {
            this.name = name;
            this.amount = amount;
        }

        public String getName() {
            return name;
        }

        public double getAmount() {
            return amount;
        }

    }

    public class CurrencyRenderer extends DefaultTableCellRenderer {

        private Font boldFont;

        public CurrencyRenderer() {
            setHorizontalAlignment(JLabel.RIGHT);
            boldFont = getFont().deriveFont(Font.BOLD);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

            if (value instanceof Double) {
                value = NumberFormat.getCurrencyInstance().format(value);
            }

            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            setFont(boldFont);

            return this;
        }

    }

    public class SingleColumnTableHeader extends JTableHeader {

        private JLabel renderer;

        public SingleColumnTableHeader() {
            setBackground(Color.WHITE);
            renderer = new JLabel("Top Ten Loan Balances");
            renderer.setBorder(new EmptyBorder(4, 0, 4, 0));
        }

        @Override
        public Dimension getPreferredSize() {
            return renderer.getPreferredSize();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            FontMetrics fm = g2d.getFontMetrics();

            Insets insets = getInsets();
            int width = getWidth() - (insets.left + insets.right);
            int height = getHeight() - (insets.top + insets.bottom);

            renderer.setBounds(insets.left, insets.top, width, height);
            renderer.paint(g2d);

            g2d.setColor(Color.LIGHT_GRAY);
            g2d.setStroke(new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            g2d.drawLine(insets.left, insets.top + height - 1, insets.left + width, insets.top + height - 1);

            g2d.dispose();
        }

    }

}

您可以轻松地创建自己的自定义JTable并覆盖configureEnclosingScrollPane来为表格标题设置自己的组件,但是,就个人而言,我认为这已经过时了。

能够提供我自己的渲染器是一种更灵活的方法,可以促进组件元素的重复使用,而不会产生紧密的代码......

您可能会发现阅读How to use Tables

非常方便

<强>更新

我想到,在Guillaume说过之后,你可以简单地将JTable标题设置为null。然后,将表格添加到滚动窗格后,您只需使用JScrollPane#setColumnHeaderView将标题设置为JLabel即可。

必须实现您自己的JTableHeader

更容易

答案 1 :(得分:5)

覆盖JTable的prepareRendere方法。对于包含文本的第1列,使用一种字体,对于第2列,使用另一种字体。

enter image description here

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

public class JTableExample {
public static void main(String[] args) {

    Object[] column = {"Column One", "Column Two"};
    Object[][] data = {{"One", "Two"}, {"Three", "Four"}, {"Five", "Five"}};

    JTable toDoTable = new JTable(data, column) {
        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int rowIndex,
                int columnIndex) {
            if(columnIndex == 1) {
                setFont(new Font("Arial", Font.BOLD, 12));
            } else {
                setFont(new Font("Arial", Font.ITALIC, 12));
            }

            return super.prepareRenderer(renderer, rowIndex, columnIndex);
        }
    };
    JScrollPane jpane = new JScrollPane(toDoTable);
    JPanel panel = new JPanel();
    JFrame frame = new JFrame();
    frame.setSize(new Dimension(400, 100));
    frame.setTitle("JTable Font Setting Example");
    panel.add(jpane);
    frame.add(new JScrollPane(panel));
    frame.setVisible(true);
}
}

<强>更新

MadProgrammer Guillaume Polet 建议。我使用DefaultTableCellRenderer修改了我的方法(使用Guillaume Polet代码作为参考。)

enter image description here

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class JTableExample {
public static void main(String[] args) {

    Object[] column = {"Column One", "Column Two"};
    Object[][] data = {{"One", "Two"}, {"Three", "Four"}, {"Five", "Five"}};

    JTable table = new JTable(data, column);

    table.getColumnModel().getColumn(1).setCellRenderer(new CustomTableCellRenderer());
    table.setShowGrid(false);
    table.setTableHeader(null);
    JLabel label = new JLabel("Top 10 by Loan Balance");
    label.setFont(label.getFont().deriveFont(15.0f));
    JScrollPane scroll = new JScrollPane(table);
    JFrame frame = new JFrame();
    frame.setSize(new Dimension(400, 100));
    frame.setTitle("JTable Font Setting Example");
    frame.add(label, BorderLayout.NORTH);
    frame.add(scroll, BorderLayout.CENTER);
    frame.setVisible(true);
}
}

class CustomTableCellRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object aValue,
            boolean isSelected, boolean hasFocus, int rowIndex, int columnIndex) {
        Component component = super.getTableCellRendererComponent(table, aValue, isSelected, hasFocus, rowIndex, columnIndex);
        component.setFont(component.getFont().deriveFont(Font.BOLD));
        return component;
    }
}

P.S:

  

table.setTableHeader(null):=&gt;要隐藏列,请使用。

     

DefaultTableCellRenderer:=&gt;返回默认表格单元格   渲染器。因此,使用它来制作第1列字体样式。

     

table.setShowGrid(假); =&GT;这将使JTable中的行成为   不可见。

答案 2 :(得分:3)

另一种方法。使用适当的CellRenderer来实现各种样式并管理文本对齐。至于使TableHeader消失,只需将其设置为null上的JTable

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.Random;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;

public class TestTableHeader {

    public static class BoldTableCellRenderer extends DefaultTableCellRenderer {

        public BoldTableCellRenderer() {
            setHorizontalAlignment(RIGHT);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            renderer.setFont(renderer.getFont().deriveFont(Font.BOLD));
            return renderer;
        }
    }

    protected void initUI() {
        Vector<Vector<Object>> datas = new Vector<Vector<Object>>();
        Vector<String> colNames = new Vector<String>();
        for (int i = 0; i < 2; i++) {
            colNames.add("Col-" + (i + 1));
        }
        for (int i = 0; i < 15; i++) {
            Vector<Object> data = new Vector<Object>();
            data.add("John Smith (" + (i + 1) + ")");
            data.add(new Random().nextInt(4000));
            datas.add(data);
        }

        table = new JTable(datas, colNames);
        table.setShowGrid(false);
        table.getColumnModel().getColumn(1).setCellRenderer(new BoldTableCellRenderer());
        table.setFillsViewportHeight(false);
        table.setTableHeader(null);
        table.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.GRAY));
        JLabel label = new JLabel("Top 10 by Loan Balance");
        label.setFont(label.getFont().deriveFont(15.0f));
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        scrollpane = new JScrollPane(table);
        scrollpane.setRowHeaderView(null);
        frame.add(label, BorderLayout.NORTH);
        frame.add(scrollpane, BorderLayout.CENTER);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }

    private JTable table;
    private JScrollPane scrollpane;

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestTableHeader().initUI();
            }
        });
    }

}