簡體   English   中英

Java圖形沒有畫任何東西

[英]java graphics isn't drawing anything

該程序為條形圖繪制了一堆矩形。 我知道bar類工作得很好,因為在添加圖形面板類之前我已經使它工作了。 我是直接畫在框架上而不是圖形面板上。 我認為這是我之前指出給我的設置可見方法調用方式的問題。 我嘗試研究它,但是在玩轉並閱讀文檔后沒有運氣。

     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();
    }
  • 你應該覆蓋getPreferredSize您的GraphPanel ,以確保它們被正確地布局
  • 您傳遞給Bar類的x / y位置無關緊要,因為這會導致您的Rectangle繪制在Bar窗格的可見上下文之外。 繪畫是在組件的上下文中完成的(0x0是組件的左上角)
  • 實際上,使用Rectangle或使用它的方式會引起問題。 在放置或上漆之前,不可能確切知道零件的大小
  • 不贊成使用resumesuspend的原因,這可能不會導致“怪異”(和奇妙)問題的解決
  • 看一下在容器布置組件的原因,為什么您的鋼筋沒有正確更新以及為什么x / y坐標毫無意義
  • 看看如何使用Swing計時器替代使用Thread

可能更像是...

酒吧

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