如何在 Java 中设置 JCheckBox 的工具提示文本?
对于 JCheckBox,请使用以下设置工具提示文本
checkBox1.setToolTipText("Sports Football"); checkBox2.setToolTipText("Sports Tennis");
将光标放在特定文本上时,工具提示文本可见。
以下是示例。在这里,我们设置了两种运动的工具提示文本
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingDemo(){ prepareGUI(); } public static void main(String[] args){ SwingDemo swingControlDemo = new SwingDemo(); swingControlDemo.showCheckBoxDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java Swing"); mainFrame.setSize(600,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showCheckBoxDemo(){ headerLabel.setText("Favourite Sports"); final JCheckBox checkBox1 = new JCheckBox("Football"); final JCheckBox checkBox2 = new JCheckBox("Tennis"); checkBox1.setToolTipText("Sports Football"); checkBox2.setToolTipText("Sports Tennis"); checkBox1.setMnemonic(KeyEvent.VK_F); checkBox2.setMnemonic(KeyEvent.VK_T); checkBox1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { statusLabel.setText("Football Checkbox: " + (e.getStateChange()==1?"checked":"unchecked")); } }); checkBox2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { statusLabel.setText("Tennis Checkbox: "+ (e.getStateChange()==1?"checked":"unchecked")); } }); controlPanel.add(checkBox1); controlPanel.add(checkBox2); mainFrame.setVisible(true); } }
输出如下。在这里,您可以在鼠标悬停时看到工具提示可见
输出
广告