简体   繁体   English

Java绘画不起作用

[英]Java paint doesn't work

am try to call paint in my listener but draw rectangle shouldn't be call 我试着在我的监听器中调用paint,但不应该调用绘制矩形

maybe my code is wrong help me please am newbie in java 也许我的代码是错误的帮助我请在java新手

btnNewButton_5.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            class MyCanvas extends JComponent {

                  public void paint(Graphics g) {
                    g.drawRect (10, 10, 200, 200);  
                  }
            }

            JFrame window = new JFrame();
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setBounds(30, 30, 300, 300);
            window.getContentPane().add(new MyCanvas());
            window.setVisible(true);

        }
    });

I hope it will help you :) 我希望它能帮到你:)

btnNewButton_5.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
        class MyCanvas extends JComponent {

              //You didnt set size 

              public MyCanvas(){
                  setSize(size, width);
              }

              //public void paint(Graphics g) { better use paintComponent
              public void paintComponent(Graphics g){
                //always use it:
                super.paintComponent(g);
                g.setColor(Color.RED); // You didnt set color
                g.drawRect (10, 10, 200, 200);  
              }
        }

        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //window.setBounds(30, 30, 300, 300); Never saw the same statement
        window.setSize(width, height);
        //window.getContentPane().add(new MyCanvas());
        window.add(new MyCanvas()); // dont use getContentPane dont need it in newest java versions
        window.setVisible(true);

    }
});

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

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