
import java.awt.BorderLayout
import java.awt.Color
import java.awt.GradientPaint
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.LayoutManager
import java.awt.Paint
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.util.Random
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JOptionPane
import javax.swing.JPanel
import javax.swing.Timer
import javax.swing.UIManager
public class GradientPanel extends JPanel implements ActionListener {
/** 计时器 */
private Timer timer = null
private Color[] colors = new Color[] {Color.BLUE, Color.GREEN, Color.ORANGE, Color.RED, Color.YELLOW}
private Color nowColor = Color.RED
private JButton setTime = null
public GradientPanel(LayoutManager lm) {
super(lm)
setTime = new JButton("设置时间")
setTime.setActionCommand("setTime")
setTime.addActionListener(this)
timer = new Timer(1000, this)
timer.start()
}
public void paintComponent(Graphics g) {
super.paintComponent(g)
if (!isOpaque()) {
return
}
Color control = UIManager.getColor("control")
int width = getWidth()
int height = getHeight()
Graphics2D g2 = (Graphics2D) g
Paint storedPaint = g2.getPaint()
g2.setPaint(new GradientPaint(0, 0, nowColor, width, height, control))
g2.fillRect(0, 0, width, height)
g2.setPaint(storedPaint)
}
public static void main(String[] args) {
GradientPanel panel = new GradientPanel(new BorderLayout())
JFrame test = new JFrame()
test.getContentPane().add(panel, BorderLayout.CENTER)
test.getContentPane().add(panel.setTime, BorderLayout.NORTH)
test.setSize(500,300)
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
test.setVisible(true)
}
public void actionPerformed(ActionEvent e) {
String commond = e.getActionCommand()
if ("setTime".equals(commond)) {
this.timer.stop()
String result = JOptionPane.showInputDialog("请输入颜色变化的时间:")
if (result != null) {
double time = Double.valueOf(result).intValue()
timer.setDelay((int)(time * 1000))
}
this.timer.restart()
} else {
Random random = new Random()
int index = random.nextInt(colors.length)
nowColor = colors[index]
paintComponent(this.getGraphics())
}
}
}
看看这样达到要求了吗?建议自己看完代码后再自己写一遍,这是一个很好的学习过程。我也是边查API边做的。
代码写得比较乱。
好好的理解下,可以把它改的好些。
实际是采用搏唯递归法求扰宴解:基李培a(n)=a(n-1)+a(n-3)
a(1)=1,a(2)=1,a(3)=2
我写一个简单的C程序,java程序很类似。
int f(int s)
{
if (s==1 || s==2) return 1
if (s==3) return 2
return f(s-1)+f(s-3)
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)