以下代码呈现没有文本的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);
});
}
}
工作正常,但有一些令人讨厌的含义,如无法更改按钮操作而不重置其文本后.
为什么?!