3

I have a JButton that is constructed using an Action and this action has a name that is contains html.

I then go about setting the mnemonic on the JButton by first parsing out html to get the first character in the name.

For example, the JButton name might be "<html>Test<br>Button</html>", so after parsing the html the mnemonic key should be "T".

So now when the JButton is rendered I can push alt-T to activate the button, however the underline mnemonic indicator on the T is not present.

Would anyone know a way to get this to occur?

sateesh
  • 27,947
  • 7
  • 36
  • 45
Denis Sadowski
  • 3,035
  • 5
  • 24
  • 26

1 Answers1

1

It is unclear to me what you mean by "setting the mnemomic on the JButton by parsing html". The mnemonic can be set on a JButton by calling the method setMnemonic in the JButton class. I tried below piece of code and when I press Alt+P I get the message I am pressed printed in the console.

public class HTMLButton extends JPanel implements ActionListener {
    JButton     b1;
    public HTMLButton() {
        super(new BorderLayout());
        b1 = new JButton("<html><b><u>P</u>ress</b></html>");
        b1.setMnemonic(KeyEvent.VK_P);
        b1.addActionListener(this);
        add(b1);
    }

    public void actionPerformed(final ActionEvent e) {
        System.out.println("I am pressed");
    }
}

Also see the section How to Use HTML in Swing Components in the Java tutorial.

sateesh
  • 27,947
  • 7
  • 36
  • 45
  • Sorry I guess I should have been more clear. I have a framework for displaying error messages that have button in my app, so for the same of reusable code what I do is parse the html (in your case "Press") in order to find the character on which the mnemonic should be set (in this case P). – Denis Sadowski Jan 24 '10 at 17:15
  • 1
    If there was no html in the JButton name, and you set a mnemonic then it would underline the P on its own. However in this case it seems that you had to add html formatting to do this yourself. Is there no way to make the JButton do the underlining itself, as opposed to having to put it in the html. As it might be the case that I have two buttons in my error framework, "Press
    Me" and "Push
    Me". In which case one of them will have a differnt mnemonic set for it, and I would prefer not to couple the underlining to the html.
    – Denis Sadowski Jan 24 '10 at 17:18
  • 1
    I didn't get your question. the code "jButton.setMnemonic('P');" already sets the underline in P. The html is unnessecary in this case. – marionmaiden Jan 25 '10 at 12:23
  • 2
    I've found that if I have: b1 = new JButton("Press
    Button"); b1.setMnemonic(KeyEvent.VK_P); That the P will not be underlined.
    – Denis Sadowski Jan 25 '10 at 19:37