gpt4 book ai didi

Java JButton.setAction(...) null 的按钮文本

转载 作者:搜寻专家 更新时间:2023-11-01 02:42:16 25 4
gpt4 key购买 nike

以下代码呈现一个没有文本的 JButton:

public abstract class Test {

public static void main(String... args) {

try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}

SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
JPanel panel = new JPanel();

String text = "Invisible";
JButton button = new JButton(text); // blank button rendered ???

System.out.println(button.getText()); // prints Invisible

button.setAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
// do nothing
}
});

System.out.println(button.getText()); // prints null ???

button.setFocusable(false);

button.setPreferredSize(new Dimension(100, 40));

panel.add(button);

frame.setResizable(false);
frame.getContentPane().add(panel);

frame.pack();
frame.setVisible(true);

});

}

}

如果我删除对 button.setAction(...) 的调用,它会呈现包含文本的按钮。

或者:

public abstract class Test {

public static void main(String... args) {

try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}

SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
JPanel panel = new JPanel();

String text = "Invisible";
JButton button = null;
button = new JButton(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
// do nothing
}
});

button.setText(text); // renders the button with text
System.out.println(button.getText()); // prints Invisible obviously

button.setFocusable(false);

button.setPreferredSize(new Dimension(100, 40));

panel.add(button);

frame.setResizable(false);
frame.getContentPane().add(panel);

frame.pack();
frame.setVisible(true);

});

}

}

工作正常,但有一些令人讨厌的含义,例如无法更改按钮操作,之后不重置其文本。

为什么?!

最佳答案

@Dima Maligin

  • 未回复,将被删除

  • 应该声明 Swing Action(也覆盖 isEnabled,这很重要)

.

 private class SwingAction extends AbstractAction {

//or public Action SwingAction() {
// return new AbstractAction("Invisible") {
// here to override AbstractAction
// }
// }

public SwingAction() {
putValue(NAME, "Invisible"); // bounds properties
putValue(SHORT_DESCRIPTION, "Invisible");
}

@Override
public void actionPerformed(ActionEvent e) {
// do nothing
}
}

关于Java JButton.setAction(...) null 的按钮文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30851673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com