在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) {
}
}
我需要将消息传送到我更改颜色的界面。我该怎么做呢?有没有其他方法可以做到这一点?
答案 0 :(得分:0)
简单地:
repaint
以更新您的身材。答案 1 :(得分:0)
首先,您可能希望阅读Performing Custom Painting和Painting in AWT and Swing,然后从{{1}中删除addMouseMotionListener
,addMouseListener
和setBackground
}}方法(并使用paint
)代替。
接下来,您需要确定处理色彩管理的最佳方式,例如,您可以在paintComponent
上使用setForeground
并在您调整JPanel
颜色时漆...
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);
}
方法创建整个应用程序,除了initi thread问题之外,您遇到了main
引用和可重用性的各种问题。 ..