【问题标题】:How to set the background image for a textarea on click of a button?如何在单击按钮时为文本区域设置背景图像?
【发布时间】:2012-01-20 15:37:44
【问题描述】:

我想通过单击按钮将文本区域的图像设置为背景图像。这怎么可能?

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class BackgroundSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Background Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final ImageIcon imageIcon = new ImageIcon("draft.gif");
    JTextArea textArea = new JTextArea() {
      Image image = imageIcon.getImage();

      Image grayImage = GrayFilter.createDisabledImage(image);
      {
        setOpaque(false);
      }

  public void paint(Graphics g) {
    g.drawImage(grayImage, 0, 0, this);
    super.paint(g);
  }
};
JScrollPane scrollPane = new JScrollPane(textArea);
Container content = frame.getContentPane();
content.add(scrollPane, BorderLayout.CENTER);
frame.setSize(250, 250);
frame.setVisible(true);
  }
}

这就是我所说的。如何做同样的事情,但使用 actionlistener(点击按钮)

【问题讨论】:

  • 到目前为止您尝试过什么?您是否研究过事件监听器,尤其是动作监听器?
  • 在调用文本区域的构造函数时,我能够在文本区域中显示背景图像,但我不确定如何使用动作侦听器来执行此操作。
  • 关于信息,我在这里处理一个小程序..
  • 从您的问题中删除 HTML 标记
  • 请按照您的预期检查代码格式。该示例中的格式化代码中缺少两个“} }”。

标签: java swing applet


【解决方案1】:

您需要扩展您的 JTextPane 类并创建一个setImage(Image image) 方法。此方法将保存图像的引用,然后调用 repaint()。

另外,您应该重写paintComponent() 方法,而不是paint() 方法。忽略任何其他说明的教程,因为它已经过时了 10 年。

【讨论】:

【解决方案2】:

试试这个:

class MyTextArea extends JTextArea {
    private Image backgroundImage;

    public MyTextArea() {
        super();
        setOpaque(false);
    }

    public void setBackgroundImage(Image image) {
        this.backgroundImage = image;
        this.repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        g.setColor(getBackground());
        g.fillRect(0, 0, getWidth(), getHeight());

        if (backgroundImage != null) {
            g.drawImage(backgroundImage, 0, 0, this);
        }

        super.paintComponent(g);
    }
}

然后在你的动作监听器中:

@Override
public void actionPerformed(ActionEvent arg0) {
    Image image = ImageIO.read(..);
    if (image != null)
        textArea.setBackgroundImage(image);     
}

这是一个例子:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class BackgroundDemo {
    private static void createAndShowUI() {

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
        } catch (InstantiationException ex) {
        } catch (IllegalAccessException ex) {
        } catch (UnsupportedLookAndFeelException ex) {
        }

        final JFrame frame = new JFrame("BackgroundDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel buttonsPanel = new JPanel();

        final MyTextArea textArea = new MyTextArea();
        textArea.setText("Some text");

        JButton loadButton = new JButton("Set background");
        buttonsPanel.add(loadButton);

        loadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
                int returnVal = fc.showOpenDialog(frame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    try {
                        Image image = ImageIO.read(fc.getSelectedFile());
                        if (image != null)
                            textArea.setBackgroundImage(image);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        JPanel content = new JPanel(new BorderLayout());
        content.add(buttonsPanel, BorderLayout.SOUTH);
        content.add(new JScrollPane(textArea), BorderLayout.CENTER);

        frame.add(content);
        frame.setSize(new Dimension(300, 300));
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    static class MyTextArea extends JTextArea {
        private Image backgroundImage;

        public MyTextArea() {
            super();
            setOpaque(false);
        }

        public void setBackgroundImage(Image image) {
            this.backgroundImage = image;
            this.repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            g.setColor(getBackground());
            g.fillRect(0, 0, getWidth(), getHeight());

            if (backgroundImage != null) {
                g.drawImage(backgroundImage, 0, 0, this);
            }

            super.paintComponent(g);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

【讨论】:

  • -1, 1) 类名不应该是 TextArea,因为已经有一个同名的 AWT 组件,这可能会导致混淆。 2)您不会创建 ImageIcon 只是为了读取图像。相反,您可能会使用 ImageIO。 3)因为这个答案是在2小时前给出的,所以没有必要把论坛弄得乱七八糟。如第 1 点和第 2 点所述,用勺子喂食的代码无济于事,而且会带来坏习惯。
猜你喜欢
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 2020-02-09
  • 2011-07-21
相关资源
最近更新 更多