在java swing中 怎么实现通过点击一个按钮,则会随机在另一个面板上生成一个或者多个点
1个回答
展开全部
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
final class DotPaintDemo extends JFrame {
final static private Dimension SIZE = new Dimension(400, 300);
public String getTitle() {return "DotPaintDemo";}
public Dimension getPreferredSize() {return SIZE;}
public Dimension getMinimumSize() {return SIZE;}
public Dimension getMaximumSize() {return SIZE;}
public Dimension getSize() {return SIZE;}
private Canvas canvas;
private JButton button;
private Brush brush;
DotPaintDemo() throws HeadlessException {
init();
attachListeners();
doLay();
setVisible(true);
}
private void init() {
brush = new DotBrush();
canvas = new Canvas(brush);
button = new JButton("Paint Dot");
button.addChangeListener(evt->{
Random random = new Random(System.nanoTime());
brush.update(null,
new Point(random.nextInt(getWidth() - 10), random.nextInt(getHeight() - 10))
);
});
}
private void attachListeners() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(1);
}
});
}
private void doLay() {
Container container = getContentPane();
container.add(canvas, BorderLayout.CENTER);
container.add(button, BorderLayout.NORTH);
pack();
}
public static void main(String... args) {
System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(DotPaintDemo::new);
}
/**
* 画笔
*/
private interface Brush extends Observer {
/**
* do paint action
* @param g the graphics context in you application
*/
void paint(Graphics g);
/**
* The component that this brush hold
* @return component instance
*/
Component getOwner();
void setOwner(Component owner);
}
private static final class DotBrush implements Brush {
private Component owner;
private Arc2D shape = new Arc2D.Float(Arc2D.Float.CHORD);
public Component getOwner() {
return owner;
}
public void setOwner(Component owner) {
this.owner = owner;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g.create();
g2.fill(new Rectangle(0,0, getOwner().getWidth(), getOwner().getHeight()));
g2.setColor(Color.PINK);
g2.fill(shape);
g2.dispose();
}
public void update(Observable o, Object arg) {
if (arg instanceof Point) {
Point p = (Point)arg;
shape.setArcByCenter(p.x, p.y, 13, 0, 360, Arc2D.Float.CHORD);
}
if (owner != null) owner.repaint();
}
}
/**
* 画布
*/
private class Canvas extends JComponent {
private Brush brush;
private Canvas(Brush brush) {
super();
this.brush = brush;
brush.setOwner(this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (brush == null) return;
brush.paint(g);
}
}
}
更多追问追答
追问
这个jre好像不是1.6的版本是么
追答
JDK1.8
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询