Search code examples
javaswinginheritancestylesjtextfield

Using styled JTextfField multiple times? (java)


I want to have 3 different textfields that should use the same styling,

txt = new JTextField();
txt.setText("Room floor number");
txt.setForeground(Color.WHITE);
txt.setEditable(false);
txt.setColumns(10);
txt.setBorder(null);
txt.setBackground(Color.GRAY);

Now what i want is another textfield with these settings applied by inheritance? Like in CSS, you can use:

textfield textfield1 {
- code1 -
- code2 -
}
textfield textfield1 textfield2 {
- code3 -
}

Not sure if this is correct but you get the deal, here textfield2 gets code1 and code2 and then adds (could replace aswell) code3 to only the textfield2.

So basically i want to use txt style for lets say txt2 and txt3. I could just txt2 everything but thats not optimal now is it? :D


Solution

  • Yes, you can, but not quite the way your thinking. You have at least two options...

    You Could

    Write a method that takes a JTextField and applies the changes you want...

    public void applyFormat(JTextField field) {
        txt.setForeground(Color.WHITE);
        txt.setEditable(false);
        txt.setColumns(10);
        txt.setBorder(null);
        txt.setBackground(Color.GRAY);    
    }
    

    Or You Could

    Write a factory method that generates a new JTextField with the required formatting applied...

    public JTextField createFormattedField() {
        JTextField txt = new JTextField();
        txt.setForeground(Color.WHITE);
        txt.setEditable(false);
        txt.setColumns(10);
        txt.setBorder(null);
        txt.setBackground(Color.GRAY);    
        return txt;
    }
    

    For example...