Java JButton.setAction(…)null的按钮文本
以下代码呈现没有文本的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,它可以是importnant)
。
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 } }
最好在JButton构造函数中输入Text,因为JButton构造函数具有Strings而不是String Variable的参数。
JButton button = new JButton("Invisible");