2015-12-01 11 views
0

Как ограничить вертикальный размер компонентов в горизонтальной панели прокрутки до вертикального размера панели прокрутки?Ограничение размера компонента в области JText в вертикальной панели JScrollPane в горизонтальном JScrollPane

Графический интерфейс пользователя всегда должен выглядеть примерно так:

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

    } 

********** Вот основная идея, обильная деталь и работоспособный код следует в случае, если это помогает **********

Справочной информации: Я m - создание графического интерфейса для системы тестирования двигателя. У меня есть JPanel с GridBagLayout внутри JScrollPane с горизонтальной полосой прокрутки. В каждом столбце панели есть заголовок, текстовая область с областью прокрутки, содержащая столбец данных датчика, и флажок, запрашивающий у пользователя, хотите ли они экспортировать этот столбец данных.

Цель: когда пользователь загружает файл, он будет считывать данные из журнала движков, выделять каждый датчик в отдельный столбец JPanel и экспортировать все отмеченные столбцы при нажатии кнопки экспорта.

Работает: все операции обработки и разделения файлов на заднем конце.

Проблема: после того, как файл загружен и горизонтальная полоса прокрутки перемещается, области текста становятся вертикально большими и проходят ниже горизонтальной JScrollPane.

Я попытался использовать GridBagLayout и BoxLayout для решения этой проблемы. Сначала расположение ящиков выглядит правильно, но показывает такое же вредное поведение при горизонтальной прокрутке.

GridBagLayout также всегда пытается добавить JTextArea в верхнюю строку. Не знаю, почему.

Я рассмотрел использование setMaximumSize() в JTextAreas, но это может сделать их слишком маленькими, если пользователь изменит размер всего окна (в этом вся причина, по которой я беспокоюсь с менеджерами компоновки в любом случае. В противном случае для этого небольшого программа, которую я бы просто использовал абсолютный макет)

Полный код, главный 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,>, 

ответ

0

Слишком много кода, чтобы посмотреть, что вы делаете. Когда вы задаете вопрос, вы должны опубликовать простой код, который демонстрирует проблему.См. SSCCE для получения дополнительной информации.

Как ограничить вертикальный размер компонентов в горизонтальной области прокрутки до вертикального размера панели прокрутки?

Панель, которую вы добавляете в панель прокрутки, должна реализовать интерфейс Scrollable. В частности, вам нужен метод getScrollableTracksViewportHeight() для возврата true.

Чтобы сэкономить на реализации всего интерфейса, вы можете проверить Scrollable Panel. Этот класс реализует методы для вас, и вы можете просто установить свойства класса для достижения желаемого результата. Мне кажется, что вам нужно будет использовать свойство FIT для прокручиваемой высоты.

 Смежные вопросы

  • Нет связанных вопросов^_^