【问题标题】:JButton text changes when an Action is set设置 Action 时 JButton 文本发生变化
【发布时间】:2016-03-26 11:09:31
【问题描述】:

我正在开发一个swing GUI 项目,我有一个JButton 可以将文本转换为JTextPane 粗体。我使用Action 来执行此操作。

这是Action的代码

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

这是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);

如果不包含Action,按钮上的文本是粗体“B”,这就是我想要的。出现的问题是,当我添加操作时,它会将按钮上的文本更改为“font-bold”。

为什么会发生这种情况,我该如何解决?

【问题讨论】:

  • bold.setBounds(393, 15, 100, 100); 1) Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 2) 为了尽快获得更好的帮助,请发帖minimal reproducible exampleShort, Self Contained, Correct Example
  • 动作是独立的工作单元,其中包括按钮用来设置其文本的动作的名称

标签: java swing jbutton


【解决方案1】:

当您使用 Action 时,Action 的属性默认为按钮。

如果您不想要“font-bold”,那么您需要在设置 Action 之后更改文本:

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

也不要使用 setBounds() 方法。 Swing 旨在与布局管理器一起使用。

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

【讨论】:

  • 谢谢,我刚想试试。我使用setBounds() 只是因为它更容易布局东西,但我明白你在说什么
【解决方案2】:

StyledEditorKit 提供的动作改变了属于JTextComponent 的子类提供的视图的Document 模型,如图here。要更改JButton 使用的字体,请使用UIManager 更改具有键"Button.font" 的属性,如here 所示。

因为要动态改变按钮的外观,所以使用UIManager获取按钮的预期字体,并在按钮的Action中指定派生字体,如下图:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2015-09-08
    • 2015-06-04
    相关资源
    最近更新 更多