java中做一个按钮,点击按钮后画一个矩形的代码怎么写?
兄弟帮你写了一个:
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
public class Print {
public static void main(String[] args) {
new Te();
}
}
class Te extends Frame implements ActionListener {
Color cc = Color.red;
int x = -20, y = -50;
Random r = new Random();
public Te() {
this.setLayout(null);
Button b = new Button(“画圆”);
this.add(b);
b.setBounds(30,30,50,50);
b.addActionListener(this);
this.addWindowListener(new WindowAdapter () {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setBounds(200,200,500,400);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
this.cc = Color.red;
this.x = r.nextInt(400);
do {
int x1 = r.nextInt(300);
this.y = x1;
} while (this.y 50);
this.repaint();
}
@Override
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(cc);
g.drawRect(x,y,50,50);
g.setColor(c);
}
}
java中如何用画布绘制矩形图形?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Ovalcanvas extends Canvas
{
int N=10;
int x[]=new int[N];
int y[]=new int[N];
Ovalcanvas()
{
setSize(300,200);
setBackground(Color.cyan);
}
public void setOval(int[] x,int[] y,int N)
{
this.N=N;
for(int i=0;iN;i++)
{
this.x[i]=x[i];
this.y[i]=y[i];
}
}
public void paint(Graphics g)
{
g.drawPolygon(x,y,N);
}
}
public class Example6_7 extends JFrame implements ActionListener
{
Ovalcanvas canvas;
TextField in_N;
Button btn;
Example6_7()
{
super(“画布上绘制多边形”);
setSize(400,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
in_N=new TextField(6);
setLayout(new FlowLayout());
add(new Label(“请输入变数:”));
add(in_N);
btn=new Button(“确定”);
btn.addActionListener(this);
add(btn);
canvas=new Ovalcanvas();
add(canvas);
validate();
}
public void actionPerformed(ActionEvent e)
{
int N=Integer.parseInt(in_N.getText());
int x[]=new int[N];
int y[]=new int[N];
for(int i=0;iN;i++)
{
x[i]=(int)(Math.random()*200);
y[i]=(int)(Math.random()*200);
}
canvas.setOval(x,y,N);
canvas.repaint();
}
public static void main(String[] args)
{
new Example6_7();
}
}
Java编写一个矩形类,并计算面积和周长?
class Rectangle{
private int width = 2;
private int length = 1;
public int getWidth(){
return this.width;
}
public void setWidth(int w){
this.width = w;
}
public int getLength(){
return this.length;
}
public void setLength(int l){
this.length = l;
}
public int getArea(){
return this.length * this.width;
}
public int getCircumference(){
return (this.length + this.width) * 2;
}
public Rectangle(){}
public Rectangle(int l, int w){
this.length = l;
this.width = w;
}
}
public class demo{
public static void main(String[] args) {
Rectangle rect = new Rectangle(30, 8);
System.out.print(“长方形的面积是:”);
System.out.println(rect.getArea());
System.out.printf(“长方形的周长是:%d\n”, rect.getCircumference());
}
}