当用户勾选复选框菜单项时,我想在控制台上向用户显示一些消息。我怎样才能做到这一点?目前,当用户检查复选框时,消息仅显示在框架上。如何在控制台上显示一些消息?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class CheckBoxMenu extends JFrame {
private JLabel statusbar;
public CheckBoxMenu() {
initUI();
}
private void initUI() {
createMenuBar();
statusbar = new JLabel("On Progress...");
statusbar.setBorder(BorderFactory.createEtchedBorder());
add(statusbar, BorderLayout.SOUTH);
setTitle("JCheckBoxMenuItem");
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu viewMenu = new JMenu("View");
JCheckBoxMenuItem sbarMi = new JCheckBoxMenuItem("Show Statusbar");
sbarMi.setSelected(true);
sbarMi.addItemListener((ItemEvent e) -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
statusbar.setVisible(true);
} else {
statusbar.setVisible(false);
}
});
viewMenu.add(sbarMi);
menubar.add(fileMenu);
menubar.add(viewMenu);
setJMenuBar(menubar);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
CheckBoxMenu ex = new CheckBoxMenu();
ex.setVisible(true);
});
}
}
答案 0 :(得分:0)
您可以在监听器中使用System.out.println
调用,或使用记录器。
sbarMi.addItemListener((ItemEvent e) -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
statusbar.setVisible(true);
// Using System.out
System.out.println("On Progress...");
// Or using a logger (defined somewhere else, using Logger.getLogger or a logging framework.)
logger.info("On Progress.");
} else {
statusbar.setVisible(false);
}
});