我正在寻找有关如何在 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);
}
}
任何和所有的帮助/方向表示赞赏。我知道我最近将此代码用于其他问题,我只想知道这一切!理想情况下,面板会在单击按钮时显示以整数为单位读取的平均值,并在焦点位于其上并按下输入时显示输入到 textfeild 中的任何内容,但我正在采取婴儿步骤,就像我说的那样,我希望此线程成为其他有类似问题但无法从 sun 文档或其他站点找到答案的人的通用教程。提前非常感谢。丹:)