简体   繁体   English

JPanel上的Java JPanel(绘图在绘图之上)

[英]Java JPanel on top of JPanel (Drawing on top of drawing)

I am trying to write a code to generate a graph like this: http://www.mathgoodies.com/lessons/graphs/images/line_example1.jpg 我正在尝试编写一个代码来生成这样的图形: 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. 我刚刚开始学习awt和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? 如何在Graphs paintComponent方法中绘制线条时,如何在此白色方块上绘制另一条线或其他任何内容? How do I add another JPanel on top of another one, so that both of them are visible? 如何在另一个JPanel之上添加另一个JPanel,以便它们都可见? (I'm using JPanel to add some buttons) (我正在使用JPanel添加一些按钮)

Hopefully you can understand what I'm asking. 希望你能理解我在问什么。

Thank you! 谢谢!

How do I draw another line or anything else on top of this white square whithout drawing the line in the Graphs paintComponent method? 如何在Graphs paintComponent方法中绘制线条时,如何在此白色方块上绘制另一条线或其他任何内容?

All custom painting should be done in the paintComponent() method. 所有自定义绘制都应该在paintComponent()方法中完成。 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. 如果要将其他组件(如JPanel)添加到面板,则可以使用布局管理器正确布置组件。 You would also need to make the components non-opaque by using the setOpaque(...) method. 您还需要使用setOpaque(...)方法使组件不透明。

Another way to layer components is to use a JLayeredPane. 分层组件的另一种方法是使用JLayeredPane。

Start by reading the Swing tutorial . 首先阅读Swing教程 There are sections on: 有部分内容:

  1. Using Layout Managers 使用布局管理器
  2. Using Layered Panes. 使用分层窗格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM