我正在尝试创建一个每秒显示一条新随机行的屏幕保护程序。它内置在JFrame中嵌入的JPanel中。
问题在于,每次构建随机行时,它都会触及JFrame的边缘。我设置它以使该行始终在JPanel中,但我不希望它每次都触及JFrame的边缘。
它永远不会在画面中间显示任何行。我确定这是一个简单的修复方法。我只是在寻找一双新鲜的眼睛。我可能没有正确理解坐标系,谢谢。
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.util.Random;
public class ScreenSaver extends JPanel implements ActionListener{
Timer timer;
int x1;
int y1;
int x2;
int y2;
public ScreenSaver() {
timer = new Timer(1000, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e){
repaint();
}
public void GetRandomValues(){
Random randh = new Random();
Random randw = new Random();
// get width of JPanel
int w = getWidth();
// get height of JPanel
int h = getHeight();
x1 = randh.nextInt(h);
x2 = randh.nextInt(h);
y1 = randw.nextInt(w);
x2 = randw.nextInt(w);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
GetRandomValues();
g2.draw(new Line2D.Double(x1, y1, x2, y2));
}
public static void main (String[] args){
ScreenSaver s1 = new ScreenSaver();
// jf is the JFrame
JFrame jf = new JFrame();
jf.setTitle("ScreenSaver.java");
jf.setSize(800, 500);
// puts frame in middle?
jf.setLocationRelativeTo(null);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// panel inside frame
jf.add(s1);
}
}
答案 0 :(得分:3)
使用单个Random
对象,初始化一次,不要在每个计时器上重新分配它。此外,在坐标创建方面存在混淆。它应该是:
private Random random = new Random();
public void GetRandomValues(){
// get width of JPanel
int w = getWidth();
// get height of JPanel
int h = getHeight();
x1 = random.nextInt(w);
x2 = random.nextInt(w);
y1 = random.nextInt(h);
x2 = random.nextInt(h);
}
x
坐标应受宽度约束,y
坐标应按高度约束。你有另一种方式。