以下示例向您展示了您想要执行的操作,但使用的是文本而不是图标。该程序切换图像、文本或您显示的任何内容。
如果您使用 JLabel 的原因是因为您想要一个平面按钮,您可以添加代码:
private void makeButtonFlat(final JButton makeMeAFlatButton) {
makeMeAFlatButton.setOpaque(false);
makeMeAFlatButton.setFocusPainted(false);
makeMeAFlatButton.setBorderPainted(false);
makeMeAFlatButton.setContentAreaFilled(false);
makeMeAFlatButton.setBorder(BorderFactory.createEmptyBorder());
}
并从
public void makeLayout() {
makeButtonFlat(playButton);
add(playButton);
}
然后它将看起来像一个 JLabel,但充当一个按钮,这更合乎逻辑。
代码片段:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Playful {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Playful");
JPanel playPanel = new PlayPanel();
frame.getContentPane().add(playPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(400, 250));
frame.setLocationRelativeTo(null); // Center
frame.pack();
frame.setVisible(true);
}
});
}
static class PlayPanel extends JPanel {
enum State {
PLAY,
PAUSE;
public State toggle() {
switch (this) {
case PLAY:
return PAUSE;
case PAUSE:
return PLAY;
default:
throw new IllegalStateException("Unknown state " + this);
}
}
}
private State state;
private JButton playButton;
private ActionListener playActionListener;
PlayPanel() {
createComponents();
createHandlers();
registerHandlers();
makeLayout();
initComponent();
}
public void createComponents() {
playButton = new JButton();
}
public void createHandlers() {
playActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
toggleState();
}
});
}
};
}
public void registerHandlers() {
playButton.addActionListener(playActionListener);
}
public void makeLayout() {
add(playButton);
}
public void initComponent() {
state = State.PAUSE;
updatePlayButton();
}
private void toggleState() {
state = state.toggle();
updatePlayButton();
}
private void updatePlayButton() {
playButton.setText(state.name());
}
}
}