Chris G
Chris G

Reputation: 80

JButton text changes when an Action is set

I am working on a swing GUI project and i have a JButton that turns text inside a JTextPane bold. I use an Action to do this.

Here's the code for the Action

public static Action boldAction = new StyledEditorKit.BoldAction();

Here's the code for the JButton

JButton bold = new JButton("B");
bold.setFont(new Font("Arial", Font.BOLD, 15));
bold.setBounds(393, 15, 100, 100);
bold.setBackground(Color.WHITE);
bold.setAction(boldAction);
frame.add(bold);

Without the Action included the text on the button is a bold "B", which is what I want. The issue that arises is that when I add in the action, it changes the text on the button to say "font-bold".

Why does this happen, and how can I fix this?

Upvotes: 3

Views: 458

Answers (2)

camickr
camickr

Reputation: 324108

When you use an Action the properties of the Action are defaulted to the button.

If you don't want "font-bold" then you need to change the text AFTER setting the Action:

JButton bold = new JButton( boldAction);
bold.setText("B");

Also don't use the setBounds() method. Swing was designed to be used with layout managers.

//bold.setBounds(393, 15, 100, 100);

Upvotes: 1

trashgod
trashgod

Reputation: 205785

The actions provided by StyledEditorKit alter the Document model belonging to the view provided by subclasses of JTextComponent, as shown here. To change the font used by a JButton, use the UIManager to change the property having the key "Button.font", as shown here.

Because you want to change the button's appearance dynamically, use the UIManager to obtain the button's expected font and specify a derived font in the button's Action, as shown below:

image

final JButton button = new JButton();
Action action = new AbstractAction("Bold") {
    Font font = (Font) UIManager.get("Button.font");

    @Override
    public void actionPerformed(ActionEvent e) {
        button.setFont(font.deriveFont(Font.BOLD));
    }
};
button.setAction(action);

Upvotes: 1

Related Questions