drawing text within a JPanel

前端 未结 4 1206
生来不讨喜
生来不讨喜 2021-01-05 16:04

I\'m looking for the most basic description of how to draw text within a JPanel. I know there are a billion tutorials out there but none of them are clicking with me and I h

4条回答
  •  有刺的猬
    2021-01-05 16:22

    Create an inner class that extends JPanel inside your Main class:

    class MyPanel extends JPanel {
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawString(Integer.toString(avg), 75, 75);
        }
    
    }
    

    Then you need to call repaint on that panel after calling computeAverage() in actionPerformed:

    //event handling
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == avgBtn) {
            computeAverage();
            panel.repaint();
        }
    }
    

提交回复
热议问题