Realign RGB Color Chooser Panel of JColorChooser Panel Java swing

41 views Asked by At

I am using the JColorChooser panel in which I have modified to use only RGB panel. Also, I removed the alpha input from it. (This image below is a standard image for reference)

enter image description here

Now I want to reposition the Color code text field right below the Blue field and move that Preview panel to the right of all the inputs. This is what I want it to be shown:

enter image description here

In short, I want to reposition some of the elements in the chooser panel. How to do that?

1

There are 1 answers

0
Sergiy Medvynskyy On

If you only need to move the preview panel to the right and remove another panels, you may write a custom UI for the color chooser. Here is the example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;

import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicColorChooserUI;

public class ColorChooserTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ColorChooserTest()::initUI);
    }
    
    private void initUI() {
        // if you need this behavior for all color choosers you shouldn't restore the old UI
        Object oldUI = UIManager.get("ColorChooserUI");
        UIManager.put("ColorChooserUI", RightSidePreviewColorUI.class.getName());
        Color c = JColorChooser.showDialog(null, "Right aligned chooser", Color.BLACK);
        UIManager.put("ColorChooserUI", oldUI);
        if (c == null) {
            System.out.println("You've pressed cancel!");
        } else {
            System.out.println("You've chosen: " + c);
        }
    }
    
    // if you use Nimbus L&F you must extend SynthColorChooserUI
    public static class RightSidePreviewColorUI extends BasicColorChooserUI {
        public static ComponentUI createUI(JComponent c) {
            return new RightSidePreviewColorUI();
        }

        @Override
        public void installUI(JComponent c) {
            super.installUI(c);
            Component comp = chooser.getPreviewPanel().getParent();
            chooser.removeAll();
            chooser.add(defaultChoosers[3]);
            chooser.add(comp, BorderLayout.EAST);

        }
    }
}