package swingnodesample; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.ImageIcon; /* * ButtonHtmlDemo.java使用以下文件: * images/right.gif * images/middle.gif * images/left.gif */ public class ButtonHtml extends JPanel implements ActionListener { protected JButton b1, b2, b3; public ButtonHtml() { ImageIcon leftButtonIcon = createImageIcon("images/right.gif"); ImageIcon middleButtonIcon = createImageIcon("images/middle.gif"); ImageIcon rightButtonIcon = createImageIcon("images/left.gif"); b1 = new JButton("<html><center><b><u>禁用</u></b><br>" + "<font color=#ffffdd>中间按钮</font>", leftButtonIcon); Font font = b1.getFont().deriveFont(Font.PLAIN); b1.setFont(font); b1.setVerticalTextPosition(AbstractButton.CENTER); b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales b1.setMnemonic(KeyEvent.VK_D); b1.setActionCommand("disable"); b2 = new JButton("中间按钮", middleButtonIcon); b2.setFont(font); b2.setForeground(new Color(0xffffdd)); b2.setVerticalTextPosition(AbstractButton.BOTTOM); b2.setHorizontalTextPosition(AbstractButton.CENTER); b2.setMnemonic(KeyEvent.VK_M); b3 = new JButton("<html><center><b><u>启用</u></b><br>" + "<font color=#ffffdd>中间按钮</font>", rightButtonIcon); b3.setFont(font); //Use the default text position of CENTER, TRAILING (RIGHT). b3.setMnemonic(KeyEvent.VK_E); b3.setActionCommand("enable"); b3.setEnabled(false); //Listen for actions on buttons 1 and 3. b1.addActionListener(this); b3.addActionListener(this); b1.setToolTipText("点击此按钮禁用中间按钮。"); b2.setToolTipText("点击此中间按钮时不会有任何反应。"); b3.setToolTipText("点击此按钮启用中间按钮。"); //Add Components to this container, using the default FlowLayout. add(b1); add(b2); add(b3); } @Override public void actionPerformed(ActionEvent e) { if ("disable".equals(e.getActionCommand())) { b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } else { b2.setEnabled(true); b1.setEnabled(true); b3.setEnabled(false); } } /** 返回一个ImageIcon,如果路径无效则返回null。 * @param path * @return */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = ButtonHtml.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("找不到文件: " + path); return null; } } }
JavaFX:互操作性