JPanel 之上的 Java JPanel(绘图之上绘图)
我正在尝试编写代码来生成如下图: http://www .mathgoodies.com/lessons/graphs/images/line_example1.jpg
我需要不止一条不同的线(我希望这就是它们的名字)。
我刚刚开始学习 awt 和 swing。经过三个小时的努力,我无法找到一种方法在任何其他图画上画一条线。
我将尝试用一个例子来解释我的问题。
假设我画了一个像这样的正方形:
JFrame window = new JFrame();
window.setLayout(null);
window.setVisible(true);
Graph graph = new Graph();
window.add(graph);
//-------------------
public class Graph extends JPanel {
....
public void paintComponent (Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(150, 20, x, y);
}
....
}
如何在这个白色正方形的顶部绘制另一条线或其他任何东西,而无需在 Graphs PaintComponent 方法中绘制线?如何在另一个 JPanel 之上添加另一个 JPanel,以便它们都可见? (我正在使用 JPanel 添加一些按钮)
希望您能理解我的要求。
谢谢你!
I am trying to write a code to generate a graph like this: http://www.mathgoodies.com/lessons/graphs/images/line_example1.jpg
I need more than one different line (I hope that's what they are called).
I'm just starting to learn awt and swing. After exhausting three hours of work, I couldn't manage a way to draw a line on top of any other drawing.
I'll try to explain my problem with an example.
Lets say I draw a square like this:
JFrame window = new JFrame();
window.setLayout(null);
window.setVisible(true);
Graph graph = new Graph();
window.add(graph);
//-------------------
public class Graph extends JPanel {
....
public void paintComponent (Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(150, 20, x, y);
}
....
}
How do I draw another line or anything else on top of this white square whithout drawing the line in the Graphs paintComponent method? How do I add another JPanel on top of another one, so that both of them are visible? (I'm using JPanel to add some buttons)
Hopefully you can understand what I'm asking.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所有自定义绘制都应在 PaintComponent() 方法中完成。我不确定你为什么要添加另一个在线绘制的面板。保持简单并将所有绘画代码放在一处。
如果您想向面板添加其他组件(如 JPanel),那么您可以使用布局管理器来正确布局组件。您还需要使用 setOpaque(...) 方法使组件不透明。
对组件进行分层的另一种方法是使用 JLayeredPane。
首先阅读 Swing 教程。有以下部分:
All custom painting should be done in the paintComponent() method. I'm not sure why you want to add another panel that paints on line. Keep it simple and keep all the painting code in one place.
If you want to add other components (like a JPanel) to the panel then you would use layout managers to lay out the components properly. You would also need to make the components non-opaque by using the setOpaque(...) method.
Another way to layer components is to use a JLayeredPane.
Start by reading the Swing tutorial. There are sections on: