[refactor] fixed warnings and made variable names more explicit in [Freeform]FinSetConfig Dialogs

- de-duped  writeCSVFile methods
This commit is contained in:
Daniel_M_Williams 2018-06-17 14:19:46 -04:00
parent 3209e0201e
commit c1d8bfda06
2 changed files with 104 additions and 150 deletions

View File

@ -135,7 +135,7 @@ public abstract class FinSetConfig extends RocketComponentConfig {
} }
public JPanel finTabPanel() { private JPanel finTabPanel() {
JPanel panel = new JPanel( JPanel panel = new JPanel(
new MigLayout("align 50% 20%, fillx, gap rel unrel, ins 20lp 10% 20lp 10%", new MigLayout("align 50% 20%, fillx, gap rel unrel, ins 20lp 10% 20lp 10%",
"[150lp::][65lp::][30lp::][200lp::]", "")); "[150lp::][65lp::][30lp::][200lp::]", ""));
@ -185,14 +185,14 @@ public abstract class FinSetConfig extends RocketComponentConfig {
label.setToolTipText(trans.get("FinSetConfig.ttip.Tabheight")); label.setToolTipText(trans.get("FinSetConfig.ttip.Tabheight"));
panel.add(label, "gapleft para"); panel.add(label, "gapleft para");
final DoubleModel mth = new DoubleModel(component, "TabHeight", UnitGroup.UNITS_LENGTH, 0); final DoubleModel tabHeightModel = new DoubleModel(component, "TabHeight", UnitGroup.UNITS_LENGTH, 0);
component.addChangeListener( tabHeightModel );
spin = new JSpinner(mth.getSpinnerModel()); spin = new JSpinner(tabHeightModel.getSpinnerModel());
spin.setEditor(new SpinnerEditor(spin)); spin.setEditor(new SpinnerEditor(spin));
panel.add(spin, "growx"); panel.add(spin, "growx");
panel.add(new UnitSelector(mth), "growx"); panel.add(new UnitSelector(tabHeightModel), "growx");
panel.add(new BasicSlider(mth.getSliderModel(DoubleModel.ZERO, length2)), panel.add(new BasicSlider(tabHeightModel.getSliderModel(DoubleModel.ZERO, length2)),
"w 100lp, growx 5, wrap"); "w 100lp, growx 5, wrap");
//// Tab position: //// Tab position:
@ -202,7 +202,7 @@ public abstract class FinSetConfig extends RocketComponentConfig {
panel.add(label, "gapleft para"); panel.add(label, "gapleft para");
final DoubleModel mts = new DoubleModel(component, "TabShift", UnitGroup.UNITS_LENGTH); final DoubleModel mts = new DoubleModel(component, "TabShift", UnitGroup.UNITS_LENGTH);
component.addChangeListener( mts);
spin = new JSpinner(mts.getSpinnerModel()); spin = new JSpinner(mts.getSpinnerModel());
spin.setEditor(new SpinnerEditor(spin)); spin.setEditor(new SpinnerEditor(spin));
panel.add(spin, "growx"); panel.add(spin, "growx");
@ -214,9 +214,10 @@ public abstract class FinSetConfig extends RocketComponentConfig {
label = new JLabel(trans.get("FinSetConfig.lbl.relativeto")); label = new JLabel(trans.get("FinSetConfig.lbl.relativeto"));
panel.add(label, "right, gapright unrel"); panel.add(label, "right, gapright unrel");
final EnumModel<FinSet.TabRelativePosition> em = new EnumModel<FinSet.TabRelativePosition>(component, "TabRelativePosition");
final EnumModel<AxialMethod> em = new EnumModel<>(component, "TabRelativePosition");
JComboBox<?> enumCombo = new JComboBox<FinSet.TabRelativePosition>(em); JComboBox<AxialMethod> enumCombo = new JComboBox<>(em);
panel.add( enumCombo, "spanx 3, growx, wrap para"); panel.add( enumCombo, "spanx 3, growx, wrap para");
@ -233,7 +234,7 @@ public abstract class FinSetConfig extends RocketComponentConfig {
try { try {
document.startUndo("Compute fin tabs"); document.startUndo("Compute fin tabs");
List<CenteringRing> rings = new ArrayList<CenteringRing>(); List<CenteringRing> rings = new ArrayList<>();
//Do deep recursive iteration //Do deep recursive iteration
Iterator<RocketComponent> iter = parent.iterator(false); Iterator<RocketComponent> iter = parent.iterator(false);
while (iter.hasNext()) { while (iter.hasNext()) {
@ -244,8 +245,8 @@ public abstract class FinSetConfig extends RocketComponentConfig {
double depth = ((Coaxial) parent).getOuterRadius() - it.getOuterRadius(); double depth = ((Coaxial) parent).getOuterRadius() - it.getOuterRadius();
//Set fin tab depth //Set fin tab depth
if (depth >= 0.0d) { if (depth >= 0.0d) {
mth.setValue(depth); tabHeightModel.setValue(depth);
mth.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); tabHeightModel.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit());
} }
} }
} else if (rocketComponent instanceof CenteringRing) { } else if (rocketComponent instanceof CenteringRing) {
@ -254,8 +255,8 @@ public abstract class FinSetConfig extends RocketComponentConfig {
} }
//Figure out position and length of the fin tab //Figure out position and length of the fin tab
if (!rings.isEmpty()) { if (!rings.isEmpty()) {
FinSet.TabRelativePosition temp = (FinSet.TabRelativePosition) em.getSelectedItem(); AxialMethod temp = (AxialMethod) em.getSelectedItem();
em.setSelectedItem(FinSet.TabRelativePosition.FRONT); em.setSelectedItem(AxialMethod.TOP);
double len = computeFinTabLength(rings, component.asPositionValue(AxialMethod.TOP), double len = computeFinTabLength(rings, component.asPositionValue(AxialMethod.TOP),
component.getLength(), mts, parent); component.getLength(), mts, parent);
mtl.setValue(len); mtl.setValue(len);
@ -506,10 +507,11 @@ public abstract class FinSetConfig extends RocketComponentConfig {
label.setToolTipText(trans.get("RocketCompCfg.lbl.ttip.componentmaterialaffects")); label.setToolTipText(trans.get("RocketCompCfg.lbl.ttip.componentmaterialaffects"));
filletPanel.add(label, "spanx 4, wrap rel"); filletPanel.add(label, "spanx 4, wrap rel");
JComboBox<?> combo = new JComboBox<>(new MaterialModel(filletPanel, component, Material.Type.BULK, "FilletMaterial")); JComboBox<Material> materialCombo = new JComboBox<Material>(new MaterialModel(filletPanel, component, Material.Type.BULK, "FilletMaterial"));
//// The component material affects the weight of the component. //// The component material affects the weight of the component.
combo.setToolTipText(trans.get("RocketCompCfg.combo.ttip.componentmaterialaffects")); materialCombo.setToolTipText(trans.get("RocketCompCfg.combo.ttip.componentmaterialaffects"));
filletPanel.add(combo, "spanx 4, growx, wrap paragraph"); filletPanel.add( materialCombo, "spanx 4, growx, wrap paragraph");
filletPanel.setToolTipText(tip); filletPanel.setToolTipText(tip);
return filletPanel; return filletPanel;
} }

View File

@ -8,11 +8,10 @@ import java.awt.event.MouseEvent;
import java.awt.geom.Point2D; import java.awt.geom.Point2D;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer; import java.io.Writer;
import java.util.List; import java.util.List;
@ -63,8 +62,9 @@ import net.sf.openrocket.startup.Application;
import net.sf.openrocket.unit.UnitGroup; import net.sf.openrocket.unit.UnitGroup;
import net.sf.openrocket.util.Coordinate; import net.sf.openrocket.util.Coordinate;
@SuppressWarnings("serial")
public class FreeformFinSetConfig extends FinSetConfig { public class FreeformFinSetConfig extends FinSetConfig {
private static final long serialVersionUID = 2504130276828826021L;
private static final Logger log = LoggerFactory.getLogger(FreeformFinSetConfig.class); private static final Logger log = LoggerFactory.getLogger(FreeformFinSetConfig.class);
private static final Translator trans = Application.getTranslator(); private static final Translator trans = Application.getTranslator();
@ -146,7 +146,7 @@ public class FreeformFinSetConfig extends FinSetConfig {
//// Position relative to: //// Position relative to:
panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.Posrelativeto"))); panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.Posrelativeto")));
JComboBox<AxialMethod> positionCombo = new JComboBox<AxialMethod>( new EnumModel<AxialMethod>(component, "AxialMethod", AxialMethod.axialOffsetMethods )); JComboBox<AxialMethod> positionCombo = new JComboBox<>( new EnumModel<>(component, "AxialMethod", AxialMethod.axialOffsetMethods ));
panel.add(positionCombo, "spanx 3, growx, wrap"); panel.add(positionCombo, "spanx 3, growx, wrap");
//// plus //// plus
panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.plus")), "right"); panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.plus")), "right");
@ -159,10 +159,7 @@ public class FreeformFinSetConfig extends FinSetConfig {
panel.add(new UnitSelector(m), "growx"); panel.add(new UnitSelector(m), "growx");
panel.add(new BasicSlider(m.getSliderModel(new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), new DoubleModel(component.getParent(), "Length"))), "w 100lp, wrap"); panel.add(new BasicSlider(m.getSliderModel(new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), new DoubleModel(component.getParent(), "Length"))), "w 100lp, wrap");
mainPanel.add(panel, "aligny 20%"); mainPanel.add(panel, "aligny 20%");
mainPanel.add(new JSeparator(SwingConstants.VERTICAL), "growy, height 150lp"); mainPanel.add(new JSeparator(SwingConstants.VERTICAL), "growy, height 150lp");
@ -170,12 +167,10 @@ public class FreeformFinSetConfig extends FinSetConfig {
panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", ""));
//// Cross section //// Cross section
//// Fin cross section: //// Fin cross section:
panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.FincrossSection")), "span, split"); panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.FincrossSection")), "span, split");
JComboBox<FinSet.CrossSection> sectionCombo = new JComboBox<FinSet.CrossSection>(new EnumModel<FinSet.CrossSection>(component, "CrossSection")); JComboBox<FinSet.CrossSection> sectionCombo = new JComboBox<>(new EnumModel<FinSet.CrossSection>(component, "CrossSection"));
panel.add(sectionCombo, "growx, wrap unrel"); panel.add(sectionCombo, "growx, wrap unrel");
@ -211,9 +206,7 @@ public class FreeformFinSetConfig extends FinSetConfig {
// Create the figure // Create the figure
figure = new FinPointFigure(finset); figure = new FinPointFigure(finset);
ScaleScrollPane figurePane = new FinPointScrollPane(); ScaleScrollPane figurePane = new FinPointScrollPane( figure);
figurePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
figurePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// Create the table // Create the table
tableModel = new FinPointTableModel(); tableModel = new FinPointTableModel();
@ -244,50 +237,16 @@ public class FreeformFinSetConfig extends FinSetConfig {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
log.info(Markers.USER_MARKER, "Export CSV free-form fin"); log.info(Markers.USER_MARKER, "Export CSV free-form fin");
JFileChooser c = new JFileChooser(); JFileChooser chooser = new JFileChooser();
// Demonstrate "Save" dialog: // Demonstrate "Save" dialog:
int rVal = c.showSaveDialog(FreeformFinSetConfig.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
File myFile = c.getSelectedFile();
Writer writer = null; if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(FreeformFinSetConfig.this)){
int nRow = table.getRowCount(); File selectedFile= chooser.getSelectedFile();
int nCol = table.getColumnCount();
try{
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(myFile.getAbsoluteFile()), "utf-8"));
//write the header information FreeformFinSetConfig.writeCSVFile(table, selectedFile);
StringBuffer bufferHeader = new StringBuffer(); }
for (int j = 0; j < nCol; j++) { }
bufferHeader.append(table.getColumnName(j)); });
if (j!=nCol) bufferHeader.append(", ");
}
writer.write(bufferHeader.toString() + "\r\n");
//write row information
for (int i = 0 ; i < nRow ; i++){
StringBuffer buffer = new StringBuffer();
for (int j = 0 ; j < nCol ; j++){
buffer.append(table.getValueAt(i,j));
if (j!=nCol) buffer.append(", ");
}
writer.write(buffer.toString() + "\r\n");
}
}finally {
writer.close();
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
panel.add(tablePane, "growy, width 100lp:100lp:, height 100lp:250lp:"); panel.add(tablePane, "growy, width 100lp:100lp:, height 100lp:250lp:");
panel.add(figurePane, "gap unrel, spanx, spany 3, growx, growy 1000, height 100lp:250lp:, wrap"); panel.add(figurePane, "gap unrel, spanx, spany 3, growx, growy 1000, height 100lp:250lp:, wrap");
@ -297,7 +256,8 @@ public class FreeformFinSetConfig extends FinSetConfig {
panel.add(scaleButton, "spany 2, alignx 50%, aligny 50%"); panel.add(scaleButton, "spany 2, alignx 50%, aligny 50%");
panel.add(exportCsvButton, "spany 2, alignx 50%, aligny 50%"); panel.add(exportCsvButton, "spany 2, alignx 50%, aligny 50%");
panel.add(new ScaleSelector(figurePane), "spany 2, aligny 50%"); ScaleSelector selector = new ScaleSelector(figurePane);
panel.add( selector, "spany 2, aligny 50%");
JButton importButton = new JButton(trans.get("CustomFinImport.button.label")); JButton importButton = new JButton(trans.get("CustomFinImport.button.label"));
importButton.addActionListener(new ActionListener() { importButton.addActionListener(new ActionListener() {
@ -314,36 +274,39 @@ public class FreeformFinSetConfig extends FinSetConfig {
return panel; return panel;
} }
public void writeCSVfile(JTable table, String filename) throws IOException{
Writer writer = null;
int nRow = table.getRowCount();
int nCol = table.getColumnCount();
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
//write the header information private static void writeCSVFile(JTable table, final File outputFile){
StringBuffer bufferHeader = new StringBuffer(); int nRow = table.getRowCount();
for (int j = 0; j < nCol; j++) { int nCol = table.getColumnCount();
bufferHeader.append(table.getColumnName(j));
if (j!=nCol) bufferHeader.append(", "); try {
} final Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "utf-8"));
writer.write(bufferHeader.toString() + "\r\n");
//write the header information
StringBuilder bufferHeader = new StringBuilder();
for (int j = 0; j < nCol; j++) {
bufferHeader.append(table.getColumnName(j));
bufferHeader.append(", ");
}
writer.write(bufferHeader.toString() + "\r\n");
//write row information
for (int i = 0; i < nRow; i++) {
StringBuilder buffer = new StringBuilder();
for (int j = 0; j < nCol; j++) {
buffer.append(table.getValueAt(i, j));
buffer.append(", ");
}
writer.write(buffer.toString() + "\r\n");
}
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//write row information
for (int i = 0 ; i < nRow ; i++){
StringBuffer buffer = new StringBuffer();
for (int j = 0 ; j < nCol ; j++){
buffer.append(table.getValueAt(i,j));
if (j!=nCol) buffer.append(", ");
}
writer.write(buffer.toString() + "\r\n");
}
} finally {
writer.close();
}
}
private void importImage() { private void importImage() {
JFileChooser chooser = new JFileChooser(); JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(FileHelper.getImageFileFilter()); chooser.setFileFilter(FileHelper.getImageFileFilter());
@ -361,7 +324,7 @@ public class FreeformFinSetConfig extends FinSetConfig {
CustomFinImporter importer = new CustomFinImporter(); CustomFinImporter importer = new CustomFinImporter();
List<Coordinate> points = importer.getPoints(chooser.getSelectedFile()); List<Coordinate> points = importer.getPoints(chooser.getSelectedFile());
document.startUndo(trans.get("CustomFinImport.undo")); document.startUndo(trans.get("CustomFinImport.undo"));
finset.setPoints(points); finset.setPoints( points);
} catch (IllegalFinPointException e) { } catch (IllegalFinPointException e) {
log.warn("Error storing fin points", e); log.warn("Error storing fin points", e);
JOptionPane.showMessageDialog(this, trans.get("CustomFinImport.error.badimage"), JOptionPane.showMessageDialog(this, trans.get("CustomFinImport.error.badimage"),
@ -386,22 +349,23 @@ public class FreeformFinSetConfig extends FinSetConfig {
tableModel.fireTableDataChanged(); tableModel.fireTableDataChanged();
} }
if (figure != null) { if (figure != null) {
figure.updateFigure(); figure.updateFigure();
} }
revalidate();
repaint();
} }
private class FinPointScrollPane extends ScaleScrollPane { private class FinPointScrollPane extends ScaleScrollPane {
private static final long serialVersionUID = 2232218393756983666L;
private static final int ANY_MASK = (MouseEvent.ALT_DOWN_MASK | MouseEvent.ALT_GRAPH_DOWN_MASK | MouseEvent.META_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK | MouseEvent.SHIFT_DOWN_MASK); private static final int ANY_MASK = (MouseEvent.ALT_DOWN_MASK | MouseEvent.ALT_GRAPH_DOWN_MASK | MouseEvent.META_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK | MouseEvent.SHIFT_DOWN_MASK);
private int dragIndex = -1; private int dragIndex = -1;
public FinPointScrollPane() { private FinPointScrollPane( final FinPointFigure _figure) {
super(figure, false); // Disallow fitting as it's buggy super( _figure, true);
} }
@Override @Override
@ -413,26 +377,30 @@ public class FreeformFinSetConfig extends FinSetConfig {
return; return;
} }
int index = getPoint(event); int pointIndex = getPoint(event);
if (index >= 0) { if ( pointIndex >= 0) {
dragIndex = index; dragIndex = pointIndex;
return; return;
} }
index = getSegment(event);
if (index >= 0) { int segmentIndex = getSegment(event);
if (segmentIndex >= 0) {
Point2D.Double point = getCoordinates(event); Point2D.Double point = getCoordinates(event);
finset.addPoint(index); finset.addPoint(segmentIndex );
try {
finset.setPoint(index, point.x, point.y);
} catch (IllegalFinPointException ignore) {
}
dragIndex = index;
try {
finset.setPoint(dragIndex, point.x, point.y);
} catch (IllegalFinPointException ignore) {
// no-op
}
dragIndex = segmentIndex;
updateFields();
return; return;
} }
super.mousePressed(event); super.mousePressed(event);
return;
} }
@ -444,12 +412,14 @@ public class FreeformFinSetConfig extends FinSetConfig {
return; return;
} }
Point2D.Double point = getCoordinates(event); Point2D.Double point = getCoordinates(event);
try { try {
finset.setPoint(dragIndex, point.x, point.y); finset.setPoint(dragIndex, point.x, point.y);
} catch (IllegalFinPointException ignore) { } catch (IllegalFinPointException ignore) {
log.debug("Ignoring IllegalFinPointException while dragging, dragIndex=" + dragIndex + " x=" + point.x + " y=" + point.y); log.debug("Ignoring IllegalFinPointException while dragging, dragIndex=" + dragIndex + " x=" + point.x + " y=" + point.y);
} }
updateFields();
} }
@ -507,28 +477,10 @@ public class FreeformFinSetConfig extends FinSetConfig {
return figure.convertPoint(x, y); return figure.convertPoint(x, y);
} }
} }
private enum Columns { private enum Columns {
// NUMBER {
// @Override
// public String toString() {
// return "#";
// }
// @Override
// public String getValue(FreeformFinSet finset, int row) {
// return "" + (row+1) + ".";
// }
// @Override
// public int getWidth() {
// return 10;
// }
// },
X { X {
@Override @Override
public String toString() { public String toString() {
@ -563,11 +515,6 @@ public class FreeformFinSetConfig extends FinSetConfig {
} }
private class FinPointTableModel extends AbstractTableModel { private class FinPointTableModel extends AbstractTableModel {
/**
*
*/
private static final long serialVersionUID = 4803736958177227852L;
@Override @Override
public int getColumnCount() { public int getColumnCount() {
@ -603,6 +550,7 @@ public class FreeformFinSetConfig extends FinSetConfig {
if (!(o instanceof String)) if (!(o instanceof String))
return; return;
// bounds check that indices are valid
if (rowIndex < 0 || rowIndex >= finset.getFinPoints().length || columnIndex < 0 || columnIndex >= Columns.values().length) { if (rowIndex < 0 || rowIndex >= finset.getFinPoints().length || columnIndex < 0 || columnIndex >= Columns.values().length) {
throw new IllegalArgumentException("Index out of bounds, row=" + rowIndex + " column=" + columnIndex + " fin point count=" + finset.getFinPoints().length); throw new IllegalArgumentException("Index out of bounds, row=" + rowIndex + " column=" + columnIndex + " fin point count=" + finset.getFinPoints().length);
} }
@ -612,15 +560,19 @@ public class FreeformFinSetConfig extends FinSetConfig {
double value = UnitGroup.UNITS_LENGTH.fromString(str); double value = UnitGroup.UNITS_LENGTH.fromString(str);
Coordinate c = finset.getFinPoints()[rowIndex]; Coordinate c = finset.getFinPoints()[rowIndex];
if (columnIndex == Columns.X.ordinal()) if (columnIndex == Columns.X.ordinal()){
c = c.setX(value); c = c.setX(value);
else }else{
c = c.setY(value); c = c.setY(value);
}
finset.setPoint(rowIndex, c.x, c.y); finset.setPoint(rowIndex, c.x, c.y);
updateFields();
} catch (NumberFormatException ignore) { } catch (NumberFormatException ignore) {
log.warn("ignoring NumberFormatException while editing a Freeform Fin");
} catch (IllegalFinPointException ignore) { } catch (IllegalFinPointException ignore) {
log.warn("ignoring IllegalFinPointException while editing a Freeform Fin");
} }
} }
} }