问题描述
这是我的代码:
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();
}
}
我想在CenterPanel
中打印随机的“ *”。
JFrame
流畅,所以我必须获得northPanel
,SouthPanel
和ContentPane
的大小,但我不知道该怎么做。
如何获取CenterPanel
的位置?
int x = (int)(Math.random()*400);
int y = (int)(Math.random()*400);
400是临时整数,所以我尝试了getWidth()
,但这不起作用。
解决方法
首先,不要使用TextField
。那是一个AWT组件。对于Swing,您应该使用JTextField
。
在显示框架之前,摆动组件没有尺寸。
Swing组件负责确定其自身大小。如果要进行自定义绘制或添加随机组件,则应重写组件的getPreferredSize()
方法以返回其所需大小。
@Override
public Dimension getPreferredSize()
{
return new Dimension(400,400);
}
然后,您的构造函数可以调用getPreferredSize()
方法来获取要在随机代码中使用的宽度/高度。
int x = (int)(Math.random() * getPreferredSize().width); // 랜덤 x좌표 생성
int y = (int)(Math.random() * getPreferredSize().height); // 랜덤 y좌표 생성
然后在使框架可见之前,请在框架上调用pack()
,所有组件将以其首选大小显示。
this.pack();
this.setVisible(true);
注意,为什么要尝试在随机位置显示标签。我也同意ControlAltDel的回答,即自定义绘画是一种更好的方法(比使用标签组件更好)。但是,我在这里提出的相同建议也适用于此。也就是说,您将实现getPreferredSize()
并使用pack()
。
如果要使用自定义绘画,则可以创建一个ArrayList
的对象进行绘画。然后paintComponent()方法将遍历ArrayList以绘制每个对象。有关此方法的示例,请参见:Custom Painting Approaches。