我如何用一个文件中的代码影响另一个文件



在NetBeans 8.0中,我制作了一个Paint程序,我需要主文件中的代码来影响我的另一个文件(一个接口文件)中的某些内容。我该怎么做呢?我的代码:

package paintapp;

import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.ActionListener;
public class PaintApp extends javax.swing.JFrame {
    int colourR, colourG, colourB;
    static String Ccolour = "BLACK";
    public static void main(String[] args) {
        JFrame main = new JFrame("Tessellating Pi - Paint");
        PaintInterface pi = new PaintInterface();
        main.add(pi);
        main.setSize(1000, 1000);
        main.setVisible(true);
        JFrame j = new JFrame("Colour Chooser");
        JButton c = new JButton("Change Colour");
        j.add(c);
        j.setSize(150, 100);
        j.setVisible(true);
        c.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if ("BLACK".equals(Ccolour)) {
                    Ccolour = "RED";
                    //code to change code in interface to set colour to red
                }
            }
        }
        );
    }
}

这是接口:

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class PaintInterface extends JPanel implements MouseListener, MouseMotionListener {
    static int x = 0, y = 0;
    @Override
    public void paint(Graphics g) {
        this.setBackground(Color.white);
        this.addMouseMotionListener(this);
        this.addMouseListener(this);
        g.setColor(Color.black);
        g.fillRect(x, y, 3, 3);
    }
    @Override
    public void mouseDragged(MouseEvent e) {
        x = e.getX();
        y = e.getY();
        repaint();
    }
    @Override
    public void mouseClicked(MouseEvent e) {
    }
    @Override
    public void mousePressed(MouseEvent e) {
    }
    @Override
    public void mouseReleased(MouseEvent e) {
    }
    @Override
    public void mouseEntered(MouseEvent e) {
    }
    @Override
    public void mouseExited(MouseEvent e) {
    }
    @Override
    public void mouseMoved(MouseEvent e) {
    }
}

我需要把我改变颜色的消息传递给接口。我该怎么做呢?有没有别的方法来做这件事?

简体:

  1. 创建setter方法来设置新颜色。
  2. 调用repaint更新you形状

首先,您可能想在AWT和Swing中阅读执行自定义绘画和绘画,然后从paint方法中删除addMouseMotionListener, addMouseListenersetBackground(并使用paintComponent)。

接下来,你需要决定处理颜色管理的最佳方式,例如,你可以简单地在JPanel上使用setForeground,并在绘画时调整Graphics的颜色…

@Override
public void actionPerformed(ActionEvent e) {
    if ("BLACK".equals(Ccolour)){
        Ccolour="RED";
        pi.setForeground(Color.RED);
        pi.repaint();
    }
}

这意味着pi将需要成为一个实例变量或final

final PaintInterface pi=new PaintInterface();

然后在PaintInterface类中,您需要更新paintComponent方法

@Override
protected void paintComponent (Graphics g) {
    super.paintComponent(g);
    g.setColor(getForeground());
    g.fillRect(x,y,3,3);
}

我也不鼓励您在main方法中创建整个应用程序,除了初始化线程问题外,您还会遇到static引用和可重用性的各种问题…

相关内容

最新更新