【发布时间】:2021-03-29 23:22:55
【问题描述】:
我正在尝试将汽车绘制为摆动的多边形,并在单击按钮时左右移动
问题是我在运行程序时无法在屏幕上显示按钮,无法让它们工作
而且我不知道在使用多边形时如何实现用户界面内部的按钮
这是我的代码:-
package java2d;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Java2D extends JFrame{
int xValues[];
int yValues[];
private JButton Right, Left;
public Java2D() {
super( "Drawing lines, rectangles and ovals" );
setSize( 500, 300 );
setVisible( true );
}
public void paint( Graphics g ) {
int xValues[] = { 40, 100, 130, 230, 260, 320, 320, 40 };
int yValues[] = { 120, 120, 40, 40, 120, 120, 170, 170 };
Polygon polygon1 = new Polygon( xValues, yValues, 8 );
g.setColor(Color.blue);
g.drawPolygon( polygon1 );
Right = new JButton("Right");
Left = new JButton("Left");
Right.setSize(50, 50);
Left.setSize(50, 50);
Right.setLocation(100, 200);
Left.setLocation(200, 200);
g.add(Right);
g.add(Left);
}
public void actionPerformed(ActionEvent event) {
if(event.getActionCommand().equals("Right")){
for (int i=0; i<xValues.length;i++) {
xValues[i] = xValues[i] + 10;
yValues[i] = yValues[i] + 10;
}
}
if(event.getActionCommand().equals("Left")){
for (int i=0; i<xValues.length;i++) {
xValues[i] = xValues[i] + 10;
yValues[i] = yValues[i] + 10;
}
}
repaint();
}
public static void main(String[] args) {
Java2D application = new Java2D();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
谢谢
【问题讨论】:
标签: java swing graphics graphics2d