简体   繁体   English

Java图形没有画任何东西

[英]java graphics isn't drawing anything

The program draws a bunch of rectangles for a bar graph. 该程序为条形图绘制了一堆矩形。 I know the bar class works perfectly fine because I've got it working before adding in the graph panel class. 我知道bar类工作得很好,因为在添加图形面板类之前我已经使它工作了。 I was drawing straight onto the frame instead of the graph panel. 我是直接画在框架上而不是图形面板上。 I assume its a problem in the way my set visible methods are called as it was pointed out to me before. 我认为这是我之前指出给我的设置可见方法调用方式的问题。 I tried looking into it but I've had no luck after playing around and reading documentation. 我尝试研究它,但是在玩转并阅读文档后没有运气。

     import java.awt.Color;
    import java.util.ArrayList;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.util.concurrent.Semaphore;

@SuppressWarnings("serial")
public class GraphPanel extends JPanel {

    private ArrayList<Bar> graphBars;
    private int nBars;

    public GraphPanel(int nBars, JFrame mainFrame) {
        this.setSize(400, 400);
        this.graphBars = new ArrayList<Bar>(nBars);
        this.nBars = nBars;
        this.initBars(mainFrame.getWidth());
        for(Bar b: this.graphBars) {
            this.add(b);
        }

    }

    private void initBars(int frameW) {
        Random random = new Random();
        float hue; 
        Color color; 
        int barPadding = frameW/this.nBars;
        for(int i = 0; i < this.nBars; i++) {
            hue = random.nextFloat();
            color = Color.getHSBColor(hue, 0.9f, 1.0f);
            this.graphBars.add(new Bar(i*barPadding + 30, 350, color));
        }
    }

    public ArrayList<Bar> getBarList() {
        return this.graphBars;
    }
}






@SuppressWarnings("serial")
public class Bar extends JPanel implements Runnable {

    int height = 0;
    Color barColor;
    Rectangle bar;
    private final int WIDTH = 20;
    Thread bartender;
    private Semaphore s;

    public Bar(int x, int y, Color barColor) {
        this.barColor= barColor;
        this.bar = new Rectangle(x, y, this.WIDTH, this.height);
        this.bartender= new Thread(this);
        this.s = new Semaphore(1);
    }

    public boolean setNewHeight(int h) {
        try {
            this.s.acquire();
            this.height = h;
            this.s.release();
            return true;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    @SuppressWarnings("deprecation")
    public void update() {
        if (this.bar.height < this.height) {
            bar.reshape(this.bar.x, --this.bar.y, this.bar.width, ++this.bar.height);
        } else {
            bar.reshape(this.bar.x, ++this.bar.y, this.bar.width, --this.bar.height);
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(this.barColor);
        g2d.fill(this.bar);
    }

    @SuppressWarnings("deprecation")
    public void callBarTender() {
        this.bartender.resume();
    }

    @SuppressWarnings("deprecation")
    @Override
    public void run() {
        System.out.println("sdf");
        while(true) {
            if (this.bar.height < this.height) {
                for(int i = this.bar.height; i<this.height; i++ ) {
                    try {
                        update();
                        repaint();
                        Thread.sleep(15);
                    } catch(Exception e) {
                        System.out.println(e);
                    }
                }
            } else if (this.height < this.bar.height) {
                for(int i = this.bar.height; i>this.height; i-- ) {
                    try {
                        update();
                        repaint();
                        Thread.sleep(15);
                    } catch(Exception e) {
                        System.out.println(e);
                    }
                }
            }
            this.bartender.suspend();
        }
    }

}



 public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setSize(400, 400);
            frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            GraphPanel gPane = new GraphPanel(3, frame);
            frame.add(gPane);

            gPane.getBarList().get(0).setVisible(true);
            gPane.getBarList().get(1).setVisible(true);
            gPane.getBarList().get(2).setVisible(true);
            gPane.setVisible(true);
            frame.setVisible(true);

            gPane.getBarList().get(0).setNewHeight(100);
            gPane.getBarList().get(1).setNewHeight(100);
            gPane.getBarList().get(2).setNewHeight(100);

            gPane.getBarList().get(0).bartender.start();
            gPane.getBarList().get(1).bartender.start();
            gPane.getBarList().get(2).bartender.start();
    }
  • You should override getPreferredSize of your GraphPanel to ensure that they are laid out correctly 你应该覆盖getPreferredSize您的GraphPanel ,以确保它们被正确地布局
  • The x/y positions you are passing to the Bar class are irrelevant, as this is causing your Rectangle to paint outside of the visible context of the Bar pane. 您传递给Bar类的x / y位置无关紧要,因为这会导致您的Rectangle绘制在Bar窗格的可见上下文之外。 Painting is done from within the context of the component (0x0 been the top/left corner of the component) 绘画是在组件的上下文中完成的(0x0是组件的左上角)
  • The use of Rectangle or the way you are using it, is actually causing issues. 实际上,使用Rectangle或使用它的方式会引起问题。 It's impossible to know exactly how big you component will be until it's layed or painted 在放置或上漆之前,不可能确切知道零件的大小
  • There is a reason why resume and suspend are deprecated, this could cause no end of "weird" (and wonderful) issues 不赞成使用resumesuspend的原因,这可能不会导致“怪异”(和奇妙)问题的解决
  • Take a look at Laying Out Components Within a Container for why you're bars aren't been updated correctly and why the x/y coordinates are pointless 看一下在容器布置组件的原因,为什么您的钢筋没有正确更新以及为什么x / y坐标毫无意义
  • Take a look at How to use Swing Timers for an alternative to your use of Thread 看看如何使用Swing计时器替代使用Thread

Possibly, something more like... 可能更像是...

酒吧

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame();
                frame.setSize(400, 400);
                //      frame.setResizable(false);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                GraphPanel gPane = new GraphPanel(3, frame);
                frame.add(gPane);

                gPane.getBarList().get(1).setFill(false);

                gPane.getBarList().get(0).start();
                gPane.getBarList().get(1).start();
                gPane.getBarList().get(2).start();

                frame.setVisible(true);

            }
        });
    }

    public class GraphPanel extends JPanel {

        private ArrayList<Bar> graphBars;
        private int nBars;

        public GraphPanel(int nBars, JFrame mainFrame) {
            this.graphBars = new ArrayList<Bar>(nBars);
            this.nBars = nBars;
            this.initBars(mainFrame.getWidth());
            for (Bar b : this.graphBars) {
                this.add(b);
            }

        }

        private void initBars(int frameW) {
            Random random = new Random();
            float hue;
            Color color;
            for (int i = 0; i < this.nBars; i++) {
                hue = random.nextFloat();
                color = Color.getHSBColor(hue, 0.9f, 1.0f);
                this.graphBars.add(new Bar(color));
            }
        }

        public ArrayList<Bar> getBarList() {
            return this.graphBars;
        }
    }

    @SuppressWarnings("serial")
    public class Bar extends JPanel {

        private Color barColor;
        private boolean fill = true;

        private float fillAmount = 0;
        private float delta = 0.01f;

        private Timer timer;
        private Rectangle bar;

        public Bar(Color barColor) {
            bar = new Rectangle();
            setBorder(new LineBorder(Color.RED));
            this.barColor = barColor;
            timer = new Timer(15, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    fillAmount += isFill() ? delta : -delta;
                    //                  System.out.println(fillAmount);
                    if (fillAmount < 0) {
                        fillAmount = 0;
                        ((Timer) e.getSource()).stop();
                    } else if (fillAmount > 1.0f) {
                        fillAmount = 1f;
                        ((Timer) e.getSource()).stop();
                    }
                    repaint();
                }
            });
        }

        public void start() {
            timer.start();
        }

        public void stop() {
            timer.stop();
        }

        public void setFill(boolean fill) {
            this.fill = fill;
            if (!timer.isRunning()) {
                if (fill && fillAmount == 1) {
                    fillAmount = 0;
                } else if (!fill && fillAmount == 0) {
                    fillAmount = 1;
                }
            }
        }

        public boolean isFill() {
            return fill;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(20, 100);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(this.barColor);
            int height = Math.round(getHeight() * fillAmount);
            bar.setSize(getWidth(), height);
            bar.setLocation(0, getHeight() - height);
            g2d.fill(bar);
            g2d.dispose();
        }

    }
}

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

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