java画一个矩形代码 用java画一个图形( 二 )


import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PaintingPanel());
frame.setBounds(100, 100, 400, 400);
frame.setVisible(true);
}
}
class PaintingPanel extends JPanel {
ArrayListRectangle list;
Rectangle current;
public PaintingPanel() {
list = new ArrayListRectangle();
addMouseMotionListener(mouseHandler);
addMouseListener(mouseHandler);
}
MouseInputListener mouseHandler = new MouseInputAdapter() {
Point startPoint;
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
current = new Rectangle();
}
public void mouseReleased(MouseEvent e) {
makeRectangle(startPoint, e.getPoint());
if (current.width0current.height0) {
list.add(current);
current = null;
repaint();
}
}
public void mouseDragged(MouseEvent e) {
if (current != null) {
makeRectangle(startPoint, e.getPoint());
repaint();
}
}
private void makeRectangle(Point p1, Point p2) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int w = Math.abs(p1.x - p2.x);
int h = Math.abs(p1.y - p2.y);
current.setBounds(x, y, w, h);
}
};
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
for (Rectangle rect : list) {
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
if (current != null) {
g.drawRect(current.x, current.y, current.width, current.height);
}
}
}
初学 用Java画一个空的矩形 谁帮我看看有没有更简便方法代码如下:
public class FunctionTest{
public static void main(String[] args) {
int m = 7, n = 10;
for (int i = 0; im; i++) {
for (int j = 0; jn; j++) {
if (i == 0 || i == (m - 1)) {
System.out.print("*");
} else if (j == 0 || j == (n - 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
运行结果:
【java画一个矩形代码 用java画一个图形】关于java画一个矩形代码和用java画一个图形的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息 , 记得收藏关注本站 。

推荐阅读