不能在单元格中对齐左侧的文本,而在右侧的图标

发布于 2025-01-29 04:50:53 字数 2315 浏览 4 评论 0原文

我正在尝试实现一个非常简单的事情,我尝试了不同的选择,但似乎没有任何选择。 我有一个简单的jtable,在我使用jlabel的列中以显示文本和图标。 我只想让文本在单元格的左侧,右侧的图标。

如果我使用此片段:

label.setHorizontalTextPosition(SwingConstants.LEFT);
label.setHorizontalAlignment(SwingConstants.RIGHT);

我只是按照自己的意愿将图标放在右边,但是文本立即在图标的左侧。 因此,我正在设置图标和文本差距。

我是这样设置的:

int width = getWidth();
label.setSize(width, getHeight());
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
int textwidth = (int)(label.getFont().getStringBounds(label.getText(), frc).getWidth());

label.setIconTextGap(width - textwidth - label.getIcon().getIconWidth());

调试它,似乎做应该做的事情,但是我得到了这个结果:

... textWidth 2次)这是结果:

”图标显示,但处于预期的错误位置,但文本仍然具有不必要的椭圆”

顺便说一句,如果我再次减少差距,则显示文本,但当然,我没有得到我想要的事情保持一致。

我想实现的是一个类似于编辑器组件的渲染器,该组件是一个组合框,如下所示:

”,您可以看到我想实现的目标”

这不是优先任务对我来说,但我真的很想了解如何管理这一点。

编辑:

我还尝试使用一个容器(也是jpanel)来添加2个jlabels并按照@madprogrammer的建议更好地管理文本和图标,但是使用单元格下的代码为空,只有背景是可见

public java.awt.Component getTreeTableCellRendererComponent(TreeTable treeTable, Object value, boolean selected, boolean hasFocus, int row, int column) {
    Container container = new Container();
    JLabel label = new JLabel();
    JLabel icon = new JLabel();
    label.setText("XXX");
    icon.setIcon(myIcon);
    if (row % 2 == 0) {
        container.setBackground(new java.awt.Color(220, 245, 230));
    }
    else {
        container.setBackground(new java.awt.Color(240, 255, 240));
    }

    label.repaint();
    icon.repaint();
                
    container.add(label, BorderLayout.WEST);
    container.add(icon, BorderLayout.CENTER);                       
    container.revalidate();
    container.doLayout();
    container.setVisible(true);     
    container.repaint();
                
    return container;
}
                

的上面的代码运行而不投掷例外。

I am trying to achieve a very simple thing, I tried different options but none seems to work.
I have a simple JTable, in a column I use JLabel in order to show the text and the icon.
I just want to have the text to be on the left of the cell and the Icon to the right.

if I use this snippet:

label.setHorizontalTextPosition(SwingConstants.LEFT);
label.setHorizontalAlignment(SwingConstants.RIGHT);

I just get the icon on the right as I want, but the text is immediately on the left of the icon.
So I am setting the icon and text gap.

I am setting it like this:

int width = getWidth();
label.setSize(width, getHeight());
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
int textwidth = (int)(label.getFont().getStringBounds(label.getText(), frc).getWidth());

label.setIconTextGap(width - textwidth - label.getIcon().getIconWidth());

Debugging it, it seems to do what is supposed to do, but I got this result:

Text with unnecessary ellipses on the left...

I tried to add a bit of tolerance (subtracting textwidth 2 times) this is the result:

Icon showing but in an expected wrong position but text still have unnecessary ellipses

By the way, the text is shown if I reduce the gap again, but of course, I do not get things aligned as I want.

What I simply would like to achieve is a renderer similar to the editor component which is a combo box as you can see below:

As you can see this what I want to achieve in terms of alignment

This is not a priority task for me but I would really like to understand how to manage this.

EDIT:

I also tried to use a Container (also a JPanel) in order to add 2 JLabels and manage the text and the icon better as suggested by @MadProgrammer, but using the code below the cell is empty, only the background is visible

public java.awt.Component getTreeTableCellRendererComponent(TreeTable treeTable, Object value, boolean selected, boolean hasFocus, int row, int column) {
    Container container = new Container();
    JLabel label = new JLabel();
    JLabel icon = new JLabel();
    label.setText("XXX");
    icon.setIcon(myIcon);
    if (row % 2 == 0) {
        container.setBackground(new java.awt.Color(220, 245, 230));
    }
    else {
        container.setBackground(new java.awt.Color(240, 255, 240));
    }

    label.repaint();
    icon.repaint();
                
    container.add(label, BorderLayout.WEST);
    container.add(icon, BorderLayout.CENTER);                       
    container.revalidate();
    container.doLayout();
    container.setVisible(true);     
    container.repaint();
                
    return container;
}
                

the code above runs without throwing exceptions..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

盗心人 2025-02-05 04:50:53

如果这个旧代码围绕着演示使用面板作为渲染器的概念。前3个字符将显示在左侧,其余的则在右侧:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableRendererPanel
{
    static class MultiLabelRenderer implements TableCellRenderer
    {
        private JPanel panel;
        private JLabel red;
        private JLabel blue;

    public MultiLabelRenderer()
    {
        red = new JLabel();
        red.setForeground(Color.RED);
        blue = new JLabel();
        blue.setForeground(Color.BLUE);

        panel = new JPanel();
        panel.setLayout( new BoxLayout(panel, BoxLayout.X_AXIS) );
        panel.add(red);
        panel.add(Box.createHorizontalGlue());
        panel.add(blue);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, final int row, final int column)
    {
        panel.setBackground( isSelected ? table.getSelectionBackground() : table.getBackground() );

        if (value == null || value.toString().isEmpty())
        {
            red.setText(" ");
            blue.setText(" ");
            return panel;
        }

        //  Set the text for the two labels

        String text = value.toString();
        red.setText( text.substring(0, 3) );
        blue.setText( text.substring(3) );

        return panel;
    }
}

public static void createAndShowGUI()

    {
        JTable table = new JTable(5, 3);
      table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.getColumnModel().getColumn(0).setCellRenderer( new MultiLabelRenderer());
        JScrollPane scrollPane = new JScrollPane( table );

        table.setValueAt("abcde", 0, 0);
        table.setValueAt("123456789", 1, 0);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( scrollPane );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }

}

Had this old code lying around demonstrating the concept of using a panel as a renderer. The first 3 characters will be displayed on the left and the remainder on the right:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableRendererPanel
{
    static class MultiLabelRenderer implements TableCellRenderer
    {
        private JPanel panel;
        private JLabel red;
        private JLabel blue;

    public MultiLabelRenderer()
    {
        red = new JLabel();
        red.setForeground(Color.RED);
        blue = new JLabel();
        blue.setForeground(Color.BLUE);

        panel = new JPanel();
        panel.setLayout( new BoxLayout(panel, BoxLayout.X_AXIS) );
        panel.add(red);
        panel.add(Box.createHorizontalGlue());
        panel.add(blue);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, final int row, final int column)
    {
        panel.setBackground( isSelected ? table.getSelectionBackground() : table.getBackground() );

        if (value == null || value.toString().isEmpty())
        {
            red.setText(" ");
            blue.setText(" ");
            return panel;
        }

        //  Set the text for the two labels

        String text = value.toString();
        red.setText( text.substring(0, 3) );
        blue.setText( text.substring(3) );

        return panel;
    }
}

public static void createAndShowGUI()

    {
        JTable table = new JTable(5, 3);
      table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.getColumnModel().getColumn(0).setCellRenderer( new MultiLabelRenderer());
        JScrollPane scrollPane = new JScrollPane( table );

        table.setValueAt("abcde", 0, 0);
        table.setValueAt("123456789", 1, 0);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( scrollPane );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文