Отключение границ Java - PullRequest
2 голосов
/ 23 марта 2012

Я бы хотел отключить все границы, которые есть у Компонента, когда Компонент отключен.

Когда вы запустите код ниже как есть, вы увидите красный LineBorder вокруг одной из текстовых областей.Я хотел бы, чтобы эта граница была отключена, когда ее TextArea отключено.

Есть ли код, который можно поместить в блок useGenericSolution в коде ниже, который будет работать для всех границ?1007 *

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

public class EnableBorder extends JFrame
{
    private static final long   serialVersionUID    = 1L;
    private static JFrame       _instance;

    public EnableBorder()
    {
        setResizable(false);
        setTitle("My Frame");
        setSize(300, 300);
        getContentPane().add(new MyPanel());
        _instance = this;
    }

    private class MyPanel extends JPanel
    {
        private static final long   serialVersionUID    = 1L;

        public MyPanel()
        {
            setLayout(new FlowLayout());
            JButton btnDisableAll = new JButton("Disable everything");
            btnDisableAll.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    EnableBorder.setEnabledAllComponents(_instance, false);
                }
            });
            add(btnDisableAll);

            // Use TitledBorder
            JTextArea titledTA = new JTextArea("This is some text that should be wide enough ");
            titledTA.setSize(400, 50);
            titledTA.setBorder(new TitledBorder("A titled border"));
            add(titledTA);

            // Use LineBorder
            JTextArea lineBorderTA = new JTextArea("This is just some more text ...");
            lineBorderTA.setSize(400, 50);
            lineBorderTA.setBorder(new LineBorder(Color.RED, 1, true));
            add(lineBorderTA);
        }
    }

    /**
     * Enables or disables a Container and all Components within a Container.
     * 
     * @param b
     *            - The value to set the 'enabled' flag to
     */
    public static void setEnabledAllComponents(Container cont, boolean b)
    {
        for (Component c : cont.getComponents())
        {
            setEnabledComponent(c, b);
        }
        setEnabledComponent(cont, b);
    }

    /**
     * Enables or disables a Component.
     * <p>
     * If the component is a Container, all of it the Components within the Container will also be modified.
     * 
     * @param c
     *            - The Component to modify
     * @param b
     *            - The value to set the 'enabled' flag to
     */
    public static void setEnabledComponent(Component c, boolean b)
    {

        if (c instanceof Container)
        {
            for (Component containerComp : ((Container) c).getComponents())
            {
                setEnabledComponent(containerComp, b);
            }
        }

        c.setEnabled(b);

        if (c instanceof JComponent)
        {

            Border border = ((JComponent) c).getBorder();
            if (border != null)
            {
                boolean useGenericSolution = true;
                if (useGenericSolution)
                {
                    Insets insets = border.getBorderInsets(c);
                    System.out.println("Insets: " + insets);
                    Graphics g = c.getGraphics();

                    if (g != null)
                    {
                        /*
                         * TODO: Is it possible to get foreground color from the current object
                         * and force the border to be painted using that color 
                         */

                        Color color = g.getColor();

                        border.paintBorder(c, g, c.getX() - 5 - insets.left, c.getY() - insets.top, c.getWidth() + insets.left + insets.right,
                                c.getHeight() + insets.top + insets.bottom);
                    }
                }
                else
                {
                    // TitledBorders can be done this way... but, a generic solution would be better
                    if (border instanceof TitledBorder)
                    {
                        if (b)
                        {
                            // Change border colors to color found in an enabled label
                            ((TitledBorder) border).setTitleColor((Color) UIManager.get("Label.enabledForeground"));
                        }
                        else
                        {
                            // Change border colors to color found in a disabled label
                            ((TitledBorder) border).setTitleColor((Color) UIManager.get("Label.disabledForeground"));
                        }
                    }
                }
            }
        }

    }

    private static void createAndShowGUI()
    {
        // Create and set up the window.
        EnableBorder frame = new EnableBorder();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    createAndShowGUI();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    System.exit(0);
                }
            }
        });
    }

}

1 Ответ

1 голос
/ 23 марта 2012

Просто добавьте следующую строку в общий блок Solution

if (useGenericSolution) {
    ((JComponent) c).setBorder(BorderFactory.createEmptyBorder());
}
...