【发布时间】:2016-11-27 18:13:17
【问题描述】:
我目前正在阅读 Head First Java 关于制作 GUI 的第 12 章。他们刚刚提到 JFrame 分为中心、北部、南部、东部和西部。然后本书使用 2 参数 add() 方法将指定组件添加到具有该 JFrame 的指定区域。
我可以为五个区域中的每一个区域添加一个 JButton。我还可以将我自己的 JPanel 添加到中心区域,周围有 JButtons。但是当我尝试将 JPanel 添加到除中心以外的任何区域时,JPanel 不会出现。
在过去的一个小时里,我真的在整个网络和 Stack Overflow 上进行了搜索,但我没有遇到任何提到将 JPanel 添加到 JFrame 中心以外的任何区域的内容。所以我的问题是:是否可以将 JPanel 添加到 JFrame 的北部、南部、东部或西部区域?
提前感谢任何可以帮助我的人。
这是我一直试图在北部地区使用我的 JPanel 运行的代码:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;
public class StackQ {
JFrame frame;
public static void main(String [] args) {
StackQ gui = new StackQ();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("location test");
JButton button2 = new JButton("location test");
JButton button3 = new JButton("location test");
JButton button4 = new JButton("location test");
myDrawPanel custom = new myDrawPanel();
frame.getContentPane().add(button, BorderLayout.CENTER);
frame.getContentPane().add(button2, BorderLayout.EAST);
frame.getContentPane().add(button3, BorderLayout.WEST);
frame.getContentPane().add(button4, BorderLayout.SOUTH);
frame.getContentPane().add(custom, BorderLayout.NORTH);
frame.setSize(300,300);
frame.setVisible(true);
}
}
class myDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color random = new Color(red, green, blue);
g.setColor(random);
g.fillOval(20,20,100,100);
}
}
【问题讨论】:
标签: java user-interface jframe jpanel