在绘制AWT的程序中添加一个秋千按钮



我有一个绘制随机三角形的程序。我想添加一个按钮,单击后,它将擦除和再生另一个随机三角形。我测试了是否可以在另一个程序中显示一个按钮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
}
}

未显示按钮的原因是您不致电:

super.paint(g);

paint()方法中。此调用将导致按钮和其他添加的组件被绘制。

在秋千中进行自定义绘画的一种更好的方法是将您的自定义绘画放入扩展JComponent和覆盖paintComponent的组件中,以利用Swing的优化绘画模型。

也考虑使用布局管理器来尺寸&amp;放置您的组件。避免使用绝对定位(null布局)。从没有布局经理的情况下进行:

尽管可以在没有布局管理器的情况下进行,但如果可能的话,您应该使用布局管理器。一个布局管理器使调整以更容易调整到与外观相关的组件外观,不同字体尺寸,对容器的变化尺寸以及不同的语言环境。

最新更新