how to add gradient background to JTable column header? - java

Hi how to set gradient background to column header ? I have Jtable:
JTable table = new JTable(4, 5);
and try to setColor: table.getTableHeader().setBackground(Color.blue);
but with no succes color of column header is still same and these is just one color and I need gradient
thx for help

Are you coding this with NetBean's code generation or are you coding your Swing by hand?
Have you tried creating a class that extends the JTableHeader and overrides its paintComponent method? Give it a try and in that method create a GradientPaint object or one of its variants use it to set the Graphics2D paint's property and then call fillRect using the current dimensions of the component to fill it with gradient color.
For example here are two ways to do this, one with a custom JTableHeader and one with a custom cell renderer that is used by the table header:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class GradientHeader {
private static void createAndShowGui() {
JTable table1 = new JTable();
GradientTableHeader gradientTableHeader = new GradientTableHeader();
gradientTableHeader.setColumnModel(table1.getColumnModel());
table1.setTableHeader(gradientTableHeader);
DefaultTableModel model = new DefaultTableModel(new Integer[][] {
{ 1, 2 }, { 3, 4 } }, new String[] { "A", "B" });
table1.setModel(model);
JTable table2 = new JTable(model);
table2.getTableHeader().setDefaultRenderer(new MyCellRenderer());
JPanel mainPanel = new JPanel(new GridLayout(1, 0));
mainPanel.add(new JScrollPane(table1));
mainPanel.add(new JScrollPane(table2));
JFrame frame = new JFrame("GradientHeader");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GradientTableHeader extends JTableHeader {
private static final Color COLOR_1 = new Color(255, 0, 0, 240);
private static final Color COLOR_2 = new Color(0, 0, 255, 120);
private static final float SIDE = 50;
private GradientPaint gradientPaint = new GradientPaint(0, 0, COLOR_1, SIDE,
SIDE, COLOR_2, true);
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(gradientPaint);
g2.fillRect(0, 0, getWidth(), getHeight());
}
}
class MyCellRenderer extends JPanel implements TableCellRenderer {
private static final Color COLOR_1 = new Color(255, 0, 0, 200);
private static final Color COLOR_2 = new Color(0, 0, 255, 200);
private static final float SIDE = 50;
private GradientPaint gradientPaint = new GradientPaint(0, 0, COLOR_1, SIDE,
SIDE, COLOR_2, true);
private JLabel label = new JLabel();
public MyCellRenderer() {
setOpaque(true);
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
label.setHorizontalAlignment(SwingConstants.CENTER);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocused, int arg4, int arg5) {
label.setText(value.toString());
return this;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(gradientPaint);
g2.fillRect(0, 0, getWidth(), getHeight());
}
}

Related

Transparent JList smears when selecting elements or scrolling

I have a transparent JList and JScrollPanel on top of a gradient JPanel the code for each of those looks like this:
JPanel midPanel = new JPanel() {
protected void paintComponent(Graphics g) {
Paint p = new GradientPaint(0.0f, 0.0f, new Color(233, 220, 0, 0),
getWidth(), getHeight(), new Color(239, 129, 91, 255), true);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
};
List code
ArrayList<String> songs = new ArrayList<>(Arrays.asList(new String[] {elements...}));
DefaultListModel<String> model = new DefaultListModel<>();
model.addAll(songs);
JList<String> songList = new JList<String>(model);
songList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
songList.setLayoutOrientation(JList.VERTICAL);
songList.setVisibleRowCount(-1);
songList.setOpaque(false);
songList.setCellRenderer(new TransparentListCellRenderer());
JScrollPane scroller = new JScrollPane(songList);
scroller.setPreferredSize(new Dimension(400, 250));
scroller.setOpaque(false);
scroller.getViewport().setOpaque(false);
scroller.setBorder(BorderFactory.createEmptyBorder());
midPanel.add(scroller);
Before anything is touched it looks like this:
And after stuff gets selected or scrolling the elements of the list all smear and create this mess:
Does anyone know how to fix this? if I had to guess what was wrong it would be an issue with the gradient because the paintComponet() method is overridden so it's not getting redrawn properly but if that is the case I do not know how to fix it. Any help is much appreciated.
The answer is to wrap the panel in a Container that is a sort of transparent.
public class AlphaContainer extends JComponent {
private JComponent component;
public AlphaContainer(JComponent component) {
this.component = component;
setLayout( new BorderLayout() );
setOpaque( false );
component.setOpaque( false );
add( component );
}
/**
* Paint the background using the background Color of the
* contained component
*/
#Override
public void paintComponent(Graphics g) {
g.setColor( component.getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
}
}

Image in JPanel not appearing immediately

I am using getImage to read files and save them and then setting these images to the backgrounds of jpanels. However, when the applet is first loaded, the images aren't visible. Only, if I resize it or scroll up and down, do the images appear. What is the problem?
#Override
public void init(){
setSize(800, 600);
setLayout(new FlowLayout());
setup();
box1.setText(texts[0]);
box2.setText(texts[1]);
box3.setText(texts[2]);
box4.setText(texts[3]);
add(box1);
add(box2);
add(box3);
add(box4);
add(testPanel);
add(localPanel);
add(background2);
}
public void setup(){
box1 = new JTextArea();
box2 = new JTextArea();
box3 = new JTextArea();
box4 = new JTextArea();
box1.setText(texts[0]);
box2.setText(texts[1]);
box3.setText(texts[2]);
box4.setText(texts[3]);
//*********** this loads immediately **********//
Image back2 = getImage(getDocumentBase(), "blank_blue.png");
background2 = new JLabel(new ImageIcon(back2));
panelBack = getImage(getDocumentBase(), "CardBar.png");
localPanel = new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(panelBack, 0, 0, null);
}
};
localPanel.setPreferredSize(new Dimension(100, 400));
}
The image may not be read it when the component is initially painted. Try:
//g2d.drawImage(panelBack, 0, 0, null);
g2d.drawImage(panelBack, 0, 0, this);

Scaling Graphics2D object shifts it

I have a JScrollPane that contains a custom JLabel with an ImageIcon. I want the user to be able to zoom in and out on the image. I'm trying to use the scale() method in the Graphics2D class to do it, but whenever I zoom, the image is being shifted down/up and right/left depending on whether I'm zooming in or out. I don't know why this is happening or how to tell how much I need to translate() the Graphics2D object to counteract this. I really appreciate any help you guys can give me. Here's my code:
class ImageViewer extends JFrame implements ActionListener{
private int WIDTH = 800;
private int HEIGHT = 600;
private JScrollPane scrollPane;
JMenuItem zoomIn, zoomOut;
JPanel panel;
MyLabel label;
private String imageUrl = "picture.jpg";
double scale = 1.0;
public static void main(String[] args) {
ImageViewer viewer = new ImageViewer();
viewer.setVisible(true);
}
private ImageViewer() {
this.setTitle("Image Viewer");
this.setSize(WIDTH, HEIGHT);
this.setBackground(Color.gray);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new BorderLayout());
this.getContentPane().add(panel);
JMenuBar menubar = new JMenuBar();
JMenu zoom = new JMenu("Zoom");
zoomIn = new JMenuItem("Zoom In");
zoom.add(zoomIn);
zoomIn.addActionListener(this);
zoomOut = new JMenuItem("Zoom Out");
zoom.add(zoomOut);
zoomOut.addActionListener(this);
menubar.add(zoom);
this.add(menubar, BorderLayout.NORTH);
Icon image = new ImageIcon(imageUrl);
label = new MyLabel(image);
scrollPane = new JScrollPane();
scrollPane.getViewport().add(label);
panel.add(scrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
Object ob = e.getSource();
if (ob == zoomIn) {
scale += .1;
label.revalidate();
label.repaint();
}
if (ob == zoomOut) {
scale -= .1;
label.revalidate();
label.repaint();
}
}
class MyLabel extends JLabel{
public MyLabel(Icon i){
super(i);
}
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
AffineTransform at = g2.getTransform();
g2.scale(scale, scale);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paintComponent(g2);
g2.setTransform(at);
}
public Dimension getPreferredSize(){
int w = (int)(scale * getIcon().getIconWidth()),
h = (int)(scale * getIcon().getIconHeight());
return new Dimension(w, h);
}
}
}
Before g2.scale(scale, scale); add g2.translate(desiredX, desiredY);

How to control font style, color, and size inside a JTable?

I have a JTable in Java Swing. I need to set the font size, color and style. How can I implement that in JTable?
why set TableRenderer for basic setting in the JTable, more --> JTable#setWhatever
EDIT (ballast removed) code:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableExample {
public TableExample() {
Object[][] data1 = new Object[50][5];
for (int i = 0; i < data1.length; i++) {
data1[i][0] = "Company # " + (i + 1);
for (int j = 1; j < data1[i].length; j++) {
data1[i][j] = "" + (i + 1) + ", " + j;
}
}
String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
DefaultTableModel model1 = new DefaultTableModel(data1, headers);
final JTable jTable1 = new JTable(model1);
jTable1.setBackground(Color.orange);
jTable1.setForeground(Color.blue);
jTable1.setRowHeight(24);
jTable1.setFont(new Font("Arial", Font.BOLD, 12));
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp1 = new JScrollPane();
sp1.setPreferredSize(new Dimension(600, 200));
sp1.setViewportView(jTable1);
final JTable jTable2 = new JTable(model1);
jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp2 = new JScrollPane();
sp2.setPreferredSize(new Dimension(600, 200));
sp2.setViewportView(jTable2);
final JTable jTable3 = new TableBackroundPaint0(data1, headers);
jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTable3.setModel(model1);
final JScrollPane sp3 = new JScrollPane();
sp3.setPreferredSize(new Dimension(600, 200));
sp3.setViewportView(jTable3);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3, 0, 10, 10));
panel1.add(sp1);
panel1.add(sp2);
panel1.add(sp3);
JFrame frame = new JFrame("tableSelection");
frame.add(panel1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TableExample te = new TableExample();
}
});
}
}
class TableBackroundPaint0 extends JTable {
private static final long serialVersionUID = 1L;
TableBackroundPaint0(Object[][] data, Object[] head) {
super(data, head);
setOpaque(false);
((JComponent) getDefaultRenderer(Object.class)).setOpaque(false);
}
#Override
public void paintComponent(Graphics g) {
Color background = new Color(168, 210, 241);
Color controlColor = new Color(230, 240, 230);
int width = getWidth();
int height = getHeight();
Graphics2D g2 = (Graphics2D) g;
Paint oldPaint = g2.getPaint();
g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
g2.fillRect(0, 0, width, height);
g2.setPaint(oldPaint);
for (int row : getSelectedRows()) {
Rectangle start = getCellRect(row, 0, true);
Rectangle end = getCellRect(row, getColumnCount() - 1, true);
g2.setPaint(new GradientPaint(start.x, 0, controlColor, (int) ((end.x + end.width - start.x) * 1.25), 0, Color.orange));
g2.fillRect(start.x, start.y, end.x + end.width - start.x, start.height);
}
super.paintComponent(g);
}
}
Set a custom TableCellRenderer. See How to Use Tables - Concepts: Editors and Renderers in the Java Tutorial for more details.

Custom UI painting problem

I have a JInternalFrame that I am applying a custom UI to. The UI paints the component, but when I add a JPanel to the JInternalFrame it doesn't show up. I think the UI is paining over the whole component, but how do I paint the UI THEN paint the components?
But if anyone has a better way of doing this, please let me know! Thanks!
public class ClassInternalFrame extends JInternalFrame {
public static Color currentColor;
public static final Color CLASS_TYPE = new Color(148, 227, 251);
public ClassInternalFrame(String title, Color classType) {
super(title, true, true, false, true);
currentColor = classType;
super.setUI(new ClassFrameUI());
Container pane = super.getContentPane();
pane.setLayout(new BorderLayout());
JPanel titlePanel = new JPanel();
titlePanel.setPreferredSize(new Dimension(0, 20));
pane.add(titlePanel, BorderLayout.NORTH);
titlePanel.setBorder(new MatteBorder(1, 1, 1, 1, Color.yellow));
}
}
class ClassFrameUI extends InternalFrameUI {
private final static ClassFrameUI frmUI = new ClassFrameUI();
public static ComponentUI createUI(JComponent c) {
return frmUI;
}
#Override
public void paint(Graphics g, JComponent c)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.LIGHT_GRAY);
g2d.fillRect(0, 0, c.getWidth(), c.getHeight());
g2d.setColor(ClassInternalFrame.currentColor);
g2d.fillRect(0, 0, c.getWidth(), 20);
g2d.setColor(Color.DARK_GRAY);
g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1, 0 }, 0));
g2d.drawRect(0, 0, c.getWidth()-1, c.getHeight()-1);
g2d.drawLine(0, 20, c.getWidth(), 20);
}
}
The problem is not that you're painting over anything, but that InternalFrameUI does absolutely nothing (if it did, you would also need to call super.paint(g, c);). Normally, painting of the components is done by a subclass such as BasicInternalFrameUI. It looks like you're trying to paint a custom title bar, a task that BasicInternalFrameUI delegates to BasicInternalFrameTitleBar.

Categories