我有一个绘制随机三角形的程序。我想添加一个按钮,单击该按钮会擦除并重新生成另一个随机三角形。我测试了是否可以在另一个程序中显示一个按钮SwingButtonTest.java
,(这是我滚动的方式,我正在学习)并且它成功了。
然后,我基本上将所有我认为必要的代码从那个程序中复制到我的三角形程序中。不幸的是,程序不显示按钮...
再次感谢任何帮助,非常感谢!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@SuppressWarnings({ "serial" })
public class TriangleApplet extends JApplet implements ActionListener {
int width, height;
int[] coords = new int[6];
JButton refresh;
public void init() {
//This stuff was added from SwingButtonTest.java
Container container = getContentPane();
container.setLayout(null);
container.setLayout(null);
refresh= new JButton("I like trains");
refresh.setBackground(Color.yellow);
refresh.setSize(140, 20);
refresh.addActionListener(this);
container.add(refresh);
//End of SwingButtonTest.java stuff
coords = randomTri();
}
public static int[] randomTri() {
int[] pointArray = new int[6];
int x;
for (int i = 0; i < 6; i++) {
x = ((int)(Math.random()*40)*10);
pointArray[i] = x;
}
return pointArray;
}
public void paint( Graphics g ) {
g.setColor(Color.BLUE);
g.drawLine(coords[0], coords[1], coords[2], coords[3]);
g.drawString("A: " + coords[0]/10 + ", " + coords[1]/10, coords[0], coords[1]);
g.drawLine(coords[2], coords[3], coords[4], coords[5]);
g.drawString("B: " + coords[2]/10 + ", " + coords[3]/10, coords[2], coords[3]);
g.drawLine(coords[4], coords[5], coords[0], coords[1]);
g.drawString("C: " + coords[4]/10 + ", " + coords[5]/10, coords[4], coords[5]);
//Math for AB
int abXDif = Math.abs(coords[0]/10 - coords[2]/10);
int abYDif = Math.abs(coords[1]/10 - coords[3]/10);
int abLength = (abXDif*abXDif) + (abYDif*abYDif);
g.drawString("AB: Sqrt of "+ abLength, 0, 10);
//Math for BC
int bcXDif = Math.abs(coords[2]/10 - coords[4]/10);
int bcYDif = Math.abs(coords[3]/10 - coords[5]/10);
int bcLength = (bcXDif*bcXDif) + (bcYDif*bcYDif);
g.drawString("BC: Sqrt of "+ bcLength, 0, 20);
//Math for AC
int acXDif = Math.abs(coords[4]/10 - coords[0]/10);
int acYDif = Math.abs(coords[5]/10 - coords[1]/10);
int acLength = (acXDif*acXDif) + (acYDif*acYDif);
g.drawString("AC: Sqrt of "+ acLength, 0, 30);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}