请问在java JTable中如何设置单元格字体居中对齐?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请问在java JTable中如何设置单元格字体居中对齐?相关的知识,希望对你有一定的参考价值。
参考技术A 设置单元格里面找到左右与垂直全部点击为居中就行了 参考技术B 这是三个类,你重新整一下哟!package database.other;import java.awt.BorderLayout;import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;public class MainFrame extends JFrame implements ActionListener
private static final long serialVersionUID = 7094024210608765600L;
private UserModel model;
private JTextField txtName = new JTextField(10);
private JTextField txtPWD = new JTextField(10);
private JButton btnAdd = new JButton("添加");public MainFrame()
super("数据库表格演示");
this.setLayout(new BorderLayout());
//添加Table
model = new UserModel();
JTable table = new JTable(model);
table.setFont(new Font(null, Font.PLAIN, 20));
table.getTableHeader().setFont(new Font(null, Font.BOLD, 22));
this.add(new JScrollPane(table), BorderLayout.CENTER);
//添加数据相关控件
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JLabel("姓名:"));
panel.add(txtName);
panel.add(new JLabel("密码:"));
panel.add(txtPWD);
panel.add(btnAdd);
this.add(panel, BorderLayout.PAGE_END);
//事件绑定
btnAdd.addActionListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setResizable(false);
this.setVisible(true);
@Override
public void actionPerformed(ActionEvent e)
boolean result = model.addUser(txtName.getText(), txtPWD.getText());
if (!result)
JOptionPane.showMessageDialog(this, "数据添加失败!");
public static void main(String[] args)
new MainFrame();
package database.other;public class UserInfo
private int userID;
private String userName;
private String passWord;public UserInfo()
public int getUserID()
return userID;
public void setUserID(int userID)
this.userID = userID;
public String getUserName()
return userName;
public void setUserName(String userName)
this.userName = userName;
public String getPassWord()
return passWord;
public void setPassWord(String passWord)
this.passWord = passWord;
@Override
public String toString()
return String.format("%d,%s,%s", userID, userName, passWord);
package database.other;import database.one.SqlConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;public class UserModel extends AbstractTableModel
private static final long serialVersionUID = 3488161650785725386L;
private ArrayList<UserInfo> users = new ArrayList<UserInfo>();
private SqlConnection sc;public UserModel()
super();
sc = new SqlConnection();
init();
@Override
public int getColumnCount()
return 3;
@Override
public int getRowCount()
return users.size();
@Override
public Object getValueAt(int row, int column)
UserInfo user = users.get(row);
switch (column)
case 0:
return user.getUserID();
case 1:
return user.getUserName();
case 2:
return user.getPassWord();
default:
return null;
@Override
public String getColumnName(int column)
switch (column)
case 0:
return "用户编号";
case 1:
return "用户名称";
case 2:
return "用户密码";
default:
return super.getColumnName(column);
private void init()
//初始化数据
Connection conn = sc.getConnection();
String sql = "select * from UserInfo";
try
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(sql);
while (rs.next()) //读取数据到集合中
UserInfo user = new UserInfo();
user.setUserID(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setPassWord(rs.getString(3));
users.add(user);
catch (SQLException e)
System.out.printf("%s%n", e.getMessage());
finally
try
conn.close();
catch (SQLException e)
public boolean addUser(String userName, String passWord)
//添加用户
Connection conn = sc.getConnection();
String sql = "insert into UserInfo (UserName,PassWord) values (?,?)";
PreparedStatement ps;
UserInfo user = new UserInfo();
user.setUserName(userName);
user.setPassWord(passWord);
try
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, userName);
ps.setString(2, passWord);
int x = ps.executeUpdate();
if (x == 1)
ResultSet rs = ps.getGeneratedKeys();
if (rs.next())
user.setUserID(rs.getInt(1));
users.add(user);
fireTableDataChanged();
return true;
return false;
catch (SQLException e)
System.out.printf("%s%n", e.getMessage());
return false;
finally
try
conn.close();
catch (SQLException e)
回答完毕,希望对你的提问有帮助,如果满意请采纳o(∩_∩)o...哈哈
Java JTable改变单元格颜色
我想制作一个可编辑的表,然后检查数据以确保其有效。我不知道如何改变一个细胞的颜色。我想获得一个单元格,例如(0,0)并将前景颜色设置为红色。我已经阅读了SO以及Oracle关于自定义ColorRenderer的其他帖子,但我只是不知道如何使用它。
谢谢。
假设您要使用不同颜色渲染的单元格表示状态(我将以“拒绝和已批准”为例)。然后我在我的表模型中实现一个名为getStatus(int row)的方法,它返回任何给定行的状态。
然后,当它到位时,我将创建一个单元格渲染器,负责渲染单元格所属的列。单元格渲染器将在下面的代码行中。
public class StatusColumnCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
//Cells are by default rendered as a JLabel.
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
//Get the status for the current row.
CustomTableModel tableModel = (CustomTableModel) table.getModel();
if (tableModel.getStatus(row) == CustomTableModel.APPROVED) {
l.setBackground(Color.GREEN);
} else {
l.setBackground(Color.RED);
}
//Return the JLabel which renders the cell.
return l;
}
然后,当渲染器到位时,只需使用以下代码“将”渲染器“应用”到表中:
Table.getColumnModel().getColumn(columnIndex).setCellRenderer(new StatusColumnCellRenderer());
关于使单元格可编辑,只需在表模型中实现isCellEditable(int rowIndex,int columnIndex)方法。如果你想保留用户提供的值(我假设你这样做),你还需要实现方法setValueAt(Object value,int rowIndex,int columnIndex)。
我想制作一个可编辑的表,然后检查数据以确保其有效。
另一种方法是在将数据保存到表模型之前编辑数据,以防止输入无效数据。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableEdit extends JFrame
{
TableEdit()
{
JTable table = new JTable(5,5);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollpane = new JScrollPane(table);
getContentPane().add(scrollpane);
// Use a custom editor
TableCellEditor fce = new FiveCharacterEditor();
table.setDefaultEditor(Object.class, fce);
}
class FiveCharacterEditor extends DefaultCellEditor
{
FiveCharacterEditor()
{
super( new JTextField() );
}
public boolean stopCellEditing()
{
try
{
String editingValue = (String)getCellEditorValue();
if(editingValue.length() != 5)
{
JTextField textField = (JTextField)getComponent();
textField.setBorder(new LineBorder(Color.red));
textField.selectAll();
textField.requestFocusInWindow();
JOptionPane.showMessageDialog(
null,
"Please enter string with 5 letters.",
"Alert!",JOptionPane.ERROR_MESSAGE);
return false;
}
}
catch(ClassCastException exception)
{
return false;
}
return super.stopCellEditing();
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column)
{
Component c = super.getTableCellEditorComponent(
table, value, isSelected, row, column);
((JComponent)c).setBorder(new LineBorder(Color.black));
return c;
}
}
public static void main(String [] args)
{
JFrame frame = new TableEdit();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
最直接的方法是通过扩展TableCellRenderer
并将DefaultTableCellRenderer
方法覆盖到getTableCellRendererComponent
来编写一个简单的setBackground( Color.RED )
。例如:
final JTable table = new JTable(...);
table.setCellRenderer( new DefaultTableCellRenderer() {
public Component getTableCellRenderer(JTable table, Object value, ...) {
super.getTableCellRenderer(...);
if ( value should be highlighted ) {
setBackground( Color.RED );
}
return this;
}
});
这是为jTable中的特定列或单元着色的最简单方法。
首先,只需创建一个简单的CustomRenderer
类
class CustomRenderer extends DefaultTableCellRenderer <br />
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setForeground(Color.blue); >
return c;
}
}
此代码获取要呈现的单元格列
TableColumn col = tblExamHistoryAll.getColumnModel().getColumn(5);
DefaultTableModel model3 = (DefaultTableModel)tblExamHistoryAll.getModel();
col.setCellRenderer(new CustomRenderer());
这是为了清除表中的所有先前行。如果您不想要它们,只需删除这些行
model3.getDataVector().removeAllElements();
model3.fireTableDataChanged();
我相信在表格中进行着色的正确方法是通过ColorHighlighter
。表格渲染器在同一列中呈现不同颜色存在问题。
这是一个如何使用荧光笔的例子。在这种情况下,它用于突出显示不可编辑的单元格。
public class IsCellEditablePredicate implements HighlightPredicate {
private JXTable table;
public IsCellEditablePredicate (final JXTable table) {
this.table = table;
}
@Override
public boolean isHighlighted(Component component, ComponentAdapter componentAdapter) {
return !table.isCellEditable(componentAdapter.row,
componentAdapter.column);
}
}
然后在您设置表格的代码中添加突出显示及其颜色参数:
ColorHighlighter grayHighlighter = new ColorHighlighter(new IsCellEditablePredicate(table));
grayHighlighter.setBackground(Color.LIGHT_GRAY);
grayHighlighter.setForeground(table.getForeground());
grayHighlighter.setSelectedBackground(table.getSelectionBackground().darker());
grayHighlighter.setSelectedForeground(table.getSelectionForeground().darker());
table.setHighlighters(grayHighlighter);
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
int control = row;
control = control % 2;
control = (control == 0) ? 1 : 0;
if (control == 1) {
c.setBackground(Color.green);
} else {
c.setBackground(Color.cyan);
}
return c;
}
您可以扩展DefaultTableCellRenderer,覆盖getTableCellRendererComponent并调用类似的东西
if (myConditions) setBackground(myColor);
在条件适用时返回“this”之前,由于DefaultTableCellRenderer.setBackGround的编码方式,它有一个非常烦人的副作用,即改变默认的背景颜色。
我发现的技巧是在名为HackedDefaultTableCellRenderer的类中完全复制DefaultTableCellRenderer的代码,添加一个直接调用Component的setBackground实现的方法:
public void setComponentBackground(Color c) {
super.setBackground(c);
}
然后从这个被黑客的类而不是DefaultTableCellRenderer派生我自定义的渲染,最后在我的自定义getTableCellRendererComponent中调用setComponentBackground而不是setBackground。
缺点是这个HackedDefaultTableCellRenderer依赖于DefaultTableCell
以上是关于请问在java JTable中如何设置单元格字体居中对齐?的主要内容,如果未能解决你的问题,请参考以下文章