我正在尝试构建一个程序来允许您绘制图形。我目前正在尝试添加一个函数,以向该图添加一个节点。我的想法是用户可以单击一个按钮,然后单击窗口上的某个位置以添加节点。我现在面临以下两个问题:
当前圆心的位置将是单击按钮的位置。我该如何解决?我希望单击[[AFTER按钮,单击NEXT将添加一个节点。基本上,我需要一个等待其他用户输入然后添加此节点的函数。
公共类Main扩展JFrame {int width = 500;
int height = 500;
JLabel label;
JPanel panel;
JButton addNodeButton;
public Main() {
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel();
label = new JLabel();
addNodeButton = new JButton("Add Node");
addNodeButton.addActionListener((new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Point p = MouseInfo.getPointerInfo().getLocation();
drawCenteredCircle(g, p.x, p.y, 3);
}
}));
panel.add(addNodeButton);
this.add(panel);
setVisible(true);
}
public static void main(String a[]) {
new Main();
}
public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
x = x-(r/2);
y = y-(r/2);
g.fillOval(x,y,r,r);
}
}
mouseListener
而不是按钮。它在您单击按钮的位置周围绘制了一个圆圈。 import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main extends JPanel {
int width = 500;
int height = 500;
JFrame frame = new JFrame();
int x;
int y;
int diameter = 60;
List<Point> points = new ArrayList<>();
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Main());
}
public Main() {
setPreferredSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.white);
addMouseListener(new MyMouseListener());
frame.add(this);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.blue);
g2d.setStroke(new BasicStroke(3));
for(Point p : points) {
g2d.drawOval(p.x,p.y, diameter,diameter);
}
}
private class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
x = me.getX()-diameter/2;
y = me.getY()-diameter/2;
points.add(new Point(x,y));
repaint();
}
}
}