3

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?

Chris G
  • 80
  • 1
  • 2
  • 9
  • `bold.setBounds(393, 15, 100, 100);` 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Mar 26 '16 at 01:40
  • Action's are self contained units of work, which include the NAME of the action which is used by buttons to set their text – MadProgrammer Mar 26 '16 at 02:24

2 Answers2

1

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);
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

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);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thanks, i had just thought to try that. I use the `setBounds()` only because it is so much easier to layout things, but i understand what you're saying – Chris G Mar 26 '16 at 03:11