我正在尝试构建一个程序,使您可以绘制图形。我目前正在尝试添加一个函数,以向该图添加一个节点。我的想法是用户可以单击一个按钮,然后单击窗口上的某个位置以添加节点。我现在面临以下两个问题:
公共类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);
}
}
问题来源:Stack Overflow
尝试这个。当您查看有关绘画的教程或查阅Java API时,将进行解释。我用了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();
}
}
}
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。