我正在寻找如何在JPanel中绘制文本的最基本描述。我知道有数十亿个教程,但没有一个适合我,而我有一些特定的问题,这可能有助于其他困惑的人。作为设置(测试应用程序),我有一个类,其中包含JLabel、JTextField、JButton和JPanel。该应用程序从外部文件中读取整数,并在按下JButton时显示它们的平均值。我已经将所有底层编程都解决了(也就是说,按钮响应并将平均值打印到命令行),但我似乎无法解决如何将平均值打印到面板中。我猜我最大的问题是如何将paint()或paintComponet()方法与其余代码结合起来。它应该是自己的类吗?JPanel应该是自己的类吗?似乎大多数教程都在告诉我是这样的,只是不确定第一步是什么。代码看起来像:
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);
}
}
非常感谢您的帮助和指导。我知道我最近在其他问题中使用了这段代码,我只是想了解全部!理想情况下,当单击按钮时,面板将显示读入整数的平均值,并在焦点在文本字段上并按下回车键时显示输入的任何内容,但我正在迈出踏实的步伐,就像我所说的那样,我希望这个主题成为一个通用教程,供其他有类似问题的人参考,他们在sun docs或其他网站上找不到答案。非常感谢您的提前帮助。丹 :)