drawing text within a JPanel

前端 未结 4 1214
生来不讨喜
生来不讨喜 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();
        }
    }
    
    0 讨论(0)
  • 2021-01-05 16:27

    I think you should not be subclassing JFrame. Make an instance of JFrame an instance
    variable of Main class and add the JPanel etc. to it.

    0 讨论(0)
  • 2021-01-05 16:31

    1) A JFrame doesn't have a paintComponent() method so the code you posted won't do anything. You need to create a custom JPanel and override its paintComponent() method to do your custom painting.

    2) Even if you do the above, the painting will still not display because a panel by default has a zero size. So you will then need to set the preferred size of the panel to make sure it is visible.

    3) Why are you even doing this. All you need to do is use a JLabel and set the text of the JLabel.

    I find it hard to believe you looked at other tutorials. The Swing tutorial on Custom Painting has a 20 line program that shows the basics.

    0 讨论(0)
  • 2021-01-05 16:43

    Add a JLabel to the JPanel.

    Call setText(String) on the JLabel and your text will be drawn within the JPanel.

    0 讨论(0)
提交回复
热议问题