在JPanel中绘制文本 [英] drawing text within a JPanel

查看:157
本文介绍了在JPanel中绘制文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找如何在JPanel中绘制文本的最基本描述。我知道那里有十亿个教程,但是他们没有一个点击我,我有一些具体问题可以帮助其他困惑的人。作为一个设置(测试应用程序),我有一个具有JLabel,JTextField,JButton和JPanel的类。应用程序从外部文件中读取整数,并在按下JButton时在面板中显示它们的平均值。我将所有底层编程整理出来(也就是说,按钮响应并将平均值打印到命令行中),但我似乎无法理清如何将平均值打印到面板。我想我最大的问题是如何将paint()或paintComponet()方法与代码的其余部分一起使用。它应该是自己的班级吗? JPanel应该是自己的课程吗?看起来这就是大多数教程告诉我的,我只是不确定第一步究竟是什么。代码如下所示:

  import javax.swing。*; 
import java.awt。*;
import java.awt.event。*;
import java.io. *;
$ b $ public class Main扩展JFrame实现ActionListener {
private int [] intArray = new int [10000];
private int numOfInts = 0;
private int avg = 0;

保护JButton avgBtn;
保护JTextField indexEntry;
保护JLabel说明;
保护JPanel resultsPanel;

public Main(){

//创建主框架
this.setTitle(Section V,question 2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(350,250);
this.setLayout(new GridLayout(4,1));

//创建指令标签并添加到框架
instructions = new JLabel(按照考试中的说明使用该程序);
this.add(instructions);

//为索引条目创建文本字段并添加到框架
indexEntry = new JTextField();
this.add(indexEntry);

//创建按钮以获得平均值并添加到框架
avgBtn = new JButton(Click for Average);
this.add(avgBtn);
avgBtn.addActionListener(this);

//创建面板以显示结果并添加到框架
resultsPanel = new JPanel();
resultsPanel.setBackground(Color.BLUE);
this.add(resultsPanel);

//从文件读入
readFromFile();

//计算平均值
computeAverage();

$ b private void readFromFile(){
try {
//打开文件
FileInputStream fstream = new FileInputStream(numbers.dat) ;
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

//创建用于读入ints的占位符
String strLine;

//按行读取文件行
int i = 0; ((strLine = br.readLine())!= null){
//在数组中放置整数并增加整数的计数
System.out.println(strLine);
intArray [i] = Integer.parseInt(strLine);
numOfInts ++;
i ++;
}
//关闭输入流
in.close();
System.out.println(numOfInts =+ numOfInts);
}
catch(Exception e){
//捕获异常(如果有的话)
System.err.println(Error:+ e.getMessage());



//计算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);


//事件处理
public void actionPerformed(ActionEvent e){
if(e.getSource()== avgBtn){
computeAverage ();


$ b // main函数
public static void main(String [] args){
Main m = new Main() ;
m.setVisible(true);
}

// paint
public void paintComponent(Graphics g){
g.drawString(avg,75,75);
}
}

赞赏任何及所有帮助/方向。我知道我最近使用了这个代码来处理其他问题,我只是想知道这一切!理想情况下,当单击按钮时,面板将显示读入的平均值,并在焦点位于其上并按下输入时显示在textfeild中输入的内容,但我正在采取婴儿步骤,就像我说的,我希望这篇文章能够成为其他人的一般教程,但也有类似问题的人不能从sun docs或其他站点找到答案。非常感谢提前。 Dan :)

解决方案

创建一个内部类来扩展Main类中的JPanel:

  class MyPanel extends JPanel {

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

}

然后你需要调用repaint在actionPerformed中调用computeAverage()之后的面板:

  //事件处理
public void actionPerformed(ActionEvent e){
if(e.getSource()== avgBtn){
computeAverage();
panel.repaint();
}
}


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 have some specific questions which may help others who are confused. As a setup (a testing app) I have a single class which has a JLabel, a JTextField, a JButton, and a JPanel. The application reads in ints from an external file and should display their average in the panel when the JButton is pressed. I have all the underlying programing sorted out (that is, the button responds and prints the average to the command line) but I just cannot seem to sort out how to print the average to the panel. I guess my biggest question is how to incorporate the paint() or paintComponet() method in along with the rest of the code. Should it be it's own class? Should the JPanel be it's own class? It seems like that's what most of the tutorials are telling me, I'm just not sure what the first step is exactly. The code looks like:

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/direction is appreciated. I know I've used this code recently for other questions, I just want to know it all! Ideally the panel would display the average of the read in ints when the button was clicked, and display whatever was entered into the textfeild when the focus was on it and enter was pressed, but I'm taking baby steps, and like I said, I'd like for this thread to be a general tutorial for others with similar questions who aren't finding answers from sun docs or other sites. Thanks so much in advance. Dan :)

解决方案

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

这篇关于在JPanel中绘制文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆