简体   繁体   English

Java Swing工程图矩形

[英]Java Swing Drawing Rectangles

I'm trying to visualize values in an Integer Array. 我正在尝试可视化整数数组中的值。 They are supposed to be like a bar graph, but just the bars no axis etc Im using Java Swing for the GUI. 它们应该像条形图,但是只是条形图没有轴,例如Im使用Java Swing作为GUI。 This is supposed to draw just one rectangle for now, but no matter how high I increase the height in g.fillRect(0,0,width,height) it is drawn as a square. 现在应该只绘制一个矩形,但是无论我将g.fillRect(0,0,width,height)的高度增加多少g.fillRect(0,0,width,height)其绘制为正方形。

Here is my code: 这是我的代码:

public class MyClass extends JPanel
{
...

public void paint(Graphics g)
{
    g.fillRect(0,0,10,100);
}

public void draw()
{
    JFrame myframe = new JFrame("FrameTest");
    myframe.setSize(new Dimension (groesse,groesse));
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    JPanel mypanel = new JPanel();
    mypanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    mypanel.setSize(new Dimension(256,256));

    mypanel.add(new MyClass(),BorderLayout.SOUTH);

    myframe.add(mypanel,BorderLayout.SOUTH);

    myframe.setVisible(true);
}

I would love to post a picture of the output but SO doesn't want me to... 我很想发布输出图片,但是我不希望我...

Use BorderLayout not FlowLayout . 使用BorderLayout而不是FlowLayout Don't add two components in the same BorderLayout area. 不要在同一BorderLayout区域中添加两个组件。 Put your MyClass instance in BorderLayout.CENTER . 将您的MyClass实例放入BorderLayout.CENTER

Also override the getPreferredSize method of MyClass to an appropriate value (the size of your drawing area), and forget setSize ; 另外,将MyClassgetPreferredSize方法重写为适当的值(您的绘图区域的大小),然后忘记setSize use pack to pack your frame before making it visible. 使用pack打包框架,然后使其可见。

And finally, don't override paint when using swing but paintComponent . 最后,在使用swing时不要覆盖paint ,而要覆盖paintComponent

mypanel.setSize(new Dimension(256,256));

Don't use setSize(). 不要使用setSize()。

Custom painting is done by overriding the paintComponent() method of your class and don't forget to invoke super.paintComponent(...) . 通过覆盖类的paintComponent()方法来完成自定义绘制,不要忘记调用super.paintComponent(...) You would also override the getPreferredSize() method to return the Dimension of your custom painting. 您还将重写getPreferredSize()方法以返回自定义绘画的Dimension。

Now your component will have a preferred size and the layout manager can do its job. 现在,您的组件将具有首选的大小,并且布局管理器可以执行其工作。

Read the section from the Swing tutorial on Custom Painting for more information and working examples. 阅读有关定制绘画的Swing教程中的部分,以获取更多信息和工作示例。

mypanel.add(new MyClass(),BorderLayout.SOUTH);

A JPanel uses a FlowLayout by default. JPanel默认使用FlowLayout。 Specifying a BorderLayout constraint does nothing. 指定BorderLayout约束不会执行任何操作。 You don't even need this panel, so get rid of it and just add the rectangle panel to the frame. 您甚至不需要此面板,因此您可以摆脱它,只需将矩形面板添加到框架中即可。

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

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