임의의 반지름 길이로 20 개의 무작위 원을 생성하는 프로그램을 작성해야합니다. 이 원 중 하나가 다른 원과 교차하면 원은 파란색이어야하며 교차하지 않으면 색상이 빨간색입니다. 또한 JFrame에 버튼을 배치해야합니다. 이 버튼을 누르면 JFrame을 지우고 동일한 색상 규칙에 따라 새로운 20 개의 원 세트를 생성해야합니다. 나는 Java Swing에 매우 익숙하며 정말로 붙어 있습니다. 나는 버튼을 제외한 모든 것을 가지고있다. 생성 할 새로운 서클 집합을 가져올 수 없습니다. 어떤 도움이라도 대단히 감사하겠습니다. 고맙습니다.버튼 JFrame의 뷰를 재설정하려면
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class IntersectingCircles extends JPanel
{
private int[] xAxis = new int [20]; // array to hold x axis points
private int[] yAxis = new int [20]; // array to hold y axis points
private int[] radius = new int [20]; // array to hold radius length
public static void main (String[] args)
{
JFrame frame = new JFrame("Random Circles");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new IntersectingCircles());
frame.pack();
frame.setVisible(true);
}
public IntersectingCircles()
{
setPreferredSize(new Dimension(1000, 800)); // set window size
Random random = new Random();
// Create coordinates for circles
for (int i = 0; i < 20; i++)
{
xAxis[i] = random.nextInt(700) + 100;
yAxis[i] = random.nextInt(500) + 100;
radius[i] = random.nextInt(75) + 10;
}
}
public void paintComponent(Graphics g)
{
// Add button to run again
JButton btnAgain = new JButton("Run Again");
btnAgain.setBounds(850, 10, 100, 30);
add(btnAgain);
btnAgain.addActionListener(new ButtonClickListener());
// Determine if circles intersect, create circles, color circles
for (int i = 0; i < 20; i++)
{
int color = 0;
for (int h = 0; h < 20; h++)
{
if(i != h)
{
double x1 = 0, x2 = 0, y1 = 0, y2 = 0, d = 0;
x1 = (xAxis[i] + radius[i]);
y1 = (yAxis[i] + radius[i]);
x2 = (xAxis[h] + radius[h]);
y2 = (yAxis[h] + radius[h]);
d = (Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1)*(y2 - y1))));
if (d > radius[i] + radius[h] || d < (Math.abs(radius[i] - radius[h])))
{
color = 0;
}
else
{
color = 1;
break;
}
}
}
if (color == 0)
{
g.setColor(Color.RED);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
else
{
g.setColor(Color.BLUE);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
}
}
private class ButtonClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if(action.equals("Run Again"))
{
new IntersectingCircles();
}
}
}
}
1) 자바 GUI를 다른 OS ', 화면 크기, 화면 해상도 등 이와 같이 작업을해야, 그들은 픽셀에 도움이되지 않습니다 완벽한 레이아웃. 대신 레이아웃 관리자 또는 [조합] (http://stackoverflow.com/a/5630271/418556)과 [공백] 레이아웃 채우기 및 테두리 (http://stackoverflow.com/a/17874718/)를 사용하십시오. 418556). 2) [Java Swing에서 set (Preferred | Maximum | Minimum) Size 메소드를 사용하지 않는 것이 좋겠습니까?] (예.) 3 참조) [Collision 복잡한 모양의 탐지] (http://stackoverflow.com/a/14575043/418556)를 참조하십시오. –
@HovercraftFullOfEels 첫번째 나는 그 찌끼를 보았습니다. 끝난! –
@AndrewThompson : 감사합니다! –