簡體   English   中英

添加到 JButton 的 ActionListener 和 MouseListener 都不能在 JPanel 的 PaintComponent 中設置顏色

[英]Neither ActionListener nor MouseListener added to JButton works for setting color in PaintComponent in JPanel

我正在創建一個 Java 程序來模擬 Windows 95 中的 Microsoft Paint。底部有一個調色板。 單擊調色板中的任何顏色都會更改鉛筆等繪畫工具的顏色。 我嘗試使用 Graphics2D 根據在調色板中單擊的按鈕設置工具的每種顏色。 我嘗試將 ActionListener 添加到表示調色板中顏色按鈕的 JButton,然后將其更改為 MouseListener。 但是我的代碼不適用於此目的。 我不確定這是否會發生,因為 ActionListener/MouseListener 包含在 for 循環中,然后包含在 MouseMotionListener 中。 在此代碼中,添加到 JButton 的 ActionListener 和 MouseListener 均無法在 JPanel 中的 PaintComponent 中設置顏色。 有沒有更好的方法來重寫這段代碼?

這是我創建的 Paint 模擬的屏幕截圖:在此處輸入圖像描述

我的代碼如下:

paintOpen = new JFrame();
paintCanvasPanel = new JPanel() {
  private static final long serialVersionUID = 1L;
  public void paintComponent(Graphics g) {
    this.addMouseMotionListener(new MouseMotionListener() {
      public void mouseDragged(MouseEvent e) {
        if (SwingUtilities.isLeftMouseButton(e)) {
          Graphics2D g = (Graphics2D) getGraphics();
          g.drawLine(e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen());
          g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g.setStroke(new BasicStroke(WIDTH, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL));
          for (int i = 0; i < 28; i++) {
            //Neither ActionListener nor MouseListener works
            paintColorButton[i].addMouseListener(new MouseAdapter() {
              public void mousePressed(MouseEvent e) {
                for (int j = 0; j < 28; j++) {
                  g.setColor(paintPaletteColor[j]);
                }
              }

            });
          }
        }
      }
      public void mouseMoved(MouseEvent e) {

      }
    });

  }
};
paintScrollPane = new JScrollPane(paintCanvasPanel);
paintScrollPane.setBackground(white);
paintScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
paintScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
paintOpen.getContentPane().add(paintScrollPane);
paintOpen.getContentPane().setBackground(white);
paintOpen.setAlwaysOnTop(true);
paintOpen.setBounds(200, 0, 420, 600);
paintOpen.setExtendedState(JFrame.MAXIMIZED_BOTH);
paintOpen.setIconImage(paintIcon.getImage());
paintOpen.setTitle("untitled - Paint");
paintPalettePanel = new JPanel();
paintColorButton = new JButton[28];
for (int i = 0; i < 28; i++) {
  paintColorButton[i] = new JButton();
  paintColorButton[i].setBackground(paintPaletteColor[i]);
  paintPalettePanel.add(paintColorButton[i]);
}
paintOpen.add(paintPalettePanel, BorderLayout.SOUTH);
}

我嘗試將ActionListener 更改為MouseListener,但仍然無法更改顏色。

            for (int i = 0; i < 28; i++) {
              paintColorButton[i].addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  for (int j = 0; j < 28; j++) {
                    g.setColor(paintPaletteColor[j]);
                  }
                }

              });
            }

我不確定這是否有任何幫助,但我拿了你的代碼,整理了一下,刪除了多余的並添加了缺失的。 我只能建議你仔細看看事情。 Swing 是面向事件的,您必須記住何時移動鼠標或按下按鈕,以便能夠在paintComponent事件中處理此信息。 在這種情況下,必須在mouseDragged中調用repaint()以便結果可見。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PaintPanel extends JPanel implements MouseMotionListener, ActionListener{
    private Color[] paintPaletteColor = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW };
    private Color drawColor = Color.BLACK;
    private MouseEvent e;

    public static void main(String[] args) {
        new PaintPanel();
    }

    public PaintPanel() {
        addMouseMotionListener(this);
        setPreferredSize(new Dimension(1024, 768));

        JScrollPane paintScrollPane = new JScrollPane(this);
        paintScrollPane.setBackground(Color.WHITE);
        paintScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        paintScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        paintScrollPane.setBackground(Color.white);

        JPanel paintPalettePanel = new JPanel();
        // Add a button for each color defined in paintPaletteColor. 
        // Add more colors there for additional buttons.
        for (int i = 0; i < paintPaletteColor.length; i++) {
            JButton button = new JButton();
            button.setBackground(paintPaletteColor[i]);
            button.addActionListener(this);
            paintPalettePanel.add(button);
        }

        JFrame paintOpen = new JFrame();
        paintOpen.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        paintOpen.add(paintScrollPane);
        paintOpen.add(paintPalettePanel, BorderLayout.SOUTH);
        paintOpen.setIconImage(new ImageIcon("Icon.png").getImage());
        paintOpen.setTitle("untitled - Paint");
        paintOpen.pack();
        paintOpen.setLocationRelativeTo(null);
        paintOpen.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // A button was clicked - remember its color.
        drawColor = ((JButton)e.getSource()).getBackground();
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        // The mouse was dragged - remember the new position and repaint the panel.
        this.e = e;
        repaint();
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        //
    }

    @Override
    public void paintComponent(Graphics g) {
        // triggered `repaint`, so let's go.
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setStroke(new BasicStroke(4, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL));
        g2d.setColor(drawColor);
        // mouse dragged ? 
        if(e != null) g2d.drawLine(e.getX(), e.getY(), e.getX(), e.getY());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM