通过选中复选框,复选框文本和jLabel图标应显示在jEditorPane中

时间:2014-07-11 22:50:08

标签: java swing jeditorpane

我的JCheckBox有一些文字,JLabelImageIcon

要求是选中JCheckBoxJCheckBox文字和JLabel图标应显示在JEditorPane

我用过

if (jCheckBox3.isSelected()) {
    s1 = jCheckBox3.getText() + jLabel1.getIcon() ;

    }

jEditorPane1.setText(s1);

输出

“复选框文本”文件:/ G:/myProject/build/classes/myproject/img.png

而不是图像我得到图像路径

1 个答案:

答案 0 :(得分:0)

Before JCeckBox is checked After you checked the JCeckBox

这是一个如何做到这一点的例子:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;


public class CheckBoxCheckingDisplayImagePanel extends JPanel implements ActionListener {

    private JCheckBox checkBox;
    private JLabel label;
    private JEditorPane editorPane;
    private JPanel editorPanel;

    public CheckBoxCheckingDisplayImagePanel() {

        try {
            JPanel panel = new JPanel(new GridLayout(0, 2));
            this.setLayout(new BorderLayout(10, 10));
            this.add(panel,BorderLayout.NORTH);
            ImageIcon icon = new ImageIcon(ImageIO.read(new URL("http://i.stack.imgur.com/lxthA.jpg")));
            label = new JLabel(icon, SwingConstants.HORIZONTAL);
            checkBox = new JCheckBox("Check me!");
            checkBox.addActionListener(this);
            panel.add(label);
            panel.add(checkBox);
            editorPane = new JEditorPane();
            this.add(editorPane,BorderLayout.CENTER);
        } catch (MalformedURLException ex) {
            Logger.getLogger(CheckBoxCheckingDisplayImagePanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CheckBoxCheckingDisplayImagePanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource().equals(checkBox)) {
            editorPane.setContentType("text/html");
            editorPane.setText("<img src=\"http://i.stack.imgur.com/lxthA.jpg\">");
        }
    }


}

帕特里克