我正在做一个“绘画”项目。到目前为止,我有一个带有1个按钮“Ligne”和一个可绘制面板的GUI。在我的类Paint_Desin中,有一个方法调用TracerLigne()。这种方法按照随机的模式画线。我想做的是放置一个鼠标监听器,使x1,y1=点击1,x2,y2=点击2。这是我的密码。谢谢(对法语评论感到抱歉)
//cree une fenetre
public class QUESTION {
public static void main(String[] args) {
Paint_GUI test2 = new Paint_GUI();
}
}
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Paint_GUI extends JFrame {
//Panels contenant tout les bouton de mon interface
private JPanel panelBtn;
//Bar d outil Btn
private JButton BtnTracerLigne;
//créer l objet Paint_Dessin
private Paint_Dessin espaceDessin = new Paint_Dessin();
public Paint_GUI() {
final int WINDOW_WIDTH = 650;
final int WINDOW_HEIGHT = 450;
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setTitle("Paint v.2.0");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Appeler la methode qui construit la barre de BTN.
buildPanelBtn();
add(panelBtn, BorderLayout.NORTH);
add(espaceDessin, BorderLayout.CENTER);
// Afficher la fenetre.
setVisible(true);
}
private void buildPanelBtn() {
BtnTracerLigne = new JButton("Ligne");
BtnTracerLigne.addActionListener(new LigneListener());
// Creer le panel.
panelBtn = new JPanel();
// Ajouter les composantes au label
panelBtn.add(BtnTracerLigne);
}
private class LigneListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
espaceDessin.TracerLigne();
}
}
}
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
import java.awt.image.*;
class Paint_Dessin extends JPanel {
private static final long serialVersionUID = -2110723486099015303L;
private static final Random RAND = new Random();
private BufferedImage buffer = null;
@Override
public void paintComponent(final Graphics g) {
final Graphics2D g2 = (Graphics2D) g;
g2.clearRect(0, 0, getWidth(), getHeight()); // cleanup du composant
g2.drawImage(getBuffer(), null, 0, 0);
}
public void TracerLigne() {
final Graphics2D g2 = getBuffer().createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLACK);
// dessin la ligne au pif dans l espace visible
final int x1 = RAND.nextInt(500); // position en X1
final int y1 = RAND.nextInt(500); // position en Y1
final int x2 = RAND.nextInt(500); // position en X2
final int y2 = RAND.nextInt(500); // position en Y2
g2.drawLine(x1, y1, x2, y2);
Line2D.Double line = new Line2D.Double(x1, y1, x2, y2);
g2.fill(line);
repaint();
}
private BufferedImage getBuffer() {
if (buffer == null) {
buffer = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
return buffer;
}
}