如何从其他面板的JTextField获取输入

时间:2019-10-15 07:45:23

标签: java swing textarea

我是使用JTextFields的新手,并对如何从3个不同的面板获取输入感到好奇。面板将从输入中获取数字并平均得分。为此,我想访问所有3个面板进行数学运算。我有一个小组,希望平均三个不同的人的分数。因此,我想获取mattsTotalScore并将其与timsTotalScore和BensTotalScore相加,并在第四个面板上的按钮后显示平均值。

import javax.swing.*;
import java.awt.*;

public class MattPanel extends JPanel {

    public MattPanel(){
        Dimension size = getPreferredSize();
        size.width = 250;
        setPreferredSize(size);
        setBorder(BorderFactory.createTitledBorder("Matt's Scores"));

        JLabel memMatt = new JLabel("MEMORABILITY :");
        JTextField textMemMattPane = new JTextField(10);

        JLabel comMatt = new JLabel("COMPOSITION :");
        JTextField textComMattPane = new JTextField(10);

        JLabel mixMatt = new JLabel("MIX/MASTER :");
        JTextField textMixMattPane = new JTextField(10);

        JLabel soundMatt = new JLabel("SOUND DESIGN :");
        JTextField textSoundMattPane = new JTextField(10);

        JLabel enjoyMatt = new JLabel("ENJOYMENT :");
        JTextField textEnjoyMattPane = new JTextField(10);

        setLayout(new GridBagLayout());

        GridBagConstraints gc = new GridBagConstraints();

        ///First Column ///////////////////////
        gc.anchor = GridBagConstraints.LINE_END;
        gc.weightx = 0.5; gc.weighty = 0.5;
        gc.gridx = 0; gc.gridy = 0;
        add(memMatt, gc);

        gc.gridx = 0; gc.gridy = 1;
        add(comMatt, gc);

        gc.gridx = 0; gc.gridy = 2;
        add(mixMatt, gc);

        gc.gridx = 0; gc.gridy = 3;
        add(soundMatt, gc);

        gc.gridx = 0; gc.gridy = 4;
        add(enjoyMatt, gc);

        //Second Column //////////////////////
        gc.anchor = GridBagConstraints.LINE_START;
        gc.gridx = 1; gc.gridy = 0;
        add(textMemMattPane,gc);

        gc.gridx = 1; gc.gridy = 1;
        add(textComMattPane,gc);

        gc.gridx = 1; gc.gridy = 2;
        add(textMixMattPane,gc);

        gc.gridx = 1; gc.gridy = 3;
        add(textSoundMattPane,gc);

        gc.gridx = 1; gc.gridy = 4;
        add(textEnjoyMattPane,gc);
    }
}

1 个答案:

答案 0 :(得分:-1)

您可以尝试使用JPanel的getComponents()方法来获取所有组件,尽管您必须以某种方式标识TextField,例如:

MattPanel panel = new MattPanel();
int sum = 0;
int nr = 0;
for(Component comp : panel.getComponents()){
    if(comp instanceof JTextField){ 
        String text = ((JTextField)comp).getText();
        sum += Integer.parseInt(text);
        nr ++;
    }
}
double avg = sum/nr;