Java绘画不起作用

时间:2016-05-30 04:23:15

标签: java java-2d

我尝试在我的监听器中调用paint,但绘制矩形不应该调用

也许我的代码有误,请帮我吧,我是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);

        }
    });

1 个答案:

答案 0 :(得分:0)

我希望它会对你有所帮助:)。

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);

    }
});