限制在水平JScrollPane中的垂直JScrollPane中的JText区域中的组件大小

时间:2015-12-01 22:58:58

标签: java jscrollpane jtextarea gridbaglayout boxlayout

如何将水平滚动窗格中组件的垂直尺寸限制为滚动窗格的垂直尺寸?

GUI应该总是这样:

http://i.stack.imgur.com/XlxBZ.png

这是滚动水平滚动条后得到的结果:

http://i.stack.imgur.com/n1LLE.png

相关代码段:创建框架,添加传感器列。也是在早些时候用BoxLayout尝试过这个问题。

frame = new JFrame();
    frame.setBounds(100, 100, 764, 494);
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{500, 500};
    gridBagLayout.rowHeights = new int[] {439,45};
    gridBagLayout.columnWeights = new double[]{1.0, 1.0};
    gridBagLayout.rowWeights = new double[]{1.0, 0.0};
    frame.getContentPane().setLayout(gridBagLayout);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setTitle("CSV Builder -- Development Version StackOverflow Example");

    //Panel for holding the text areas for each sensor
    JPanel sensorPanel = new JPanel();
    GridBagLayout sensorGridBagLayout = new GridBagLayout();
    sensorGridBagLayout.rowHeights = new int[] {40,40,39};
    sensorGridBagLayout.rowWeights = new double[]{0.0,1.0, 0.0};
    sensorPanel.setLayout(sensorGridBagLayout);

    //Scroll pane on horizontal box
    JScrollPane scrollPane = new JScrollPane(sensorPanel);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

    GridBagConstraints gbc_scrollPane = new GridBagConstraints();
    gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
    gbc_scrollPane.fill = GridBagConstraints.BOTH;
    gbc_scrollPane.gridx = 0;
    gbc_scrollPane.gridy = 0;
    frame.getContentPane().add(scrollPane, gbc_scrollPane);

    //Set up text areas for each sensor
    for(int k = 0; k < EngineDataParser.titles.length; k++){    

        //Make Label
        JLabel lblEngineTemperature = new JLabel(EngineDataParser.titles[k]);
        GridBagConstraints gbc_lblEngineTemperature = new GridBagConstraints();
        gbc_lblEngineTemperature.insets = new Insets(0, 0, 5, 5);
        gbc_lblEngineTemperature.gridx = k;
        gbc_lblEngineTemperature.gridy = 1;
        gbc_lblEngineTemperature.anchor = GridBagConstraints.NORTH;

        //Make text area
        JTextArea sensorTextArea = new JTextArea();
        sensorTextArea.setLineWrap(false);
        sensorTextArea.setText("No Data Yet");
        sensorTextArea.setBounds(50,50,50,200);
        GridBagConstraints gbc_sensorTextArea = new GridBagConstraints();
        gbc_sensorTextArea.insets = new Insets(0, 0, 5, 5);

        //Add scroll pane
        JScrollPane sensorScrollPane = new JScrollPane(sensorTextArea);
        sensorScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        sensorScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        sensorScrollPane.setBounds(50,50,50,200);
        GridBagConstraints gbc_sensorScrollPane = new GridBagConstraints();
        gbc_sensorScrollPane.insets = new Insets(0, 0, 5, 5);
        gbc_sensorScrollPane.fill = GridBagConstraints.BOTH;
        gbc_scrollPane.gridx = k;
        gbc_scrollPane.gridy = 2;
        gbc_scrollPane.weightx = 1.0;
        gbc_scrollPane.weighty = 1.0;
        gbc_scrollPane.anchor = GridBagConstraints.CENTER;

        //make checkbox
        JCheckBox exportCheckBox = new JCheckBox("Export "+EngineDataParser.titles[k]);
        GridBagConstraints gbc_exportCheckBox = new GridBagConstraints();
        exportCheckBox.addActionListener(checkboxListener);
        gbc_exportCheckBox.insets = new Insets(0, 0, 5, 5);
        gbc_exportCheckBox.gridx = k;
        gbc_exportCheckBox.gridy = 3;
        gbc_exportCheckBox.anchor = GridBagConstraints.SOUTH;

        //add all to panel
        sensorPanel.add(lblEngineTemperature, gbc_lblEngineTemperature);
        sensorPanel.add(sensorScrollPane, gbc_sensorScrollPane);
        sensorPanel.add(exportCheckBox, gbc_exportCheckBox);

        //add all to arrays for later adjusting
        sensorLabels.add(lblEngineTemperature);
        sensorTextAreas.add(sensorTextArea);
        sensorCheckBoxes.add(exportCheckBox);

    }

**********这是主要的想法,丰富的细节和可运行的代码如果它有帮助**********

背景:我正在为引擎测试系统制作GUI。我在带有水平滚动条的JScrollPane中有一个带GridBagLayout的JPanel。在面板的每一列中,都有一个标题,文本区域,其中滚动窗格包含一列传感器数据,还有一个复选框,询问用户是否要导出该列数据。

意图:当用户加载文件时,它将从引擎日志中读取数据,将每个传感器分离到JPanel中的单独列,并在按下导出按钮时导出任何已检查的列。

什么工作:所有后端文件处理/分离都有效。

问题:加载文件并移动水平滚动条后,文本区域会垂直变大并延伸到水平JScrollPane下方。

我已尝试使用GridBagLayout和BoxLayout来解决此问题。盒子布局首先看起来正确,但在水平滚动时显示相同的有害行为。

GridBagLayout也总是尝试将JTextArea添加到顶行。不知道为什么。

我考虑在JTextAreas上使用setMaximumSize(),但是如果用户调整整个窗口的大小,这可能会使它们太小(这就是我无论如何都要打扰布局管理器的全部原因。否则,对于这个小的我刚刚使用绝对布局的程序)

完整代码,主GUI:     这是代码:

package engineSensorReader;

import java.awt.Color;


public class CSVBuilder {

/*Creates a GUI that builds a CSV file from an file of raw serial output from a sensor array
 * Each line of the unprocessed file looks like so
 * <TEMP1:123,TEMP2:122,TEMP3:124,GLAT:1138, ... PONT:1,>
 * Each file has a different set of sensors
 * The program puts each sensor in a separate column with a check box beneath it
 * If the user leaves the box checked, that column is written to a CSV file the user exports
 */

//Globally accessible GUI components 
private JFrame frame;
JTextArea engineTemperatureTextArea = new JTextArea();
JButton loadFileButton = new JButton("Load File");
JFileChooser fileFinder = new JFileChooser();
JButton exportFileButton = new JButton("Export File");

//Lists of components pertaining to each sensor
private List<JLabel> sensorLabels = new ArrayList<JLabel>();
private List<JTextArea> sensorTextAreas = new ArrayList<JTextArea>();
private List<JCheckBox> sensorCheckBoxes = new ArrayList<JCheckBox>();

//Text are for raw file 
private JTextArea rawFileTextArea = new JTextArea();
private JScrollPane rawFileScrollPane = new JScrollPane(); 

//instantiate custom data parser object
EngineDataParser dataParser = new EngineDataParser();

//array of booleans tells us if we want a certain sensor in the output file
private boolean[] exportSensorChecks = new boolean[EngineDataParser.titles.length];

private boolean fileIsImported = false;

private Color greenish = new Color(196,250,185);
private Color reddish = new Color(250,199,185);


public static void main(String[] args){
    CSVBuilder mCSVBuilder = new CSVBuilder();
}

public JFrame getFrame() {
    return frame;
}

public CSVBuilder() {
    initialize();
}

void initialize() {

    frame = new JFrame();
    frame.setBounds(100, 100, 764, 494);
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{500, 500};
    gridBagLayout.rowHeights = new int[] {439,45};
    gridBagLayout.columnWeights = new double[]{1.0, 1.0};
    gridBagLayout.rowWeights = new double[]{1.0, 0.0};
    frame.getContentPane().setLayout(gridBagLayout);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Image mainIcon = new ImageIcon(this.getClass().getResource("/hat.png")).getImage();
    frame.setIconImage(mainIcon);
    frame.setVisible(true);
    frame.setTitle("CSV Builder -- Development Version StackOverflow Example");

    //Panel for holding the text areas for each sensor
    JPanel sensorPanel = new JPanel();
    GridBagLayout sensorGridBagLayout = new GridBagLayout();
    sensorGridBagLayout.rowHeights = new int[] {40,40,39};
    sensorGridBagLayout.rowWeights = new double[]{0.0,1.0, 0.0};
    sensorPanel.setLayout(sensorGridBagLayout);

    //Scroll pane on horizontal box
    JScrollPane scrollPane = new JScrollPane(sensorPanel);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

    GridBagConstraints gbc_scrollPane = new GridBagConstraints();
    gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
    gbc_scrollPane.fill = GridBagConstraints.BOTH;
    gbc_scrollPane.gridx = 0;
    gbc_scrollPane.gridy = 0;
    frame.getContentPane().add(scrollPane, gbc_scrollPane);

    //Set up text areas for each sensor
    for(int k = 0; k < EngineDataParser.titles.length; k++){    

        //Make Label
        JLabel lblEngineTemperature = new JLabel(EngineDataParser.titles[k]);
        GridBagConstraints gbc_lblEngineTemperature = new GridBagConstraints();
        gbc_lblEngineTemperature.insets = new Insets(0, 0, 5, 5);
        gbc_lblEngineTemperature.gridx = k;
        gbc_lblEngineTemperature.gridy = 1;
        gbc_lblEngineTemperature.anchor = GridBagConstraints.NORTH;

        //Make text area
        JTextArea sensorTextArea = new JTextArea();
        sensorTextArea.setLineWrap(false);
        sensorTextArea.setText("No Data Yet");
        sensorTextArea.setBounds(50,50,50,200);
        GridBagConstraints gbc_sensorTextArea = new GridBagConstraints();
        gbc_sensorTextArea.insets = new Insets(0, 0, 5, 5);

        //Add scroll pane
        JScrollPane sensorScrollPane = new JScrollPane(sensorTextArea);
        sensorScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        sensorScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        sensorScrollPane.setBounds(50,50,50,200);
        GridBagConstraints gbc_sensorScrollPane = new GridBagConstraints();
        gbc_sensorScrollPane.insets = new Insets(0, 0, 5, 5);
        gbc_sensorScrollPane.fill = GridBagConstraints.BOTH;
        gbc_scrollPane.gridx = k;
        gbc_scrollPane.gridy = 2;
        gbc_scrollPane.weightx = 1.0;
        gbc_scrollPane.weighty = 1.0;
        gbc_scrollPane.anchor = GridBagConstraints.CENTER;

        //make checkbox
        JCheckBox exportCheckBox = new JCheckBox("Export "+EngineDataParser.titles[k]);
        GridBagConstraints gbc_exportCheckBox = new GridBagConstraints();
        exportCheckBox.addActionListener(checkboxListener);
        gbc_exportCheckBox.insets = new Insets(0, 0, 5, 5);
        gbc_exportCheckBox.gridx = k;
        gbc_exportCheckBox.gridy = 3;
        gbc_exportCheckBox.anchor = GridBagConstraints.SOUTH;

        //add all to panel
        sensorPanel.add(lblEngineTemperature, gbc_lblEngineTemperature);
        sensorPanel.add(sensorScrollPane, gbc_sensorScrollPane);
        sensorPanel.add(exportCheckBox, gbc_exportCheckBox);

        //add all to arrays for later adjusting
        sensorLabels.add(lblEngineTemperature);
        sensorTextAreas.add(sensorTextArea);
        sensorCheckBoxes.add(exportCheckBox);

    }       

    Box buttonBox = Box.createHorizontalBox();
    GridBagConstraints gbc_buttonBox = new GridBagConstraints();
    gbc_buttonBox.gridx = 1;
    gbc_buttonBox.gridy = 1;
    gbc_buttonBox.anchor = GridBagConstraints.EAST;
    frame.getContentPane().add(buttonBox, gbc_buttonBox);

    rawFileTextArea = new JTextArea();
    rawFileTextArea.setText("No file selected yet");
    rawFileTextArea.setBounds(50,50,300,400);

    rawFileScrollPane = new JScrollPane(rawFileTextArea);
    rawFileScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    rawFileScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    JLabel rawFileLabel = new JLabel("Raw File Contents");

    Box rawFileBox = Box.createVerticalBox();
    rawFileBox.add(rawFileLabel);
    rawFileBox.add(rawFileScrollPane);
    GridBagConstraints gbc_rawFileBox = new GridBagConstraints();
    gbc_rawFileBox.gridx = 1;
    gbc_rawFileBox.gridy = 0;
    gbc_rawFileBox.anchor = GridBagConstraints.WEST;
    gbc_rawFileBox.fill = GridBagConstraints.BOTH;
    gbc_rawFileBox.insets = new Insets(0, 0, 5, 5);
    frame.getContentPane().add(rawFileBox, gbc_rawFileBox);

    loadFileButton.addActionListener(manipulateFileListener);
    buttonBox.add(loadFileButton);

    exportFileButton.addActionListener(manipulateFileListener);
    buttonBox.add(exportFileButton);

    frame.pack();
    frame.setVisible(true);
}

//Reads raw serial file to text areas
private void readFileToBoxes(File importedFile) throws IOException{
    try{
        FileReader importReader = new FileReader(importedFile); 
        BufferedReader readFileReader = new BufferedReader(importReader);
        StringBuilder fileContents = new StringBuilder((int)importedFile.length());
        Scanner scanner = new Scanner(importedFile);
        String lineSeparator = System.getProperty("line.separator");
        String currentSensorReading;
        String readLineString;

        try {
            while(scanner.hasNextLine()) {

                readLineString = scanner.nextLine();
                rawFileTextArea.append(readLineString +"\n");
                dataParser.interpret(readLineString);
                if(dataParser.readyToOutput){
                    int newNumber = 0;
                    for(int h = 0; h<EngineDataParser.titles.length;h++){
                        if(fileIsImported == false){ //Check if this is first run through
                            sensorTextAreas.get(h).setText("");
                        }
                        currentSensorReading = EngineDataParser.getLastNumericalReadings()[h];
                        if(currentSensorReading!=null){
                            sensorTextAreas.get(h).append(currentSensorReading+"\n");
                            sensorTextAreas.get(h).setBackground(greenish);
                            sensorCheckBoxes.get(h).setSelected(true);
                            exportSensorChecks[h] = true;
                        }else{
                            System.out.println("no data," + EngineDataParser.titles[h] + "iterator: "+ h);
                            sensorTextAreas.get(h).append(currentSensorReading+"\n");
                            sensorTextAreas.get(h).setBackground(reddish);
                            sensorCheckBoxes.get(h).setSelected(false);
                            exportSensorChecks[h] = false;
                        }

                    }
                    fileIsImported = true;
                }
            }
        } finally {
            scanner.close();
        }

    }catch(FileNotFoundException didNotFindFile){
        didNotFindFile.printStackTrace();
        engineTemperatureTextArea.setText("File chosen but not found"); 
    }
}

//Writes appropriate columns to CSV file
private void saveFileToCSV(File fileToSave){
    String dataLine = "";
    try {
        PrintWriter writeToCSVWriter = new PrintWriter(fileToSave);
        for(int sensor = 0; sensor <EngineDataParser.titles.length; sensor++){
            if(exportSensorChecks[sensor] == true){
                writeToCSVWriter.print(EngineDataParser.titles[sensor]);
                writeToCSVWriter.print(",");
            }
        }

        for(int dataPoint = 0; dataPoint <= dataParser.getWriteToIndex(); dataPoint++){
            dataLine = "";
            for(int sensor = 0; sensor <EngineDataParser.titles.length; sensor++){
                if(exportSensorChecks[sensor] == true){
                    System.out.println("To here, printing data point");
                    dataLine  += dataParser.getAssignedDataPoint(sensor, dataPoint) + ",";
                }
            }
            writeToCSVWriter.println(dataLine);
        }
        writeToCSVWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//Check box listener handles...well, checkboxes and coloring text areas
ActionListener checkboxListener = new ActionListener(){
    public void actionPerformed(ActionEvent boxChecked){
        for(int boxIndex = 0; boxIndex < EngineDataParser.titles.length; boxIndex ++){
            if(boxChecked.getSource() == sensorCheckBoxes.get(boxIndex)){
                if(sensorCheckBoxes.get(boxIndex).isSelected()){
                    exportSensorChecks[boxIndex] = true;
                    sensorTextAreas.get(boxIndex).setBackground(greenish);
                }else{
                    exportSensorChecks[boxIndex] = false;
                    sensorTextAreas.get(boxIndex).setBackground(reddish);
                }
            }
        }
    }
};

//Action listener handles file importing and exporting
ActionListener manipulateFileListener = new ActionListener(){
    public void actionPerformed(ActionEvent e){
        if(e.getSource() == loadFileButton){
            int whatHappens = fileFinder.showOpenDialog(frame);
            if(whatHappens == JFileChooser.APPROVE_OPTION){
                File importedFile = fileFinder.getSelectedFile();
                try{
                    readFileToBoxes(importedFile);
                }catch(IOException didNotFindFile){
                    didNotFindFile.printStackTrace();
                    engineTemperatureTextArea.setText("File chosen but something else failed"); 
                }
                engineTemperatureTextArea.setText("We chose the file: " + importedFile.getName());
            }else{
                engineTemperatureTextArea.setText("We somehow failed to choose a file");
            }
        }else if(e.getSource() == exportFileButton){
            int whatHappens = fileFinder.showSaveDialog(frame);
            if(whatHappens == JFileChooser.APPROVE_OPTION){
                File exportFile = fileFinder.getSelectedFile();
                saveFileToCSV(exportFile);
                engineTemperatureTextArea.setText("We exported the file: " + exportFile.getName());

                if(exportFile.getName().indexOf(".csv") < 0 && exportFile.getName().indexOf(".txt") < 0){
                    JOptionPane.showMessageDialog(frame, "Unrecognized file extension or no extension used.  Consider re-saving as .txt (for using CSV builder) or .csv (for easier use with spreadsheet)");
                }

            }else{
                engineTemperatureTextArea.setText("We somehow failed to choose a file");
            }
        }
    }
};

数据分析类

package engineSensorReader;

import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class EngineDataParser implements Runnable {

static boolean readyToOutput = false; //shows we have data ready to update a GUI or whatever
static boolean enableFileWrite = false; //will be set to true if we want to log this data to a file
static boolean listsOfPointsCreated = false; //tells us we need to make titles and all

//Arraylists for each sensor reading.  We won't always have all of them but that's alright
ArrayList<String> engineTemperatures = new ArrayList<String>();
ArrayList<String> transmissionTemperatures = new ArrayList<String>();
ArrayList<String> ambientTemperatures = new ArrayList<String>();
ArrayList<String> auxiliaryTemperatures = new ArrayList<String>();
ArrayList<String> engineRPMs = new ArrayList<String>();
ArrayList<String> cVTDrivenRPMs = new ArrayList<String>();
ArrayList<String> gPSLatitudes = new ArrayList<String>();
ArrayList<String> gPSLongitudes = new ArrayList<String>();
ArrayList<String> gPSAltitudes = new ArrayList<String>();
ArrayList<String> gPSFixes = new ArrayList<String>();
ArrayList<String> fuelLevels = new ArrayList<String>();
ArrayList<String> throttlePositions = new ArrayList<String>();
ArrayList<String> pointCounts = new ArrayList<String>();
ArrayList<String> auxiliarySensor1Readings = new ArrayList<String>();
ArrayList<String> auxiliarySensor2Readings = new ArrayList<String>();
ArrayList<String> auxiliarySensor3Readings = new ArrayList<String>();

ArrayList<ArrayList<String>> allDataArray = new ArrayList<ArrayList<String>>();

private int writeToIndex = 0;

//String ArrayList of titles for each
static String[] titles = {"Transmission Temperature","Engine Temperature","Ambient Temperature","Auxiliary Temperature","Engine RPM","CVT Driven RPM","GPS Latitidue (Decimal Degrees)","GPS Longitude (Decimal Degrees)","GPS Altitude","GPS Fix (1 or 0)","Fuel Level","Throttle Position","Point Count","Auxilary Sensor 1","Auxilary Sensor 2","Auxilary Sensor 3"};

private static volatile String[] lastNumericalReadings = new String[titles.length];

public void run(){

}

public String getAssignedDataPoint(int sensorIndex, int readingNumber){
    String foundValue = "";
    if(sensorIndex < titles.length){
        if(sensorIndex == 0){
            if(readingNumber < transmissionTemperatures.size()){
                foundValue = transmissionTemperatures.get(readingNumber);
            }
        }else if(sensorIndex == 1){
            if(readingNumber < engineTemperatures.size()){
                foundValue = engineTemperatures.get(readingNumber);
            }
        }else if(sensorIndex == 2){
            if(readingNumber <ambientTemperatures.size()){
                foundValue = ambientTemperatures.get(readingNumber);
            }
        }else if(sensorIndex == 3){
            if(readingNumber <auxiliaryTemperatures.size()){
                foundValue = auxiliaryTemperatures.get(readingNumber);
            }
        }else if(sensorIndex == 4){
            if(readingNumber <engineRPMs.size()){
                foundValue = engineRPMs.get(readingNumber);
            }
        }else if(sensorIndex == 5){
            if(readingNumber <cVTDrivenRPMs.size()){
                foundValue = cVTDrivenRPMs.get(readingNumber);
            }
        }else if(sensorIndex == 6){
            if(readingNumber <gPSLatitudes.size()){
                foundValue = gPSLatitudes.get(readingNumber);
            }
        }else if(sensorIndex == 7){
            if(readingNumber <gPSLongitudes.size()){
                foundValue = gPSLongitudes.get(readingNumber);
            }
        }else if(sensorIndex == 8){
            if(readingNumber <gPSAltitudes.size()){
                foundValue = gPSAltitudes.get(readingNumber);
            }
        }else if(sensorIndex == 8){
            if(readingNumber <gPSFixes.size()){
                foundValue = gPSFixes.get(readingNumber);
            }
        }else if(sensorIndex == 10){
            if(readingNumber <fuelLevels.size()){
                foundValue = fuelLevels.get(readingNumber);
            }
        }else if(sensorIndex == 11){
            if(readingNumber <throttlePositions.size()){
                foundValue = throttlePositions.get(readingNumber);
            }
        }else if(sensorIndex == 12){
            if(readingNumber <pointCounts.size()){
                foundValue = pointCounts.get(readingNumber);
            }
        }else if(sensorIndex == 13){
            if(readingNumber <auxiliarySensor1Readings.size()){
                foundValue = auxiliarySensor1Readings.get(readingNumber);
            }
        }else if(sensorIndex == 14){
            if(readingNumber <auxiliarySensor2Readings.size()){
                foundValue = auxiliarySensor2Readings.get(readingNumber);
            }
        }else if(sensorIndex == 15){
            if(readingNumber <auxiliarySensor3Readings.size()){
                foundValue = auxiliarySensor3Readings.get(readingNumber);
            }
        }
    }

    if(foundValue.equals("")){
        foundValue = "0";
        System.out.println("HULLO? No sensor at requested index");
        System.out.print(" (Index: " + sensorIndex + "readingNumber: " + readingNumber +")");
        System.out.println(readingNumber);  
    }
    return foundValue;

}

public int countAvailableSensors(String stringIn){
    String[] bitsOfData = stringIn.split(",");
    System.out.print("The bits of data: ");
    System.out.println(bitsOfData);
    System.out.print("There are "+bitsOfData.length+" sensors.");
    return bitsOfData.length;

}

public void interpret(String stringIn){
    //take last data point from SerialReader
    //      System.out.println("Parser Called");
    //split at commas
    String[] bitsOfData = stringIn.split(",");

    //Check that we have a full string
    if(stringIn.indexOf("<") != -1 && stringIn.indexOf(">") != -1){
        //go through token by token
        for(String token : bitsOfData){
            //System.out.println(token);
            if(token.indexOf("TMP") != -1){//We have found a temperature reading
                //Split at :
                String[] tokenSplit = token.split(":");
                //Find title (T1, T2 etc)

                //Add to appropriate list of sensorReadings
                if(tokenSplit[0].indexOf("1")!=-1){
                    //We have transmission temperatures
                    transmissionTemperatures.add(tokenSplit[1]);
                    lastNumericalReadings[0] = tokenSplit[1];
                }else if(tokenSplit[0].indexOf("2")!=-1){
                    //we have engine temperature
                    engineTemperatures.add(tokenSplit[1]);
                    lastNumericalReadings[1]= tokenSplit[1];
                }else if(tokenSplit[0].indexOf("3")!=-1){
                    //we have ambient temperature
                    ambientTemperatures.add(tokenSplit[1]);
                    lastNumericalReadings[2]= tokenSplit[1];
                }else if(tokenSplit[0].indexOf("4")!=-1){
                    //we have aux temperature
                    auxiliaryTemperatures.add(tokenSplit[1]);
                    lastNumericalReadings[3]= tokenSplit[1];
                }
            }else if(token.indexOf("RPM1") != -1){//We have found engine RPM reading
                String[] tokenSplit = token.split(":");
                engineRPMs.add(tokenSplit[1]);
                lastNumericalReadings[4]= tokenSplit[1];
            }else if(token.indexOf("RPM2")!=-1){//We have found CVT Driven RPM
                String[] tokenSplit = token.split(":");
                lastNumericalReadings[5]= tokenSplit[1];
                cVTDrivenRPMs.add(tokenSplit[1]);
            }else if(token.indexOf("GLON") != -1){//We have found GPS Latitude
                String[] tokenSplit = token.split(":");
                gPSLatitudes.add(tokenSplit[1]);
                lastNumericalReadings[6]= tokenSplit[1];
            }else if(token.indexOf("GLAT") != -1){//We have found GPS Longitude
                String[] tokenSplit = token.split(":");
                gPSLongitudes.add(tokenSplit[1]);
                lastNumericalReadings[7]= tokenSplit[1];
            }else if(token.indexOf("GALT") != -1){//We have found GPS Altitude
                String[] tokenSplit = token.split(":");
                gPSAltitudes.add(tokenSplit[1]);
                lastNumericalReadings[8]= tokenSplit[1];
            }else if(token.indexOf("GFIX") != -1){//We have found GPS Fix
                String[] tokenSplit = token.split(":");
                gPSFixes.add(tokenSplit[1]);
                lastNumericalReadings[9]= tokenSplit[1];
            }else if(token.indexOf("FUL1") != -1){//We have found fuel level
                String[] tokenSplit = token.split(":");
                fuelLevels.add(tokenSplit[1]);
                lastNumericalReadings[10]= tokenSplit[1];
            }else if(token.indexOf("TPS1") != -1){//We have found throttle position
                String[] tokenSplit = token.split(":");
                throttlePositions.add(tokenSplit[1]);
                lastNumericalReadings[11]= tokenSplit[1];
            }else if(token.indexOf("PNT1")!= -1){//We have found point count
                String[] tokenSplit = token.split(":");
                pointCounts.add(tokenSplit[1]);
                lastNumericalReadings[12]= tokenSplit[1];
            }else if(token.indexOf("AUX1")!= -1){//We have found Auxilary Sensor 1
                String[] tokenSplit = token.split(":");
                auxiliarySensor1Readings.add(tokenSplit[1]);
                lastNumericalReadings[13]= tokenSplit[1];
            }else if(token.indexOf("AUX2")!= -1){//We have found Auxilary Sensor 2
                String[] tokenSplit = token.split(":");
                auxiliarySensor2Readings.add(tokenSplit[1]);
                lastNumericalReadings[14]= tokenSplit[1];
            }else if(token.indexOf("AUX3")!= -1){//We have found Auxilary Sensor 3
                String[] tokenSplit = token.split(":");
                auxiliarySensor3Readings.add(tokenSplit[1]);
                lastNumericalReadings[15]= tokenSplit[1];
            }
        }

        setWriteToIndex(getWriteToIndex() + 1);
        //if this is the first time through, say we're now ready for output and reset WriteToIndex
        if(readyToOutput == false){
            readyToOutput = true;
            setWriteToIndex(0);

            //              for(String reading:lastNumericalReadings){
            //              
            //              }
        }
        System.out.println("Here's the last numerical readings: ");
        System.out.println(Arrays.deepToString(lastNumericalReadings));

    }else{
        System.out.println("We didn't get a full string");
    }

}


public static String[] getLastNumericalReadings(){
    return lastNumericalReadings;
}

public int getWriteToIndex() {
    return writeToIndex;
}

public void setWriteToIndex(int writeToIndex) {
    this.writeToIndex = writeToIndex;
}
}

导入文件中的一行如下所示。不幸的是,它们看起来像HTML标签,因此发布整个文件是有问题的。但是典型的导入文件只是一堆类似于此的行,所以如果你冒险进行测试,只需将其粘贴到.txt一百万次。

                  <TMP1:142,TMP2:144,TMP3:138,RPM1:3708,RPM2:1280,GLAT:4042.6142,GLON:07400.4168,GALT:545.4,GFIX:0,FUL1:110.00,TPS1:210,TPS1:336,PNT1:0,>, 

1 个答案:

答案 0 :(得分:0)

看太多代码看看你在做什么。当你提出问题时,你应该发布一个简单的代码来证明这个问题。有关详细信息,请参阅SSCCE

  

如何将水平滚动窗格中组件的垂直尺寸限制为滚动窗格的垂直尺寸?

您添加到滚动窗格的面板需要实现Scrollable界面。特别是,您需要使用getScrollableTracksViewportHeight()方法返回true

为了节省您自己实现整个界面,您可能需要查看Scrollable Panel。此类为您实现这些方法,您只需在类上设置属性即可获得所需的结果。听起来像你需要使用FIT属性作为可滚动高度。

相关问题