-1

I am trying to change font of my JTextField by using a JComboBox. The problem is when I try to run the program it works fine but now when I try to change font in the program I get tons of errors. Here is the code:

    JTextField myJTextField = new JTextField ("This text will be changed!", 20);
    myJTextField.setEditable(false);
    add(myJTextField);

    Font font = new Font ("Serif", Font.PLAIN, 14);
    Font font1 = new Font ("Serif", Font.BOLD, 14);
    Font font2 = new Font ("Serif", Font.ITALIC, 14);
    Font myFonts [] = {font ,font1, font2};
    myBox1 = new JComboBox (myFonts);

    myBox1.addItemListener (new ItemListener () {
        public void itemStateChanged (ItemEvent e) {
            Font myFonts [] = {font ,font1, font2};
            int array [] = {0,1,2};

            if (e.getStateChange() == ItemEvent.SELECTED)
                    myFonts [0] = new Font ("Serif", Font.PLAIN, 14);
            else if (e.getStateChange() == ItemEvent.SELECTED)
                    myFonts [1] = new Font ("Serif", Font.BOLD, 14);
            else if (e.getStateChange() == ItemEvent.SELECTED)
                    myFonts [2] = new Font ("Serif", Font.ITALIC, 14);

            myJTextField.setFont(myFonts[array.length]);
        }
    }); add(myBox1);

Any help will be really appreciated.

Cookie
  • 53
  • 1
  • 4
  • If you get tons of errors and need our help, it makes sense for you to post some of them, no? Please read the [help] section for more help on asking a good question. Also, consider taking a little time to create and post a [minimal example program](http://stackoverflow.com/help/mcve) as that would help us better understand your problem. – Hovercraft Full Of Eels Jul 29 '14 at 14:01
  • 2
    `myJTextField.setFont(myFonts[array.length]);` Can't do that since that will give you Index Out Of Bounds Since the length of array is the same length as myFonts and Arrays are zero-based index in Java – gtgaxiola Jul 29 '14 at 14:02

2 Answers2

1

If I am not erring, every if condition the same. And myFonts[array.length] will yield an IndexOutOf Bounds.

myBox1.addItemListener (new ItemListener() {
    @Override
    public void itemStateChanged (ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            Font font = (Font) e.getItem();
            myJTextField.setFont(font);
        }
    }
};
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

You can't pass Font objects directly into a JComboBox constructor. Look into using setRenderer() and creating your own Renderer class like this example:

Getting fonts, sizes, bold,...etc

Community
  • 1
  • 1
John V
  • 269
  • 3
  • 15