Mudar propriedades de todos os componentes do mesmo tipo?

2 respostas
Thallysson

Olá, eu gostaria de saber neste tópico se é possível aplicar alterações em todos os componentes do mesmo tipo no meu projeto? Exemplo cada jbutton que eu adicionar em qualquer lugar fique com o plano de fundo vermelho.

2 Respostas

H

@Thallysson, você pode usar um método recursivo a partir do contentPane, varrendo todos os filhos. Segue exemplo:

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class CorFilhos extends JFrame {

	private JPanel contentPane;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					CorFilhos frame = new CorFilhos();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public CorFilhos() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JButton btnNewButton = new JButton("a");
		btnNewButton.setBounds(24, 200, 89, 23);
		contentPane.add(btnNewButton);
		
		JPanel panel = new JPanel();
		panel.setBounds(157, 34, 244, 189);
		contentPane.add(panel);
		panel.setLayout(null);
		
		JButton button = new JButton("b");
		button.setBounds(70, 5, 89, 23);
		panel.add(button);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBounds(10, 50, 224, 128);
		panel.add(panel_1);
		
		JButton button_1 = new JButton("c");
		panel_1.add(button_1);
		
		colorirFilhos(contentPane);
	}
	
	public static void colorirFilhos(Container container){
		// Percorre todos os filhos
		for(Component component : container.getComponents()){
			
			// Se for do tipo Container, pode ter filhos também
			if(component instanceof Container){
				
				// Colore apenas os JButton's
				if(component instanceof JButton){
					JButton botao = (JButton) component;
					botao.setBackground(Color.RED);
				}
				
				colorirFilhos((Container) component);
			}
		}
	}
}

Se adicionar botões dinamicamente, basta chamar o método colorirFilhos novamente.

Abcs!

Thallysson

Muito obrigado, solucionou meu problema :slight_smile:

Criado 1 de abril de 2016
Ultima resposta 2 de abr. de 2016
Respostas 2
Participantes 2