I have a component that is a JPanel
that contains two JTextFields
, I wanted to be able to apply borders and backgrounds only to the JTextFields
, without applying it in the panel.
I treat everything on the main screen to be applied to everything that is of type JComponent
, and also because the component can be applied to multiple screens.
For other components like JTextFields
and JTextArea
, it applies correctly.
Simplified example:
package focu;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class TelaPrincipal extends JFrame implements FocusListener {
private JLabel label = new JLabel("Componente:");
private MeuComponente comp = new MeuComponente();
private JLabel label2 = new JLabel("JTextField:");
JTextField jt = new JTextField();
private JLabel label3 = new JLabel("JTextArea:");
JTextArea area = new JTextArea();
public static void main(String[] args) {
TelaPrincipal teste = new TelaPrincipal();
teste.setVisible(true);
}
public TelaPrincipal() {
setTitle("Teste");
add(montaTela());
//setSize(150, 300);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JComponent montaTela() {
JPanel painel = new JPanel();
painel.setLayout(new FlowLayout());
painel.add(label);
painel.add(comp);
comp.addFocusListener(this);
painel.add(label2);
painel.add(jt);
jt.setPreferredSize(new Dimension(100, 20));
jt.addFocusListener(this);
painel.add(label3);
painel.add(area);
area.setPreferredSize(new Dimension(100, 100));
area.addFocusListener(this);
return painel;
}
@Override
public void focusGained(FocusEvent fe) {
if (fe.getSource() instanceof JComponent) {
((JComponent) fe.getSource()).setBorder(new LineBorder(Color.RED));
((JComponent) fe.getSource()).setBackground(Color.LIGHT_GRAY);
}
}
@Override
public void focusLost(FocusEvent e) {
((JComponent) e.getSource()).setBorder(new LineBorder(Color.GRAY));
((JComponent) e.getSource()).setBackground(Color.WHITE);
}
}
class MeuComponente extends JPanel
{
public JTextField jt01 = new JTextField();
public JTextField jt02 = new JTextField();
public MeuComponente()
{
setLayout(new FlowLayout());
add(jt01);
jt01.setPreferredSize(new Dimension(70, 20));
add(jt02);
jt02.setPreferredSize(new Dimension(70, 20));
}
}