[英]How to drag and draw line between 2 points in Java Swing
我想用鼠標拖動在兩個xy坐標之間繪制一條線,但無法繪制任何內容
它是一個使用swing和awt的gui應用程序,目前我使用鼠標事件將鼠標事件的初始和最終xy位置記錄為[x1,y1,x2,y2]
,但是無法在兩者之間繪制線條他們。
畫線是自己的函數,稱為主函數
編輯:說我有2節課;
public class mainApp extends JFrame implements ActionListener, Runnable {
private JPanel jpanel = new JPanel();
private mainApp(String title) throws HeadlessException {
super(title);
}
private void createGUI() {
// TODO
// ...
// cannot call unless is static
drawStraightLine.drawLine(jpanel);
this.pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {}
@Override
public void run() {createGUI();}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new mainApp("drawline"));
}
}
public class drawStraightLine extends JPanel {
public static void drawLine(JPanel jpanel) {
// content which conceivably works
// mouselisteners and repaint()
public void paintComponent (Graphics g){
super.paintComponent(g);
if (check != null) {
Color purple = new Color(128, 0, 128);
g.setColor(purple);
g.drawLine(x1, y1, x2, y2);
}
}
}
我不能調用drawline(jpanel),除非它是一個靜態函數,但是將其設為靜態會導致mouselisteners和repaint變得無效。
您不需要數組甚至X&Y。您可以使用mouseEvent的getPoint()方法。 嘗試這個:
public static void main(String args[]) throws Exception {
JFrame f = new JFrame("Draw a Line");
f.setSize(300, 300);
f.setLocation(300, 300);
f.setResizable(false);
JPanel p = new JPanel() {
Point pointStart = null;
Point pointEnd = null;
{
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointStart = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
pointStart = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
pointEnd = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
pointEnd = e.getPoint();
repaint();
}
});
}
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) {
g.setColor("put your color here");
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}
}
};
f.add(p);
f.setVisible(true);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.