How to change the border color?

4

How can I change the border color created by BorderFactory?

import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;

public class BordaTitulo extends JDialog {

    public BordaTitulo() {
        setTitle("Teste Dialog");
        add(criaBorda());
        setSize(500, 320);        
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public JComponent criaBorda() {
        JPanel painelPrincipal = new JPanel();
        painelPrincipal.setLayout(new GridBagLayout());

        JPanel painelBorda = new JPanel();
        painelBorda.setLayout(new GridBagLayout());
        painelBorda.setBorder(BorderFactory.createTitledBorder("Teste"));

        painelBorda.setPreferredSize(new Dimension(350, 70));         
        painelPrincipal.add(painelBorda);
        return painelPrincipal;
    }

    public static void main(String[] args) {
        BordaTitulo t = new BordaTitulo();
        t.setVisible(true);
    }
}
    
asked by anonymous 17.06.2017 / 02:39

1 answer

8

You need a small " workaround " to work.

First you need to create a common colored border, and then a TitledBorder passing the border already created together with a title as a parameter:

Border lineBorder = BorderFactory.createLineBorder(Color.green);
TitledBorder title = BorderFactory.createTitledBorder(lineBorder, "Teste");
painelBorda.setBorder(title);

Applied in your sample code, it results:

Ifyouwantthetexttomatchthecoloroftheborder,justsetacolorusingthe setTitleColor " of class TitledBorder :

Border lineBorder = BorderFactory.createLineBorder(Color.green);
TitledBorder title = BorderFactory.createTitledBorder(lineBorder, "Teste");
title.setTitleColor(Color.green);
painelBorda.setBorder(title);
    
17.06.2017 / 02:45