gpt4 book ai didi

java - 有没有办法为 JTable 创建渐变背景?

转载 作者:行者123 更新时间:2023-12-02 06:20:14 25 4
gpt4 key购买 nike

我已经放弃并就这个问题向社区寻求帮助(不想再用我的头撞这个代码(和我的笔记本电脑)。

)

我正在尝试为我的 JTable 创建渐变背景 - 我已经在这个网站和多个论坛上检查了为各种组件创建渐变背景的方法。大多数论坛建议重写 paintComponent() 方法并将组件设置为透明 JTable.setOpaque(false)。我已经在多种配置中尝试过此操作,但没有成功。

使用此链接中的 GradientViewport 帮助 here ,我能够为滚动 Pane 设置渐变背景,但不能为表格本身设置渐变背景。下面是我一直在努力解决这个问题的一些示例代码:

import java.awt.*;
import java.util.Random;

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

public class GradientTest
{
private static final Color C1 = new Color(255, 200, 200);
private static final Color C2 = new Color(200, 200, 255);

private GradientViewport viewport;

private JTable testTbl;

private JPanel mainPanel = new JPanel();
private JFrame frame = new JFrame();

private String[] answer = {"Yes", "No"};
private String[] first = {"Jack", "Kelly", "Mike", "Lisa"};
private String[] last = {"Donovan", "Marshall", "Jones", "Kinder"};

public GradientTest()
{
String [] colNames = {"First Name", "Last Name", "Eligible"};
DefaultTableModel model = new DefaultTableModel(colNames, 0);

testTbl = new JTable(model);
// {
// @Override
// protected void paintComponent(Graphics g)
// {
// super.paintComponent(g);
// GradientPaint gp = new GradientPaint(0, 0, C1, getWidth(), getHeight(), C2, false);
// Graphics2D g2d = (Graphics2D) g;
// g2d.setPaint(gp);
// g2d.fillRect(0, 0, getWidth(), getHeight());
// }
// };

for(int x=0; x<10; x++) {

String fName = first[new Random().nextInt(first.length)];
String lName = last[new Random().nextInt(last.length)];
String areaMonitor = answer[new Random().nextInt(answer.length)];

model.addRow(new Object[] {fName, lName, areaMonitor});
}

testTbl.setOpaque(false);

JScrollPane scrollPane = new JScrollPane();
viewport = new GradientViewport(C1, C2);
viewport.setView(testTbl);

scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.setViewportBorder(null); //removes border from table
scrollPane.setViewport(viewport);

mainPanel.add(scrollPane);

frame.add(mainPanel);
frame.pack();

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

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

如果我取消注释 paintComponent() 方法并重新运行,渐变会覆盖整个表格,从而无法查看底层数据。我知道我上面链接的帖子中有类似的问题/答案,但我正在寻找类似于滚动 Pane 中显示的渐变。

提前感谢任何可以提供帮助的人 - 如果确实没有办法做到这一点,我会坚持使用我所拥有的。

最佳答案

因此,去掉注释后,我只需要在代码中添加几行:

DefaultTableCellRenderer rend = new DefaultTableCellRenderer();
rend.setOpaque(false);
testTbl.setDefaultRenderer(Object.class, rend);
我还添加了 @MadProgrammer 链接中的一些代码来解决我的 header 问题。再次感谢您的帮助。

关于java - 有没有办法为 JTable 创建渐变背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55840827/

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