This is my code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.TextField;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class NorthPanel extends JPanel{
public NorthPanel() {
this.setBackground(Color.LIGHT_GRAY); // 배경색 설정
this.add(new JButton("열기"));
this.add(new JButton("닫기"));
this.add(new JButton("나가기"));
}
}
class CenterPanel extends JPanel{
public CenterPanel() {
setLayout(null); // Layout없애줌.(default=bodrderlayout)
for (int i=0; i<10; i++) {
int x = (int)(Math.random()*400); // 랜덤 x좌표 생성
int y = (int)(Math.random()*400); // 랜덤 y좌표 생성
JLabel l = new JLabel("*");
l.setForeground(Color.RED);
l.setLocation(x,y); // 생성한 랜덤좌표로 설정
l.setSize(20,20);
add(l);
}
}
}
class SouthPanel extends JPanel{
public SouthPanel() {
this.setBackground(Color.YELLOW);
add(new JButton("Word Input"));
add(new TextField(20));
}
}
public class Panels extends JFrame {
public Panels(){
this.setTitle("여러 개의 패널을 가진 프레임");
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 창 닫으면 종료되도록
Container c = this.getContentPane(); // 기반이 될 contentpane
c.add(new NorthPanel(), BorderLayout.NORTH);
c.add(new CenterPanel(), BorderLayout.CENTER);
c.add(new SouthPanel(), BorderLayout.SOUTH);
this.setVisible(true); // 화면에 보이게
}
public static void main(String[] args) {
new Panels();
}
}
I want to print random "*" in CenterPanel
.
JFrame
is fluid so I have to get size of NorthPanel
, SouthPanel
and ContentPane
but I don't know how..
How do I get the location of the CenterPanel
?
int x = (int)(Math.random()*400);
int y = (int)(Math.random()*400);
400 is temporary integer so I tried getWidth()
but that doesn't work.