Search code examples
javaswingjlabellayout-managerboxlayout

JLabel not aligning to the right in a BoxLayout


I have some JLabel components in a JPanel (taskPanel) with a BoxLayout (which is in a panel with a GridBagLayout) and the labels are refusing to be aligned to the right. They keep aligning to the left no matter how I manipulate them.

Here I setup the GridBagConstraints for the panel that has the labels

GridBagConstraints taskPanelC = new GridBagConstraints();
taskPanelC.gridx = 4;
taskPanelC.gridy = 0;
taskPanelC.gridwidth = 1;
taskPanelC.anchor = GridBagConstraints.NORTHEAST;
taskPanelC.weighty = 1;
taskPanelC.weightx = 1;
taskPanelC.insets = new Insets(10, 10, 10, 10);
timePanel.add(taskPanel, taskPanelC);

Here are the GridBagConstraints for the panel before the task panel

//Setup the gridBagLayout
GridBagConstraints timeTextC = new GridBagConstraints();
timeTextC.gridx = 1;
timeTextC.gridy = 0;
timeTextC.gridwidth = 3;
timeTextC.anchor = GridBagConstraints.CENTER;
timeTextC.weighty = 1;
timeTextC.weightx = 1;

Here I add a header to the taskPanel (I don't really care how this is aligned)

taskListLabel = new JLabel("Task List");
taskListLabel.setFont(new Font("Helvetica", Font.BOLD, 24));
taskPanel.add(taskListLabel);

Here is where I am adding the labels I want to be right-justified/aligned. I have tried setHorizontalTextPosition and setAlignmentX and both do not work, causing the text to stay left aligned. However, when I tried setAlignmentX, the header became unaligned with the task labels

JLabel task = new JLabel(name, SwingConstants.RIGHT);
//Allow deleting of the label
task.addMouseListener(new ClickListener());
//Add task to the task panel
taskPanel.add(task);

This is what it currently looks like img

I want the text under task list to be right-aligned so the time is always on the right

Here is a link to the full code in case the summary was not enough: Github Repo


Solution

  • Check out the following methods from the JLabel API:

    1. setHorizontalAlignment(...) - used to align the text when the width of the label is greater than the width of the text
    2. setAlignmentX(...) - might be used by the layout manager to align component