gpt4 book ai didi

java - Java 标签中的文本对齐方式

转载 作者:行者123 更新时间:2023-12-01 05:51:46 25 4
gpt4 key购买 nike

我正在开发一个以充满数字的表格为中心的 Java 应用程序。在某些列中,我想对齐列中的数字(当然是文本),以便小数点在单元格的中心垂直对齐。

我没有看到任何适用于这种情况的对齐常量。 Java中有没有官方的机制来处理这种情况?

预先感谢您的帮助。

约翰·多纳

最佳答案

我对此并不专业,但它确实可以像我上面提到的那样工作,通过使用 JTextPane 作为自定义单元格渲染器并将选项卡属性设置为小数点对齐。如果执行此操作,则必须注意将数据表示为字符串,并且在编辑数据时将制表符添加到数据字符串的开头。

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.text.*;

@SuppressWarnings("serial")
public class TabStopDecimalAlign extends JPanel {
private static final String[][] DATA = {{"One", "1.234"}, {"Two", "232.3223"},
{"Three", "0.2323"}, {"Four", "12.345"}, {"Five", "10000.0"}};
private static final String[] COLUMNS = {"Count", "Data"};
private static final int ROW_HEIGHT = 24;
private DecimalAlignRenderer decimalAlignRenderer = new DecimalAlignRenderer();
private DefaultTableModel model = new DefaultTableModel(DATA, COLUMNS);
private JTable table = new JTable(model) {
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
if (column == 1) {
return decimalAlignRenderer;
}
return super.getCellRenderer(row, column);
}
};

public TabStopDecimalAlign() {
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
table.setRowHeight(ROW_HEIGHT);
}

private static class DecimalAlignRenderer implements TableCellRenderer {
private static final float POS = 40f;
private static final int ALIGN = TabStop.ALIGN_DECIMAL;
private static final int LEADER = TabStop.LEAD_NONE;
private static final SimpleAttributeSet ATTRIBS = new SimpleAttributeSet();
private static final TabStop TAB_STOP = new TabStop(POS, ALIGN, LEADER);
private static final TabSet TAB_SET = new TabSet(new TabStop[] { TAB_STOP });

private StyledDocument document = new DefaultStyledDocument();
private JTextPane pane = new JTextPane(document);

public DecimalAlignRenderer() {
StyleConstants.setTabSet(ATTRIBS, TAB_SET);
pane.setParagraphAttributes(ATTRIBS, false);
}

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if (value == null) {
pane.setText("\t0.0");
} else {
pane.setText("\t" + value.toString());
}
return pane;
}


}



private static void createAndShowUI() {
JFrame frame = new JFrame("TabStopDecimalAlign");
frame.getContentPane().add(new TabStopDecimalAlign());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

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

关于java - Java 标签中的文本对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4481255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com