我想在我的系统上添加另一个设计/模型JTable
。这是一个简单的设计,但对我(作为一个新手)来说,我很难设置这种桌子。我希望表格看起来像这样:
是否可以在 Java 中设计这样的表格?请分享您的任何想法。
我想在我的系统上添加另一个设计/模型JTable
。这是一个简单的设计,但对我(作为一个新手)来说,我很难设置这种桌子。我希望表格看起来像这样:
是否可以在 Java 中设计这样的表格?请分享您的任何想法。
有很多不同的方法可以实现这个结果......
在这里,我用我自己的实现替换了标题,将类型的默认单元格渲染器设置为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
为表头设置自己的组件,但是,就个人而言,我认为这太过分了。
能够提供我自己的渲染器是一种更加灵活的方法,并且可以促进组件元素的重用,而不会产生紧密耦合的代码......
您可能会发现通读如何使用表格很方便
更新
我突然想到,在 Guillaume 说了什么之后,您可以简单地将JTable
s 标题设置为null
. 然后,将表格添加到滚动窗格后,您可以简单地JScrollPane#setColumnHeaderView
将标题设置为类似JLabel
.
实现你自己的会更容易JTableHeader
覆盖 JTable 的 prepareRendere 方法。对于包含文本的第 1 列,使用一种字体,对于第 2 列,使用另一种字体。
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 代码作为参考)修改了我的方法。
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;
}
}
PS:
table.setTableHeader(null): => 用于隐藏列使用。
DefaultTableCellRenderer: => 这将返回默认的表格单元格渲染器。所以用它来制作 column-1 字体样式。
table.setShowGrid(false); => 这将使 JTable 中的行不可见。
还有另一种方法。使用适当的 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();
}
});
}
}