Java – draw text in JPanel
I'm looking for the most basic description of how to draw text in JPanel I know there are a billion tutorials, but none of them click with me. I have some specific questions that can help other confused people As a setup (test application), I have a class with a jlabel, a jtextfield, a JButton and a JPanel The application reads integers from an external file and displays their average value in the panel when JButton is pressed I've sorted out all the underlying programming (that is, the button responds and prints the average to the command line), but I can't seem to figure out how to print the average to the panel I think my biggest problem is how to combine the paint () or paintcomponet () method with the rest of the code Should it be your own class? Should JPanel be its own class? It seems that this is what most tutorials tell me. I'm just not sure what the first step is The code is as follows:
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class Main extends JFrame implements ActionListener { private int[] intArray = new int[10000]; private int numOfInts = 0; private int avg = 0; protected JButton avgBtn; protected JTextField indexEntry; protected JLabel instructions; protected JPanel resultsPanel; public Main(){ //create main frame this.setTitle("Section V,question 2"); this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); this.setSize(350,250); this.setLayout(new GridLayout(4,1)); //create instruction label and add to frame instructions = new JLabel("Follow the instructions on the exam to use this program"); this.add(instructions); //create textfield for index entry and add to frame indexEntry = new JTextField(); this.add(indexEntry); //create button for average and add to frame avgBtn = new JButton("Click for Average"); this.add(avgBtn); avgBtn.addActionListener(this); //create panel to display results and add to frame resultsPanel = new JPanel(); resultsPanel.setBackground(Color.BLUE); this.add(resultsPanel); //read in from file readFromFile(); //compute average computeAverage(); } private void readFromFile() { try { // Open the file FileInputStream fstream = new FileInputStream("numbers.dat"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); //create placeholder for read in ints String strLine; //Read File Line By Line int i = 0; while ((strLine = br.readLine()) != null) { //place ints in array and increament the count of ints System.out.println (strLine); intArray[i] = Integer.parseInt(strLine); numOfInts++; i++; } //Close the input stream in.close(); System.out.println ("numOfInts = " + numOfInts); } catch (Exception e) { //Catch exception if any System.err.println("Error: " + e.getMessage()); } } //compute averaage private void computeAverage() { int sum = 0; for (int i = 0; i < numOfInts; i++) sum += intArray[i]; avg = sum/numOfInts; System.out.println("avg = " + avg); } //event handling public void actionPerformed(ActionEvent e) { if(e.getSource() == avgBtn) { computeAverage(); } } //"main" function public static void main(String[] args) { Main m = new Main(); m.setVisible(true); } //paint public void paintComponent(Graphics g){ g.drawString(avg,75,75); } }
Any and all help / directions are appreciated I know I've used this code for other problems recently. I just want to know all this! Ideally, the panel will display the average value read when the button is clicked and show what was entered when the focus is on the text frame and input is pressed, but I'm taking small steps. As I said, I hope this post can become a general tutorial for others who have similar questions but don't find answers from sun documents or other websites Thank you very much in advance Dan:)
Solution
Create an internal class that extends JPanel in the main class:
class MyPanel extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(Integer.toString(avg),75); } }
Then, you need to call computeAverage () in actionPerformed and call repaint on the panel.
//event handling public void actionPerformed(ActionEvent e) { if (e.getSource() == avgBtn) { computeAverage(); panel.repaint(); } }