How to change the color of the border?

Asked

Viewed 1,320 times

4

How I could change the color of the border 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);
    }
}

1 answer

8


You need a little "workaround" to work.

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

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

Applied in your example code, it results:

inserir a descrição da imagem aqui

If you want the text to follow the border color, just set a color using the method setTitleColor class TitledBorder:

Border lineBorder = BorderFactory.createLineBorder(Color.green);
TitledBorder title = BorderFactory.createTitledBorder(lineBorder, "Teste");
title.setTitleColor(Color.green);
painelBorda.setBorder(title);
  • he changed only the title, the line that forms the border remains pattern.

  • @Java ta using Nimbus as lookandfeel?

  • ta without any lookandfeel

  • @java now yes, see the edition.

  • 1

    now yes! Thank you !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.