我想用鼠标拖动在两个xy坐标之间画一条线,但无法绘制任何东西
它是一个使用 swing 和 awt 的 GUI 应用程序,我目前让鼠标使用鼠标事件记录初始和最终 xy 位置,这些事件存储在数组中 [x1,y1,x2,y2]
但是,无法在它们之间画一条线。
drawline 是调用到 main 中的它自己的函数
编辑: 假设我有 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),但是将其设为静态会导致鼠标监听器和重绘变得无效。
只要 Graphics g 位于函数内部而不是直接位于类中,它就会成为无效符号(忽略作为占位符的 check 和 xy 值)
最佳答案
你不需要数组,甚至不需要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);
}
关于java - 如何在 Java Swing 中在两点之间拖动和绘制线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56124118/