【发布时间】:2021-08-27 21:57:57
【问题描述】:
如何用实心圆圈替换代码上显示的按钮。圆圈(例如红色)必须像按钮一样远离光标。 是否有另一种可能的方式来实现此类任务?
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class NewSwingTemplate {
private Random d = new Random();
public NewSwingTemplate() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(createButton());
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JButton createButton() {
final JButton button = new JButton("Button");
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
int a = d.nextInt(200);
int b = d.nextInt(200);
button.setLocation(a, b);
}
});
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new NewSwingTemplate();
}
});
}
}
【问题讨论】:
-
您可以自定义绘制
Shape。签出:stackoverflow.com/a/67443344/131872。它展示了如何绘制和拖动任何Shape。您只需要替换“拖动”逻辑并处理mouseMoved事件。您首先需要检查Shape是否包含鼠标点。如果是这样,那么您将 Shape 转换到另一个位置。 -
或者你实际上可以创建一个Round Button。
-
那么您的问题解决了吗?你一直在问问题,但你从不接受答案或评论问题是否得到解决。
-
那么您的问题解决了吗?您不断提出问题,但如果建议有助于解决问题,您永远不会接受答案或评论。
标签: java swing mouselistener