FrameImageDemo

public class FrameImageDemo extends JFrame
{
    private static final long serialVersionUID = 1L;
    
    private DrawSub sines = new DrawSub();
    
    private JSlider adjust = new JSlider();
    
    private JProgressBar progressBar = new JProgressBar();
    
    public FrameImageDemo()
    {
        try
        {
            jbinit();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    public void init()
    {
        Container cp = getContentPane();
        
        cp.add(sines, BorderLayout.CENTER);
        adjust.addChangeListener(new ChangeListener()
        {
            public void stateChanged(ChangeEvent e)
            {
                sines.setCycles(((JSlider)e.getSource()).getValue());
                progressBar.setValue(adjust.getValue());
            }
        });
        cp.add(BorderLayout.SOUTH, adjust);
        cp.add(progressBar, BorderLayout.NORTH);
    }
    
    private void jbinit()
        throws Exception
    {
        this.setTitle("绘图");
        init();
        adjust.setPaintLabels(true);
        adjust.setPaintTicks(true);
        adjust.setForeground(Color.orange);
        adjust.setToolTipText(" ");
        this.adjust.setMinimum(1);
        progressBar.setForeground(Color.red);
    }
    
    public static void main(String[] args)
    {
        FrameImageDemo frame = new FrameImageDemo();
        frame.pack();
        frame.setVisible(true);
    }
}

class DrawSub extends JPanel
{
    private static final long serialVersionUID = 1L;
    
    private static final int SCALEFACTOR = 200;
    
    private int cycles;
    
    private int points;
    
    private double[] sines;
    
    private int[] pts;
    
    public DrawSub()
    {
        setCycles(5);
        
    }
    
    public void setCycles(int newCycles)
    {
        cycles = newCycles;
        points = SCALEFACTOR * cycles * 2;
        sines = new double[points];
        for (int i = 0; i < points; i++)
        {
            double radians = (Math.PI / SCALEFACTOR) * i;
            sines[i] = Math.sin(radians);
        }
        repaint();
    }
    
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        int maxWidth = getWidth();
        double step = (double)maxWidth / (double)points;
        int maxHeight = getHeight();
        pts = new int[points];
        for (int i = 0; i < points; i++)
        {
            pts[i] = (int)(sines[i] * maxHeight / 2 * 0.95 + maxHeight / 2);
        }
        g.setColor(Color.red);
        for (int i = 1; i < points; i++)
        {
            int x1 = (int)((i - 1) * step);
            int x2 = (int)(i * step);
            int y1 = pts[i - 1];
            int y2 = pts[i];
            g.drawLine(x1, y1, x2, y2);
        }
    }
}
 

你可能感兴趣的:(image)