So I build a shell that looks like the following
After I click the change path button, I prompt for the path and then set the text. The problem is after doing so new text gets cut off if its too long like so.
I am using a Label to display the path, and the only method I'm using in the listener regarding the Laebl is the setText() method. Is there a way to not have this happen? I am using SWT and prefer to maintain the grid layout so I can have the 2 columns. Any info would be helpful. Thank you.
Here's the code
String unit[] = {"Pixil", "Inch"};
final CustomAttribute realWidth = new CustomAttribute(String.valueOf(obj.getGraph().getWidth(null)));
final CustomAttribute realHeight = new CustomAttribute(String.valueOf(obj.getGraph().getHeight(null)));
double[] sizes = obj.convertToSizes();
if(sizes != null){
realWidth.setValue(sizes[0]);
realHeight.setValue(sizes[1]);
}
final Shell shell = new Shell(d);
shell.setImage(ApplicationPlugin.getImage(ApplicationPlugin.QUATTRO_ICON));
shell.setLayout(new org.eclipse.swt.layout.GridLayout(2,true));
shell.setText(EDIT_IMG_WINDOW_TITLE);
//width info
final Label labelWidth = new Label(shell, SWT.HORIZONTAL);
final Text textWidth = new Text(shell,SWT.SINGLE | SWT.BORDER);
//height info
final Label labelHeight = new Label(shell, SWT.HORIZONTAL);
final Text textHeight = new Text(shell,SWT.SINGLE | SWT.BORDER);
//units info
final Combo unitCombo = new Combo (shell, SWT.READ_ONLY);
final Button ratioBox = new Button (shell, SWT.CHECK);
ratioBox.setText(EDIT_IMG_RADIO);
//path info
final Button pathButton = new Button (shell, SWT.PUSH);
pathButton.setText(EDIT_IMG_PATH);
final Label pathText = new Label(shell, SWT.HORIZONTAL);
pathText.setText(obj.getTextData()[0]);
Button change = new Button (shell, SWT.PUSH);
change.setText(EDIT_IMG_SAVE_BUTTON);
ModifyListener heightListener = new ModifyListener(){
public void modifyText(ModifyEvent e) {
if(realImgListen && textHeight.getText() != ""){
realImgListen = false;
try{
double oldHeight = realHeight.getDouble();
double newHeight = Double.parseDouble(textHeight.getText());
double oldWidth = Double.parseDouble(textWidth.getText());
if(unitCombo.getSelectionIndex() == 1){
newHeight = newHeight * designer.getPixilPerInch();
oldWidth = oldWidth * designer.getPixilPerInch();
}
realHeight.setValue(newHeight);
double[] sizes = obj.convertToSizes();
if(sizes != null)
realWidth.setValue(sizes[0]);
else
realWidth.setValue(oldWidth);
if(realHeight.getDouble() > SheetCanvas.sheetYSize)
realHeight.setValue(SheetCanvas.sheetYSize);
if(realHeight.getDouble() < 1)
realHeight.setValue(1);
if(ratioBox.getSelection() == true){
double scale = Double.parseDouble(realHeight.getValue()) / oldHeight;
realWidth.setValue(String.valueOf(realWidth.getDouble()*scale));
if(unitCombo.getSelectionIndex() == 0)
textWidth.setText(String.valueOf((int)Math.round(Double.parseDouble(realWidth.getValue()))));
else
textWidth.setText(String.valueOf(Double.parseDouble(realWidth.getValue())/designer.getPixilPerInch()));
}
obj.storeSizingInfo(realWidth.getDouble(), realHeight.getDouble(), 0);
realImgListen = true;
}
catch(NumberFormatException e2){
realImgListen = true;
}
}
}
};
ModifyListener widthListener = new ModifyListener(){
public void modifyText(ModifyEvent e) {
if(realImgListen && textHeight.getText() != ""){
realImgListen = false;
try{
double oldWidth = realWidth.getDouble();
double newWidth = Double.parseDouble(textWidth.getText());
double oldHeight = Double.parseDouble(textHeight.getText());
if(unitCombo.getSelectionIndex() == 1){
newWidth = newWidth * designer.getPixilPerInch();
oldHeight = oldHeight * designer.getPixilPerInch();
}
realWidth.setValue(newWidth);
double[] sizes = obj.convertToSizes();
if(sizes != null)
realHeight.setValue(sizes[1]);
else
realHeight.setValue(oldHeight);
if(realWidth.getDouble() > SheetCanvas.sheetYSize)
realWidth.setValue(SheetCanvas.sheetYSize);
if(realWidth.getDouble() < 1)
realWidth.setValue(1);
if(ratioBox.getSelection() == true){
double scale = Double.parseDouble(realWidth.getValue()) / oldWidth;
realHeight.setValue(String.valueOf(realHeight.getDouble()*scale));
if(unitCombo.getSelectionIndex() == 0)
textHeight.setText(String.valueOf((int)Math.round(Double.parseDouble(realHeight.getValue()))));
else
textHeight.setText(String.valueOf(Double.parseDouble(realHeight.getValue())/designer.getPixilPerInch()));
}
obj.storeSizingInfo(realWidth.getDouble(), realHeight.getDouble(), 0);
realImgListen = true;
}
catch(NumberFormatException e2){
realImgListen = true;
}
}
}
};
textHeight.addModifyListener(heightListener);
textWidth.addModifyListener(widthListener);
unitCombo.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
realImgListen = false;
if(unitCombo.getSelectionIndex() == 0){
textWidth.setText(String.valueOf((int)Math.rint(realWidth.getDouble())));
textHeight.setText(String.valueOf((int)Math.rint(realHeight.getDouble())));
}
else{
textWidth.setText(String.valueOf(realWidth.getDouble()/designer.getPixilPerInch()));
textHeight.setText(String.valueOf(realHeight.getDouble()/designer.getPixilPerInch()));
}
realImgListen = true;
}
});
change.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
Double width = realWidth.getDouble();
Double height = realHeight.getDouble();
String line1;
if(obj.getTextData() != null)
line1 = obj.getTextData()[0];
else
line1 = null;
String[] textData = {line1,null};
obj.setTextData(textData);
obj.storeSizingInfo(Math.rint(width), Math.rint(height),0);
designer.updateDataFromSource(settings);
designer.repaint();
updatePanelButtons();
shell.close();
}
});
pathButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//path button
String path = null;
path = getPathFromBrowser(FILE_CHOOSER_IMAGE_TITLE_STR,DEFAULT_PATH,acceptedImgFormats,null,SWT.OPEN);
pathText.setText(path);
if(path != null){
String[] paths = settings.getCustomImagePath();
int pathIndex = 0;
for(int i = 0; i < paths.length; i++){
if(obj.getTextData()[0].equals(paths[i]))
pathIndex = i;
}
paths[pathIndex] = path;
settings.setCustomImagePath(paths);
paths = settings.getCustomImageChoices();
paths[pathIndex] = getFileNameFromPath(path);
settings.setCustomImageChoices(paths);
designer.updateDataFromSource(settings);
String[] textData = obj.getTextData();
textData[0] = path;
if(textData.length > 1)
textData[1] = null;
obj.setTextData(textData);
}
}
});
textWidth.setTextLimit(7);
textHeight.setTextLimit(7);
labelWidth.setText(EDIT_IMG_WIDTH);
labelHeight.setText(EDIT_IMG_HEIGHT);
unitCombo.setItems(unit);
unitCombo.select(0);
ratioBox.setSelection(true);
org.eclipse.swt.graphics.Rectangle clientArea = shell.getClientArea();
unitCombo.setBounds(clientArea.x, clientArea.y, 300, 200);
shell.pack();
shell.open();
Shell shellTemp = SWT_AWT.new_Shell(d, designer);
Monitor primary = d.getPrimaryMonitor();
org.eclipse.swt.graphics.Rectangle bounds = primary.getBounds();
org.eclipse.swt.graphics.Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
shell.moveAbove(shellTemp);
shellTemp.dispose();
shell.addListener(SWT.Close, new Listener() {
#Override
public void handleEvent(Event event) {
editingImg();
}
});
realImgListen = false;
textWidth.setText(String.valueOf((int)Double.parseDouble(realWidth.getValue())));
textHeight.setText(String.valueOf((int)Double.parseDouble(realHeight.getValue())));
realImgListen = true;
The width of your columns is currently being set to the width of the widest control - probably 'Maintain Image Ratio'. If you set the the path text to anything longer than that it will be truncated.
You could set a width hint on the path control to set its size:
GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false);
data.widthHint = 100; // You choose the width
pathText.setLayoutData(data);
Note that you have specified that the columns are of equal width so this will add similar space to the first column. You might want to switch to unequal width columns.
Alternatively you can ask the Shell to recalculate the size after you set the new text. Just call:
shell.pack();
It looks like that you are redrawing the change path label components and you are not wrapping the label .
That why at the time of redrawing some part of the text is not visible.
Use warping or you can also increase the screen size
Related
Every time I try to run my file to display a graph it gets the majority of teh program done, up until to the GraphAtOrigin Class. This is where an error is thrown, saying the "IndexOutOfBoundsException: Index 0 out of bounds for length 0". So I believe there is something wrong with the wat I converted the domainList String ArrayList to the domainNumList Double ArrayListsome or a problem when I try to get the double array from the CreateGraphInterior Class. What do I need to do to prevent this exception and allow the code to run?
I have already tried casting the String ArrayList to a Double ArrayList with varies techniques, but if you have a better way let me know.
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class GraphProject {
public static JTextField depStart = new JTextField(10);
public static JTextField depEnd = new JTextField(10);
public static JTextField indStart = new JTextField(10);
public static JTextField indEnd = new JTextField(10);
public static JFrame main = new JFrame("Input The Graph Scale");
public static JButton submit = new JButton("Submit");
// for the input of Title, subtitle, and units
public static JFrame getInfo = new JFrame("Input The Graph Information");
public static JTextField gTitle = new JTextField(10);
public static JTextField gSubTitle = new JTextField(10);
public static JTextField depAxisUnit = new JTextField(10);
public static JTextField indAxisUnit = new JTextField(10);
public static JButton submitInfo = new JButton("Submit");
public static boolean selected = false;
public static boolean noSelected = false;
public static int dataLength;
public static double domainMax;
public static double rangeMax;
public static ArrayList<String> rangeList = new ArrayList<String>();
public static ArrayList<String> domainList = new ArrayList<String>();
public static void main(String[] args)throws Exception {
// Used to print out the data from the txt file
/*
ArrayList<String> result = new ArrayList<>();
FileReader fr = new FileReader("DataSetValues.txt");
int i;
while((i=fr.read()) != -1){
System.out.print((char)i);
}
*/
readData1();
readData2();
ObtainGraphInfo getGraphInfo = new ObtainGraphInfo();
getGraphInfo.graphInfo();
}
// Creates the Option Pane for user to input axis start and end positions
public static void axisPositions(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boolean yes = false;
boolean no = false;
JCheckBox startAtOrigin = new JCheckBox("Yes", yes);
startAtOrigin.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
selected = true;
makeGraph();
System.out.println("run the method to make the points graph at origin (0,0)");
main.dispose();
}
}
});
JCheckBox dontStartAtOrigin = new JCheckBox("No", no);
dontStartAtOrigin.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
noSelected = true;
makeGraph();
System.out.println("run the method to stop the points from graphing at the origin (0,0)");
main.dispose();
}
}
});
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
main.setContentPane(gui);
main.setLocationRelativeTo(null);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Do you want the points to begin graphing "));
controls.add(startAtOrigin);
labels.add(new JLabel(" with the origin (0,0)? "));
controls.add(dontStartAtOrigin);
/*labels.add(new JLabel("Independent Axis Start Position: "));
controls.add(indStart);
labels.add(new JLabel("Independent Axis End Position: "));
controls.add(indEnd);*/
// Codes for the action performed when the submit button is pressed
submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){
submit = (JButton)e.getSource();
main.dispose();
makeGraph();
}
});
gui.add(submit, BorderLayout.SOUTH);
main.getRootPane().setDefaultButton(submit);
main.pack();
submit.setVisible(false);
main.setVisible(true);
}
// Read the data from txt file and put it into an arrayList then separate into domain and range arrayLists
public static ArrayList<String> readData1() throws Exception{
ArrayList<String> dataList = new ArrayList<String>();
File file = new File("C://Users//wildc//Desktop//ToMac//Computer Science//Java Programs//GraphProjectFolder//testValues.txt");
Scanner scanData = new Scanner(file);
try{
while (scanData.hasNext()){
dataList.add(scanData.next());
}
int position = 0;
for (int counter = 0; counter < ((dataList.size()/2) + 1) ; counter ++ ) {
domainList.add(dataList.get(position));
position = (position + 2);
}
scanData.close();
//Creating domainList
} catch(Exception e) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran 1");
}
System.out.println(domainList.size() + " This is the Domain SIzeS");
System.out.println(domainList + "This is the domain List");
System.out.println(dataList + "This is the data list");
dataLength = domainList.size();
domainMax = Double.parseDouble(Collections.max(domainList));
System.out.println(domainMax + " : Domain max");
return domainList;
}
public static ArrayList<String> readData2() throws Exception{
ArrayList<String> dataList = new ArrayList<String>();
File file = new File("C://Users//wildc//Desktop//ToMac//Computer Science//Java Programs//GraphProjectFolder//testValues.txt");
Scanner scanData = new Scanner(file);
try{
while (scanData.hasNext()){
dataList.add(scanData.next());
}
scanData.close();
//Creating rangeList
int position = 1;
for (int counter = 0; counter < ((dataList.size()/2) + 1) ; counter ++ ) {
rangeList.add(dataList.get(position));
position = (position + 2);
}
// Was used to replace a certain element with another (incomplete)
}catch(Exception e) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran 2");
}
rangeMax = Double.parseDouble(Collections.max(rangeList));
System.out.println(rangeMax + " : Range max");
return rangeList;
}
//Displaying the frame for the graph to be on
public static void makeGraph(){
JFrame graph = new JFrame();
graph.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
graph.setSize(1000,1000);
graph.setTitle("Test Graph Scales");
graph.setLocationRelativeTo(null);
CreateGraphOutline graphFrame = new CreateGraphOutline();
CreateGraphInterior verticalLines = new CreateGraphInterior();
graph.add(graphFrame);
graph.setVisible(true);
graph.add(verticalLines);
graph.setVisible(true);
// TestFile testingAction = new TestFile();
//String[] testing = {"1","2","3"};
// testingAction.main(testing);
CreateGraphAttributes graphAttributes = new CreateGraphAttributes();
graph.add(graphAttributes);
GraphAtOrigin graphWithOriginStart = new GraphAtOrigin();
if (selected == true) {
graph.add(graphWithOriginStart);
graph.setVisible(true);
}
/*GraphNotAtOrigin graphNotWithOriginStart = new GraphAtOrigin();
if (noSelected == true) {
graph.add(graphNotWithOriginStart);
graph.setVisible(true);
}
makeGraph();
}*/
}}
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
import java.util.*;
public class CreateGraphAttributes extends JComponent{
public static String whereToStart;
public static String graphTitle;
public static String graphSubTitle;
public static String depUnit;
public static String indUnit;
public static String depTitle;
public static String indTitle;
public static FontMetrics metrics;
public void paintComponent(Graphics image) {
Graphics2D graph = (Graphics2D) image;
ObtainGraphInfo graphSpecifics = new ObtainGraphInfo();
ArrayList graphInformation = (ArrayList)graphSpecifics.setGraphAttributes();
graphTitle = graphInformation.get(0).toString();
graphSubTitle = graphInformation.get(1).toString();
depUnit = graphInformation.get(2).toString();
indUnit = graphInformation.get(3).toString();
depTitle = graphInformation.get(4).toString();
indTitle = graphInformation.get(5).toString();
// System.out.println(depAxisStartText + "," + indAxisStartText);
// title
Rectangle titleSpace = new Rectangle(200,50,600,200);
Font titleFont = new Font("Serif", Font.BOLD | Font.PLAIN, 22);
titleText(graph, graphTitle, titleSpace, titleFont);
// subtitle
Rectangle subTitleSpace = new Rectangle(200,100,600,150);
Font subTitleFont = new Font("Serif", Font.PLAIN, 14);
subTitleText(graph, graphSubTitle, subTitleSpace, subTitleFont);
// dependent axis 500, 700
Rectangle depTitleSpace = new Rectangle(200,600,550,150);
depAxisText(graph, depTitle, depUnit, depTitleSpace, subTitleFont);
// independent axis 10, 400
Rectangle indTitleSpace = new Rectangle(0,200,100,400);
indAxisText(graph, indTitle, indUnit, indTitleSpace, subTitleFont);
Point bottomLeftPoint = new Point(200,600);
Point bottomRightPoint = new Point(800,600); // 600px difference
Point leftBottomPoint = new Point(200,600);
Point leftTopPoint = new Point(200,200); // 400px difference
Point rightBottomPoint = new Point(800,600);
Point rightTopPoint = new Point(800,200);
Point topLeftPoint = new Point(200,200);
Point topRightPoint = new Point(800,200); // 600px difference
}
public void titleText(Graphics2D g, String text, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Draw the String
g.drawString(text, x, y);
}
public void subTitleText(Graphics2D g, String text, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Draw the String
g.drawString(text, x, y);
}
public void depAxisText(Graphics2D g, String text, String text2, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Create correct text structure
text = (text + " (" + text2 + ")");
// Draw the String
g.drawString(text, x, y);
}
public void indAxisText(Graphics2D g, String text, String text2, Rectangle rect, Font font) {
// Get the FontMetrics
metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Create correct text structure
text = (text + " (" + text2 + ")");
// Draw the String
g.drawString(text, x, y);
}
}
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
public class CreateGraphOutline extends JComponent{
public void paintComponent(Graphics image, boolean selected) {
Graphics2D graph = (Graphics2D) image;
Point bottomLeftPoint = new Point(200,600);
Point bottomRightPoint = new Point(800,600); // 600px difference
Line2D.Double depAxis = new Line2D.Double(bottomLeftPoint,bottomRightPoint);
BasicStroke lineThickness = new BasicStroke(4);
graph.setStroke(lineThickness);
graph.setColor(Color.BLACK);
graph.draw(depAxis);
Point leftBottomPoint = new Point(200,600);
Point leftTopPoint = new Point(200,200); // 400px difference
Line2D.Double indAxis = new Line2D.Double(leftBottomPoint,leftTopPoint);
graph.draw(indAxis);
Point rightBottomPoint = new Point(800,600);
Point rightTopPoint = new Point(800,200);
Line2D.Double rightIndAxis = new Line2D.Double(rightBottomPoint,rightTopPoint);
graph.draw(rightIndAxis);
Point topLeftPoint = new Point(200,200);
Point topRightPoint = new Point(800,200); // 600px difference
Line2D.Double topDepAxis = new Line2D.Double(topLeftPoint,topRightPoint);
graph.draw(topDepAxis);
}
}
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class ObtainGraphInfo {
public static JFrame getInfo = new JFrame("Input The Graph Information");
public static JTextField gTitle = new JTextField(10);
public static JTextField gSubTitle = new JTextField(10);
public static JTextField depAxisUnit = new JTextField(10);
public static JTextField indAxisUnit = new JTextField(10);
public static JTextField depAxisTitle = new JTextField(10);
public static JTextField indAxisTitle = new JTextField(10);
public static JButton submitInfo = new JButton("Submit");
public static GraphProject mainFile = new GraphProject();
public static ArrayList gAttributes;
public static void main(String[] args) {
}
// Prompt the user for the title, subtitle, and units of the Graph
public static void graphInfo(){
getInfo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
getInfo.setContentPane(gui);
getInfo.setLocationRelativeTo(null);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Graph Title: "));
controls.add(gTitle);
labels.add(new JLabel("Graph Sub-Title: "));
controls.add(gSubTitle);
labels.add(new JLabel("Dependent Axis Unit: "));
controls.add(depAxisUnit);
labels.add(new JLabel("Independent Axis Unit: "));
controls.add(indAxisUnit);
labels.add(new JLabel("Dependent Axis Title: "));
controls.add(depAxisTitle);
labels.add(new JLabel("Independent Axis Title: "));
controls.add(indAxisTitle);
// Codes for the action performed when the submit button is pressed
submitInfo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){
submitInfo = (JButton)e.getSource();
if (gTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (gSubTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
if (depAxisUnit.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
if (indAxisUnit.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (depAxisTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else {
if (indAxisTitle.getText().equals("")) {
Component alert = new JFrame();
JOptionPane.showMessageDialog(null, "Please make sure each field has an input", "Complete The Graph Information Fields!", JOptionPane.ERROR_MESSAGE);
} else{
String graphTitle = gTitle.getText();
String graphSubTitle = gSubTitle.getText();
String dependentAxisUnit = depAxisUnit.getText();
String independentAxisUnit = indAxisUnit.getText();
String dependentAxisTitle = depAxisTitle.getText();
String independentAxisTitle = indAxisTitle.getText();
ArrayList graphAttributes = new ArrayList<String>();
graphAttributes.add(graphTitle);
graphAttributes.add(graphSubTitle);
graphAttributes.add(dependentAxisUnit);
graphAttributes.add(independentAxisUnit);
graphAttributes.add(dependentAxisTitle);
graphAttributes.add(independentAxisTitle);
getInfo.dispose();
makeGraphAttributes(graphAttributes);
mainFile.axisPositions();
}
}
}
}
}
}}});
gui.add(submitInfo, BorderLayout.SOUTH);
getInfo.getRootPane().setDefaultButton(submitInfo);
getInfo.pack();
getInfo.setVisible(true);
}
public static void makeGraphAttributes(ArrayList<String> graphAttributes){
gAttributes = (ArrayList) graphAttributes.clone();
System.out.println(gAttributes);
setGraphAttributes();
}
public static ArrayList<String> setGraphAttributes(){
return gAttributes;
}
}
// This is the Text File Used
0.281 0.0487
0.396 0.727
0.522 0.974
0.639 0.121
0.774 0.145
// This class creates the Double ArrayList
public class CreateGraphInterior extends JComponent{
public static ArrayList<Double> domainNumList = new ArrayList<Double>();
public static ArrayList<Double> rangeNumList = new ArrayList<Double>();
public static ArrayList<String> domainList = new ArrayList<String>();
public static ArrayList<String> rangeList = new ArrayList<String>();
public static GraphProject main = new GraphProject(); // this is where the original domainList and rangeList are found
public static int dataSize;
public static double domMax;
public static double ranMax;
public void paintComponent(Graphics image) {
main.dataLength = dataSize;
main.domainMax = domMax;
main.rangeMax = ranMax;
makeLists();
Graphics2D graph = (Graphics2D) image;
int domAxisPos = 200;
for (int counter = 0; counter < 9; counter++ ) {
Point topPoint = new Point(domAxisPos,200);
Point bottomPoint = new Point(domAxisPos,620);
Line2D.Double verticalLines = new Line2D.Double(bottomPoint,topPoint);
BasicStroke lineThickness = new BasicStroke(2);
graph.setStroke(lineThickness);
graph.setColor(Color.BLACK);
graph.draw(verticalLines);
domAxisPos = domAxisPos + 75;
}
int ranAxisPos = 600;
for (int counter = 0; counter < 9; counter++ ) {
Point leftPoint = new Point(180,ranAxisPos);
Point rightPoint = new Point(800,ranAxisPos);
Line2D.Double horizontalLines = new Line2D.Double(leftPoint,rightPoint);
BasicStroke lineThickness = new BasicStroke(2);
graph.setStroke(lineThickness);
graph.setColor(Color.GRAY);
graph.draw(horizontalLines);
ranAxisPos = ranAxisPos - 50;
}
if (main.selected == true) {
GraphAtOrigin graphWithOrigin = new GraphAtOrigin();
}
if (main.noSelected == true) {
System.out.println("Its false");
ranAxisPos = 600;
double domLabel = 0;
for (int counter = 0; counter < 9; counter++ ) {
graph.drawString(Double.toString(domLabel), domAxisPos, 650);
domLabel = domLabel + 2.0;
domAxisPos = domAxisPos - 50;
}
}
}
public static void makeLists(){
try{
domainList = main.readData1();
System.out.println(domainList + " This is domain list");
rangeList = main.readData2();
System.out.println(rangeList + " This is range list");
int count = 0;
for (int counter = 0; counter < (main.dataLength + 1) ; counter++) {
try {
//Convert String to Double, and store it into Double array list.
String domNumber = domainList.get(count);
double domNumber2 = Double.parseDouble(domNumber);
String ranNumber = rangeList.get(count);
double ranNumber2 = Double.parseDouble(ranNumber);
domainNumList.add(domNumber2);
rangeNumList.add(ranNumber2);
count = count + 1;
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
System.out.println("This error ran");
}
}}catch(Exception e){
System.out.println("Error arose");
}
}
}
// This is where I try to use the Double ArrayList
public class GraphAtOrigin extends JComponent{
public static GraphProject main = new GraphProject();
public static CreateGraphInterior graphInterior = new CreateGraphInterior();
// make regular unit into pixel unit
public static double oneDomPX = (domMax / 600);
public static double oneRanPX = (ranMax / 400);
public static ArrayList<Double> domainNumList = new ArrayList<Double>();;
public static ArrayList<Double> rangeNumList = new ArrayList<Double>();;
public static void plotPoints(){
domainNumList = graphInterior.domainNumList; // error occurs here
rangeNumList = graphInterior.rangeNumList;
int domPointPos = 0;
int ranPointPos = 0;
for (int counter = 0; counter < (main.dataLength + 1); counter++) {
// X data point
double domNum = domainNumList.get(domPointPos);
//A what to add to 200
double domAdd = domNum / oneDomPX;
// newX make the point relavent to the graphs location
double domPoint = domAdd + 200;
// make domPoint integer to be used on point method
int newDomPoint = (int)domPoint;
// subtract half the thickness of point to make it graph at the points center
newDomPoint = newDomPoint - 3;
// X data point
double ranNum = graphInterior.rangeNumList.get(ranPointPos);
//A what to add to 200
double ranAdd = ranNum / oneRanPX;
// newX make the point relavent to the graphs location
double ranPoint = 600 - ranAdd;
// make domPoint integer to be used on point method
int newRanPoint = (int)ranPoint;
// subtract half the thickness of point to make it graph at the points center
newRanPoint = newRanPoint - 3;
graph.fillOval(newDomPoint,newRanPoint,6,6);
domPointPos++;
ranPointPos++;
}
}
}
The output should then allow the for loops to execute and draw data points, but the exception is thrown and the program doesn't complete.
I suspect the problem is at:
for (int counter = 0; counter < (main.dataLength + 1) ; counter++) {
If the dataLength is 0 then this will run once and perform a get(0) which will throw the exception you have shown.
However if all you want to do is to convert a list of strings to a list of doubles, then you could use:
domainList.stream().map(Double::valueOf).collect(Collectors.toList());
If you wish to quietly skip invalid strings then there is a long explanation of the regexp to use in the javadoc for Double. A simple version might be:
Pattern doublePattern = Pattern.compile("\\d+(\\.\\d+)?");
List<Double> result = domainList.stream()
.filter(doublePattern::matches).map(Double::valueOf)
.collect(Collectors.toList());
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
my progress bar is update only to 100%. i check with printing and it's seems everything run as it should be but the UI does not update according to the parameters in the printing check!
here is my Panel class. the main class create frame the adding the MyPanel i create:
public class MyPanel extends JPanel {
File[] DFLIST;
File DF[];
File INP;
File LOG;
JButton chooseDF = new JButton("Choose defect file");
JButton chooseLog = new JButton("Choose log file");
JButton chooseInp = new JButton("Choose inp file");
JButton analayze = new JButton("Analayze");
DefectFileReader[] dfReader;
Document[] docArray;
boolean DFloaded = false;
boolean LOGloaded = false;
boolean INPloaded = false;
Checkbox recipeName;
Checkbox inspectionDuration;
Checkbox area;
Checkbox numberOfDefects;
Checkbox numberOfDefectsPerDetector;
Checkbox sensetivityName;
Checkbox SlicesDetected;
private static int rowIndex = 2;
private static int cellIndex = 4;
FileOutputStream fos;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("analyze_result");
Row row = sheet.createRow(rowIndex);
Cell cell = row.createCell(cellIndex);
XSSFCellStyle csForFirstWrite = workbook.createCellStyle();
XSSFCellStyle csForSecondWrite = workbook.createCellStyle();
XSSFFont fontForBold = workbook.createFont();
XSSFFont fontNotForBold = workbook.createFont();
String totalDuration = "00:00:00";
private int currentFolder = 0;
//TwoRoot t;
JProgressBar pBar = new JProgressBar();
Frame frame = new Frame("Progress Bar");
MyprogressBar taskBar;
/* creating the main panel of the frame - divided to 3 parts. in the north pictures , in the west checkbox , in the east the file chooser */
public MyPanel(){
this.setLayout(new BorderLayout());
this.add(pictureInNorth() , BorderLayout.NORTH);
this.add(checkBoxPanel() , BorderLayout.WEST);
this.add(chooseFilesPanel() , BorderLayout.EAST);
//pBar.setForeground(Color.black);
//pBar.setStringPainted(true);
//this.add(pBar , BorderLayout.SOUTH);
}
/* creating the north panel with the picture */
private JPanel pictureInNorth(){
JPanel toReturn = new JPanel();
toReturn.setBackground(Color.black);
JButton analayzerPic = new JButton(new ImageIcon(new ImageIcon("C:/Users/uvalerx073037/workspace/Analayzer_GUI_Ver2/src/Images/vXqyQkOv.jpeg")
.getImage().getScaledInstance(600, 30,
java.awt.Image.SCALE_SMOOTH)));
analayzerPic.setBackground(Color.black);
toReturn.add(analayzerPic);
return toReturn;
}
/* creating the checkBox in the west */
private JPanel checkBoxPanel(){
recipeName = new Checkbox("Recipe Name" , false);
inspectionDuration = new Checkbox("Inspection Duration" , false);
area = new Checkbox("Area" , false);
numberOfDefects = new Checkbox("Number Of Defects" , false);
numberOfDefectsPerDetector = new Checkbox("Number Of Defects Per Detector", false);
sensetivityName = new Checkbox("Sensetivity Name", false);
SlicesDetected = new Checkbox("Slices were detected" , false);
JPanel toReturn = new JPanel();
toReturn.setLayout(new BoxLayout(toReturn, BoxLayout.Y_AXIS));
toReturn.add(recipeName);
toReturn.add(inspectionDuration);
toReturn.add(numberOfDefects);
toReturn.add(numberOfDefectsPerDetector);
toReturn.add(sensetivityName);
toReturn.add(SlicesDetected);
toReturn.add(area);
return toReturn;
}
/*creating the file chooser in the east */
private Box chooseFilesPanel(){
MyActionListener lis = new MyActionListener();
chooseDF.addActionListener(lis);
chooseInp.addActionListener(lis);
chooseLog.addActionListener(lis);
analayze.addActionListener(lis);
analayze.setForeground(Color.BLUE);
Box toReturn = Box.createVerticalBox();
toReturn.add(Box.createGlue());
toReturn.add(chooseDF);
toReturn.add(Box.createGlue());
toReturn.add(chooseLog);
toReturn.add(Box.createGlue());
toReturn.add(chooseInp);
toReturn.add(Box.createGlue());
toReturn.add(analayze).setSize(50,50);
return toReturn;
}
/* function to check after the user clicked on the analyze button if all the conditions are OK */
public Boolean isValidToStart(){
if(DFloaded == false && LOGloaded == false && INPloaded == false){
JOptionPane.showMessageDialog(null, "NO FILE WAS LOADED!!!", "User Error" , JOptionPane.ERROR_MESSAGE);
return false;
}
if(recipeName.getState() == false && inspectionDuration.getState() == false && area.getState() == false &&
numberOfDefects.getState() == false && numberOfDefectsPerDetector.getState() == false && sensetivityName.getState() == false){
JOptionPane.showMessageDialog(null , "NO CHECK BOX WAS MARKED!!!" + "\n" + "WHAT DATA WOULD YOU LIKE TO COLLECT?" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
if(area.getState() == true && (LOGloaded == false || DFloaded == false || INPloaded == false)){
JOptionPane.showMessageDialog(null , "IF YOU WANT TO COLLECT AERA YOU NEED TO CHOOSE INP + LOG + DEF" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
if(SlicesDetected.getState() == true && LOGloaded == false){
JOptionPane.showMessageDialog(null , "You need to load the LOG in order to get the amount of slices were detected!" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
else
return true;
}
/* build the row of the titles , only what the user marked in the check box */
private void firstWriteToExcel(DefectFileReader curDF , XSSFSheet sheet , XSSFWorkbook workbook , FileOutputStream fos) throws Exception{
fontForBold.setBold(true);
csForFirstWrite.setFont(fontForBold);
csForFirstWrite.setFillForegroundColor(new XSSFColor(java.awt.Color.lightGray));
csForFirstWrite.setFillPattern(CellStyle.SOLID_FOREGROUND);
csForFirstWrite.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
if(recipeName.getState() == true){
row = sheet.createRow(rowIndex - 1);
row.createCell(cellIndex).setCellValue("Recipe Name: " + curDF.getRecipeName());
sheet.autoSizeColumn(cellIndex);
}
row = sheet.createRow(rowIndex++);
row.createCell(cellIndex).setCellValue("inspection index");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
if(numberOfDefects.getState() == true){
row.createCell(cellIndex).setCellValue("Total Defects");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(numberOfDefectsPerDetector.getState() == true){
ArrayList<String> toOtherFunc = new ArrayList<String>();
toOtherFunc = curDF.getDetectorNames();
for(int i=0; i < toOtherFunc.size() ; i++){
row.createCell(cellIndex).setCellValue(toOtherFunc.get(i));
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
}
if(sensetivityName.getState() == true){
row.createCell(cellIndex).setCellValue("sensetivity Name");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(LOGloaded == true){
row.createCell(cellIndex).setCellValue("Slices were detected");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(inspectionDuration.getState()==true){
row.createCell(cellIndex).setCellValue("Inspection Duration");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
for (Row row : sheet){
for (Cell cell_local : row){
cell_local.setCellStyle(csForFirstWrite);
}
}
System.out.println("row index is: " + rowIndex + "cell index is: " + cellIndex);
}
/* fill the excel in the data were collected */
private void writeToExcel(DefectFileReader curDF , XSSFSheet sheet , XSSFWorkbook workbook , FileOutputStream fos) throws Exception{
fontNotForBold.setBold(false);
csForSecondWrite.setFont(fontNotForBold);
csForSecondWrite.setFillForegroundColor(new XSSFColor(java.awt.Color.white));
csForSecondWrite.setFillPattern(CellStyle.SOLID_FOREGROUND);
csForSecondWrite.setBorderBottom(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderTop(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderRight(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellIndex = 4;
row = sheet.createRow(rowIndex++);
row.createCell(cellIndex++).setCellValue("inspection_" + (rowIndex - 3));
if(numberOfDefects.getState() == true)
row.createCell(cellIndex++).setCellValue(curDF.getTotalDefects());
if(numberOfDefectsPerDetector.getState() == true){
ArrayList<String> toOtherFunc = new ArrayList<String>();
int[] toPrintNumber = new int[toOtherFunc.size()];
toOtherFunc = curDF.getDetectorNames();
System.out.println(toOtherFunc);
toPrintNumber = curDF.getDefectPerDetector(toOtherFunc);
for(int i=0; i < toOtherFunc.size() ; i++)
row.createCell(cellIndex++).setCellValue(toPrintNumber[i]);
}
if(sensetivityName.getState() == true)
row.createCell(cellIndex++).setCellValue(curDF.getSensetivityName());
if(LOGloaded == true){
LogFileReader logReader = new LogFileReader(LOG , curDF.getInspectionEndTime());
ArrayList<String> toLog = curDF.getRunsIndex();
String toPrint = "";
for(int i=0 ; i < toLog.size() ; i = i+2)
toPrint += toLog.get(i) + ": " + logReader.diagnozeLog(toLog.get(i+1)) + " ";
if(toPrint.equals(""))
row.createCell(cellIndex).setCellValue("The data of this run is not in this log!");
else
row.createCell(cellIndex).setCellValue(toPrint);
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(inspectionDuration.getState()==true)
row.createCell(cellIndex++).setCellValue(curDF.inspectionDuration());
for (Row row : sheet){
if( row.getRowNum() > 2){
for (Cell cell_local : row){
cell_local.setCellStyle(csForSecondWrite);
}
}
}
System.out.println("row index is: " + rowIndex + " cell index is: " + cellIndex);
}
/* adding the inspection time of the current run to the total time */
public String sumTimes(String time1) {
PeriodFormatter formatter = new PeriodFormatterBuilder()
.minimumPrintedDigits(2)
.printZeroAlways()
.appendHours()
.appendLiteral(":")
.appendMinutes()
.appendLiteral(":")
.appendSeconds()
.toFormatter();
org.joda.time.Period period1 = formatter.parsePeriod(time1);
org.joda.time.Period period2 = formatter.parsePeriod(totalDuration);
return formatter.print(period2.plus(period1).normalizedStandard());
}
public void initializeFrame(){
frame.setSize(300, 100);
pBar.setForeground(Color.black);
pBar.setStringPainted(true);
frame.add(pBar);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MyprogressBar extends SwingWorker<Void, Integer> {
JProgressBar pBar;
int max;
int currentFolder;
public MyprogressBar(JProgressBar curBar , int max , int currentFolder){
this.pBar = curBar;
this.max = max;
this.currentFolder = currentFolder;
}
public void done(){
}
#Override
protected Void doInBackground() throws Exception {
System.out.println("i'm in background");
double i = currentFolder;
double t = DFLIST.length;
double toSetInDouble = (i/t);
int toSet = (int) (toSetInDouble * 100);
pBar.setValue(toSet);
System.out.println(toSet);
repaint();
Thread.sleep(10);
publish(toSet);
return null;
}
}
/* adding listener to all of the buttons and check boxes */
public class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
if(click.getSource() == chooseDF){
File directory;
FilenameFilter f = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.length()<=2;
}
};
FilenameFilter def = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".def");
}
};
JFileChooser chooser = new JFileChooser(System.getProperties().getProperty("user.dir"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
DFloaded = true;
directory = chooser.getSelectedFile();
File[] fileList = directory.listFiles(f);
Arrays.sort(fileList , new NaturalOrderComparator());
DFLIST = new File[fileList.length];
for(int i = 0 ; i<fileList.length ; i++){
File[] tmp = fileList[i].listFiles(def);
for(int j=0 ; j<tmp.length ; j++)
DFLIST[i] = tmp[j];
}
}
}
if(click.getSource() == chooseInp){
JFileChooser fc2 = new JFileChooser();
if (fc2.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
INPloaded = true;
INP = fc2.getSelectedFile();
}
}
if(click.getSource() == chooseLog){
JFileChooser fc3 = new JFileChooser();
if(fc3.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
LOGloaded = true;
LOG = fc3.getSelectedFile();
}
}
if(click.getSource() == analayze){
Boolean valid = isValidToStart();
if(valid == true){
try{
fos = new FileOutputStream("c:/temp/analayze.xlsx");
if(DFloaded == true){
try {
initializeFrame();
DF = new File[DFLIST.length];
dfReader = new DefectFileReader[DFLIST.length];
docArray = new Document[DFLIST.length];
for( ; currentFolder < DFLIST.length ; currentFolder++){
new MyprogressBar(pBar, 100, currentFolder + 1).execute();
frame.repaint();
System.out.println("i'm sending the file down here to parse from file to document");
System.out.println(DFLIST[currentFolder].getAbsoluteFile());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
docArray[currentFolder] = (Document) db.parse(DFLIST[currentFolder]);
docArray[currentFolder].getDocumentElement().normalize();
dfReader[currentFolder] = new DefectFileReader(DFLIST[currentFolder] , docArray[currentFolder]);
dfReader[currentFolder].getRunsIndex();
totalDuration = sumTimes(dfReader[currentFolder].inspectionDuration());
if(currentFolder==0){
firstWriteToExcel(dfReader[0], sheet, workbook, fos);
writeToExcel(dfReader[0], sheet, workbook, fos);
}
if(currentFolder!=0)
writeToExcel(dfReader[currentFolder] , sheet , workbook , fos );
repaint();
if(INPloaded == true){
}
DFLIST[currentFolder] = null;
dfReader[currentFolder].clearDfReader();
docArray[currentFolder] = null;
System.gc();
}
}
catch(Exception e ) {
System.out.println(e);
System.exit(0);
}
}
row = sheet.createRow(rowIndex);
totalDuration = sumTimes("00:00:00");
if(inspectionDuration.getState() == true){
row.createCell(cellIndex - 1).setCellValue(totalDuration);
row.getCell(cellIndex - 1).setCellStyle(csForFirstWrite);
}
((Workbook) workbook).write(fos);
workbook.close();
JOptionPane.showMessageDialog(null, "Your data has been analyze!\n you can find the result in c:\\temp");
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
#Udi it would have been really great if you could have pasted a structured code. However, with whatever code you pasted, here is an indicative solution using swingworker. You just need to call your whole actionPerformed() code from doInBackground() of swingworker. Hope it helps.
Moreover, I find the java docs of swingworker a very useful to understand how it works. Examples are very simple yet well explained.
https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html
// use this code inside actionPerformed()
new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
// all your code goes here
for( ; currentFolder < DFLIST.length ; currentFolder++){
double f = currentFolder + 1;
double t = DFLIST.length;
double currentPercentInDouble = (f / t);
int currentPercent = (int) (currentPercentInDouble * 100);
// send the current progress to progress bar. This needs to be updated to progress bar in process() method
publish(currentPercent)
}
// rest of the code
}
#Override
protected void process(List<V> chunks) {
// update the progress bar here
}
}.execute();
I am trying to highlight Java syntax using StyleRanges in SWT StyledText boxes. Here is the relevant code.
String code = text.getText();
int fromIndex = 0;
String keyword = "public";
if(code.toLowerCase().contains(keyword.toLowerCase())){
System.out.println("Match found");
Shell shell = text.getShell();
Display display = shell.getDisplay();
System.out.println("Got shell and display...");
Color orange = new Color(display, 255, 127, 0);
int index = code.indexOf(keyword, fromIndex);
int length = keyword.length();
StyleRange styleRange = new StyleRange(0, 22, orange, null,SWT.BOLD);
text.setStyleRange(styleRange);
System.out.println("colored...");
fromIndex = index;
}
but the StyleRanges do nothing? Can someone help me out with this?
Edit: If i use this new code
`private void Color_Code(StyledText text) {
Shell shell = this.getShell();
Display display = shell.getDisplay();
String[] lines = text.getText().split("\\n");
String keyWord = "public";
Color red = display.getSystemColor(SWT.COLOR_RED);
int offset = 0;
for (String line : lines)
{
int index = line.indexOf(keyWord);
if (index != -1)
{
StyleRange range = new StyleRange(index + offset, keyWord.length(), red, null, SWT.BOLD);
text.setStyleRange(range);
}
offset += line.length() + 1; // +1 for the newline character
}
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}`
Tree population code: private void Populate_Method_Tree(Tree tree) {
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.MCCCLONES.size(); i++) {
int id = SampleHandler.f.MCCCLONES.get(i).getMCCID();
TreeItem temp = new TreeItem(tree, SWT.V_SCROLL);
temp.setText("MCCID: " + id);
Populate_Drop_Down(id);
}
}
Dropdown Population code:
protected void Populate_Drop_Down(int id) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.MCCCLONES.size(); i++) {
if (id == SampleHandler.f.MCCCLONES.get(i).getMCCID()) {
ArrayList<String> Method_Names = new ArrayList<>();
for (int j = 0; j < SampleHandler.f.MCCCLONES.get(i)
.getMethod_Clones().size(); j++) {
String name = SampleHandler.f.MCCCLONES.get(i)
.getMethod_Clones().get(j).getMethod()
.getFileName();
String[] parts = name.split("[\\\\ .]");
Method_Names.add(parts[parts.length - 2]
+ " "
+ Integer
.toString(SampleHandler.f.MCCCLONES
.get(i).getMethod_Clones()
.get(j).getMethod()
.getMethodID()));
}
String[] Methds = new String[Method_Names.size()];
Methds = Method_Names.toArray(Methds);
combo.setItems(Methds);
combo.setText(Methds[0]);
String[] parts = Methds[0].split("[\\s+]");
int MID = Integer.parseInt(parts[1]);
Fill_Code(MID);
}
}
}
Textbox filling code:
private void Fill_Code(int MID) {
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.METHODS.size(); i++) {
if (SampleHandler.f.METHODS.get(i).getMethodID() == MID) {
text.setText(SampleHandler.f.METHODS.get(i).getCode());
//Color_Code(text);
}
}
}
it highlight the word public in my first instance but stops populating my dropdown menu and tree.
There has to be something wrong with your other code. Everything works just fine here.
Here is an example:
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
StyledText text = new StyledText(shell, SWT.BORDER | SWT.MULTI | SWT.WRAP);
text.setText("public class Text\n{\n public static void main(String[] args)\n {\n System.out.println(\"Text\");\n }\n}");
String[] lines = text.getText().split("\\n");
String keyWord = "public";
Color red = display.getSystemColor(SWT.COLOR_RED);
int offset = 0;
for (String line : lines)
{
int index = line.indexOf(keyWord);
if (index != -1)
{
StyleRange range = new StyleRange(index + offset, keyWord.length(), red, null, SWT.BOLD);
text.setStyleRange(range);
}
offset += line.length() + 1; // +1 for the newline character
}
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
Looks like this:
I have a table with 4 columns. I try to integrate a ToolTip for all cells of the third column.
With my Code the ToolTip only appears for the cells of the first column.
This is my Code:
protected void checkAction() throws Exception {
System.out.println("Start Test");
//Erstellen einer neuen Shell
final Shell shell = new Shell();
shell.setSize(280, 300);
shell.setText("Testtabelle");
//Erstellen einer neuen Tabelle
final Table table = new Table(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
table.setLinesVisible(true);
table.setHeaderVisible(true);
//Einlesen der Überschriften und Vergabe der Namen
String[] titles = {"Element", "Stage", "Type", "Generate-User", "Change-User" };
for (int i = 0; i < titles.length; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(titles[i]);
}
// Inhalte hinzufügen
final int count = 4;
for (int i = 0; i < count; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, "Test "+i);
item.setText(1, ""+(i+1));
item.setText(2, "Testtype");
item.setText(3, "562910");
item.setText(4, "423424");
}
// Disable native tooltip
table.setToolTipText ("");
// Implement a "fake" tooltip
final Listener labelListener = new Listener () {
public void handleEvent (Event event) {
Label label = (Label)event.widget;
Shell shell = label.getShell ();
switch (event.type) {
case SWT.MouseDown:
Event e = new Event ();
e.item = (TableItem) label.getData ("_TABLEITEM");
// Assuming table is single select, set the selection as if
// the mouse down event went through to the table
table.setSelection (new TableItem [] {(TableItem) e.item});
table.notifyListeners (SWT.Selection, e);
shell.dispose ();
table.setFocus();
break;
case SWT.MouseExit:
shell.dispose ();
break;
}
}
};
Listener tableListener = new Listener () {
Shell tip = null;
Label label = null;
public void handleEvent (Event event) {
switch (event.type) {
case SWT.Dispose:
case SWT.KeyDown:
case SWT.MouseMove: {
if (tip == null) break;
tip.dispose ();
tip = null;
label = null;
break;
}
case SWT.MouseHover: {
TableItem item = table.getItem (new Point (event.x, event.y));
if (item != null) {
if (tip != null && !tip.isDisposed ()) tip.dispose ();
tip = new Shell (shell, SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL);
FillLayout layout = new FillLayout ();
layout.marginWidth = 2;
tip.setLayout (layout);
label = new Label (tip, SWT.NONE);
label.setData ("_TABLEITEM", item);
if (item.getText().equals("Test 3")){
label.setText ("Jonas Intfeld");
}
else{
label.setText (item.getText ());
}
label.addListener (SWT.MouseExit, labelListener);
label.addListener (SWT.MouseDown, labelListener);
Point size = tip.computeSize (SWT.DEFAULT, SWT.DEFAULT);
Rectangle rect = item.getBounds (0);
Point pt = table.toDisplay (rect.x, rect.y);
tip.setBounds (pt.x, pt.y, size.x, size.y);
tip.setVisible (true);
}
}
}
}
};
table.addListener (SWT.Dispose, tableListener);
table.addListener (SWT.KeyDown, tableListener);
table.addListener (SWT.MouseMove, tableListener);
table.addListener (SWT.MouseHover, tableListener);
// Tabelle und Shell Packen
for (int i = 0; i < titles.length; i++) {
table.getColumn(i).pack();
}
table.setSize(table.computeSize(SWT.DEFAULT, 200));
shell.pack();
// Shell öffnen
try { shell.open();
} catch (SWTException e) {
System.out.println("Test: "+e);
shell.close();
}
}
Is there any way to activate the Tooltip for the 3. Column ?
At the moment when I move over the cells in the 3. column the Tooltip appears for the 1. column.
Maybe the best option is to search the column by title?
Your problem is this line:
Rectangle rect = item.getBounds(0);
You are asking for the bounds of the first column. Just change the index to the column where you want your tooltip to appear and you'll be fine:
Rectangle rect = item.getBounds(2);
If you need to get the column index from the mouse position, use this code:
Point point = new Point(event.x, event.y);
int column = 0;
for (int i = 0; i < table.getColumnCount(); i++)
{
if (item.getBounds(i).contains(point))
{
column = i;
break;
}
}
Rectangle rect = item.getBounds(column);
I am to stimulate a java applet of a menu with checkboxes and checkboxgroups, with calories listed next to each food choice. My problem is I cannot figure out why I keep getting this error message when i compile it:
AnAppletWithCheckboxes.java:188: illegal forward reference
int crepeVal = Integer.parseInt(textField.getText());
I get that for every line that I have is converting the textField into an int, so hence there are 17 errors. Any idea of why will be appreciated!
Here is my Code:: it is very long because there are plenty checkboxes and textFields. I commented Out My place of Error! :
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AnAppletWithCheckboxes extends Applet implements ItemListener {
public void init() {
setLayout(new GridLayout(1, 0));
CheckboxGroup dinnerType = new CheckboxGroup();
standard = new Checkbox("standard", dinnerType, false);
standard.addItemListener(this);
deluxe = new Checkbox("deluxe", dinnerType, true);
deluxe.addItemListener(this);
CheckboxGroup appetizers = new CheckboxGroup();
crepe = new Checkbox("crepe", appetizers, false);
crepe.addItemListener(this);
quiche = new Checkbox("quiche", appetizers, false);
quiche.addItemListener(this);
dumpling = new Checkbox("dumpling", appetizers, false);
dumpling.addItemListener(this);
textField = new TextField("300");
textField.setEditable(false);
textField2 = new TextField("330");
textField2.setEditable(false);
textField3 = new TextField("98");
textField3.setEditable(false);
CheckboxGroup soupOrSalad = new CheckboxGroup();
soup = new Checkbox("Soup", soupOrSalad, false);
soup.addItemListener(this);
CheckboxGroup soups = new CheckboxGroup();
cream = new Checkbox("cream", soups, false);
cream.addItemListener(this);
broth = new Checkbox("broth", soups, false);
broth.addItemListener(this);
gumbo = new Checkbox("gumbo", soups, false);
gumbo.addItemListener(this);
textField4 = new TextField("190");
textField4.setEditable(false);
textField5 = new TextField("20");
textField5.setEditable(false);
textField6 = new TextField("110");
textField6.setEditable(false);
salad = new Checkbox("Salad", soupOrSalad, false);
salad.addItemListener(this);
CheckboxGroup salads = new CheckboxGroup();
tossed = new Checkbox("tossed", salads, false);
tossed.addItemListener(this);
caesar = new Checkbox("caesar", salads, false);
caesar.addItemListener(this);
croutons = new Checkbox("croutons");
croutons.addItemListener(this);
lite = new Checkbox("lite dressing");
lite.addItemListener(this);
textField7 = new TextField("35");
textField7.setEditable(false);
textField8 = new TextField("90");
textField8.setEditable(false);
textField9 = new TextField("60");
textField9.setEditable(false);
textField10 = new TextField("50");
textField10.setEditable(false);
CheckboxGroup entrees = new CheckboxGroup();
chicken = new Checkbox("chicken", entrees, false);
chicken.addItemListener(this);
beef = new Checkbox("beef", entrees, false);
beef.addItemListener(this);
lamb = new Checkbox("lamb", entrees, false);
lamb.addItemListener(this);
fish = new Checkbox("fish", entrees, false);
fish.addItemListener(this);
textField11 = new TextField("200");
textField11.setEditable(false);
textField12 = new TextField("170");
textField12.setEditable(false);
textField13 = new TextField("65");
textField13.setEditable(false);
textField14 = new TextField("150");
textField14.setEditable(false);
CheckboxGroup deserts = new CheckboxGroup();
pie = new Checkbox("pie", deserts, false);
pie.addItemListener(this);
fruit = new Checkbox("fruit", deserts, false);
fruit.addItemListener(this);
sherbet = new Checkbox("sherbet", deserts, false);
sherbet.addItemListener(this);
textField15 = new TextField("80");
textField15.setEditable(false);
textField16 = new TextField("60");
textField16.setEditable(false);
textField17 = new TextField("107");
textField17.setEditable(false);
calories = new Button("Calories");
calTextField = new TextField("0"+total);
calTextField.setEditable(false);
setLayout(new GridLayout(0, 1));
Panel p = new Panel();
add(p);
p.add(standard);
p.add(deluxe);
appetizerPanel = new Panel();
add(appetizerPanel);
label = new Label("Appetizer");
appetizerPanel.add(label);
appetizerPanel.add(crepe);
appetizerPanel.add(textField);
appetizerPanel.add(quiche);
appetizerPanel.add(textField2);
appetizerPanel.add(dumpling);
appetizerPanel.add(textField3);
soupPanel = new Panel();
add(soupPanel);
soupPanel.add(soup);
soupPanel.add(cream);
soupPanel.add(textField4);
soupPanel.add(broth);
soupPanel.add(textField5);
soupPanel.add(gumbo);
soupPanel.add(textField6);
saladPanel = new Panel();
add(saladPanel);
saladPanel.add(salad);
saladPanel.add(tossed);
saladPanel.add(textField7);
saladPanel.add(caesar);
saladPanel.add(textField8);
saladPanel.add(croutons);
saladPanel.add(textField9);
saladPanel.add(lite);
saladPanel.add(textField10);
entreePanel = new Panel();
add(entreePanel);
label2 = new Label("Entree");
entreePanel.add(label2);
entreePanel.add(chicken);
entreePanel.add(textField11);
entreePanel.add(beef);
entreePanel.add(textField12);
entreePanel.add(lamb);
entreePanel.add(textField13);
entreePanel.add(fish);
entreePanel.add(textField14);
desertPanel = new Panel();
add(desertPanel);
label3 = new Label("Desert");
desertPanel.add(label3);
desertPanel.add(pie);
desertPanel.add(textField15);
desertPanel.add(fruit);
desertPanel.add(textField16);
desertPanel.add(sherbet);
desertPanel.add(textField17);
caloriesPanel = new Panel();
add(caloriesPanel);
caloriesPanel.add(calories);
caloriesPanel.add(calTextField);
}
public void LabelChange(Label b) {
if (b ==label3)
b.setForeground(Color.lightGray);
else
label3.setForeground(Color.black);
}
/* This is where i get those errors!! */
int crepeVal = Integer.parseInt(textField.getText());
int quicheVal = Integer.parseInt(textField2.getText());
int dumplingVal = Integer.parseInt(textField3.getText());
int creamVal = Integer.parseInt(textField4.getText());
int brothVal = Integer.parseInt(textField5.getText());
int gumboVal = Integer.parseInt(textField6.getText());
int tossedVal = Integer.parseInt(textField7.getText());
int caesarVal = Integer.parseInt(textField8.getText());
int croutonsVal = Integer.parseInt(textField9.getText());
int liteVal = Integer.parseInt(textField10.getText());
int chickenVal = Integer.parseInt(textField11.getText());
int beefVal = Integer.parseInt(textField12.getText());
int lambVal = Integer.parseInt(textField13.getText());
int fishVal = Integer.parseInt(textField14.getText());
int pieVal = Integer.parseInt(textField15.getText());
int fruitVal = Integer.parseInt(textField16.getText());
int sherbetVal = Integer.parseInt(textField17.getText());
public boolean action(Event evt, Object whatAction){
if(!(evt.target instanceof Button)){
return false;
}
else {
calorieCount();
return true;
}
}
public void calorieCount () {
if (crepe.getState())
crepeVal += total;
else
crepeVal = 0;
if (quiche.getState())
quicheVal += total;
else
quicheVal = 0;
if (dumpling.getState())
dumplingVal += total;
else
dumplingVal= 0;
if (cream.getState())
creamVal += total;
else
creamVal = 0;
if (broth.getState())
brothVal += total;
else
brothVal = 0;
if (gumbo.getState())
gumboVal += total;
else
gumboVal = 0;
if (tossed.getState())
tossedVal += total;
else
tossedVal = 0;
if (caesar.getState())
caesarVal += total;
else
caesarVal = 0;
if (croutons.getState())
croutonsVal += total;
else
croutonsVal = 0;
if (lite.getState())
liteVal += total;
else
liteVal = 0;
if (chicken.getState())
chickenVal += total;
else
chickenVal = 0;
if (beef.getState())
beefVal += total;
else
beefVal = 0;
if (lamb.getState())
lambVal += total;
else
lambVal = 0;
if (fish.getState())
fishVal += total;
else
fishVal = 0;
if (pie.getState())
pieVal += total;
else
pieVal = 0;
if (fruit.getState())
fruitVal += total;
else
fruitVal = 0;
if (sherbet.getState())
sherbetVal += total;
else
sherbetVal = 0;
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == standard || e.getSource() == deluxe)
handleDinnerType((Checkbox)e.getSource());
else if (e.getSource() == soup || e.getSource() == salad)
handleSoupSaladChoice((Checkbox)e.getSource());
}
void handleDinnerType(Checkbox selectedType) {
boolean enabled;
if (selectedType == standard){
enabled = false;
LabelChange(label3);
}
else{
enabled = true;
LabelChange(label);
}
soup.setEnabled(enabled);
salad.setEnabled(enabled);
pie.setEnabled(enabled);
fruit.setEnabled(enabled);
sherbet.setEnabled(enabled);
cream.setEnabled(enabled);
broth.setEnabled(enabled);
gumbo.setEnabled(enabled);
tossed.setEnabled(enabled);
caesar.setEnabled(enabled);
croutons.setEnabled(enabled);
lite.setEnabled(enabled);
}
void handleSoupSaladChoice(Checkbox selectedCourse) {
boolean soupEnabled, saladEnabled;
if (selectedCourse == soup) {
soupEnabled = true;
saladEnabled = false;
soup.setForeground(Color.BLACK);
salad.setForeground(Color.lightGray);
}
else {
soupEnabled = false;
saladEnabled = true;
soup.setForeground(Color.lightGray);
salad.setForeground(Color.BLACK);
}
cream.setEnabled(soupEnabled);
broth.setEnabled(soupEnabled);
gumbo.setEnabled(soupEnabled);
tossed.setEnabled(saladEnabled);
caesar.setEnabled(saladEnabled);
croutons.setEnabled(saladEnabled);
lite.setEnabled(saladEnabled);
}
Label
label, label2, label3;
Panel
appetizerPanel, soupPanel, saladPanel, entreePanel, desertPanel, caloriesPanel;
Checkbox
standard, deluxe,
soup, salad,
crepe, quiche, dumpling,
cream, broth, gumbo,
tossed, caesar,
croutons, lite,
chicken, beef, lamb, fish,
pie, fruit, sherbet;
Button calories;
int total = 0;
TextField
textField, textField2, textField3,
textField4, textField5, textField6,
textField7, textField8, textField9,
textField10, textField11, textField12,
textField13, textField14, textField15,
textField16, textField17, calTextField;
}
In Java, you are not allowed to refer to a field a in an initializer of another field b if b is declared before a in the source code. That is, this is allowed:
int b = 3;
int a = b;
but this is not allowed:
int a = b;
int b = 3;
By the way, if Java had some magic way of figuring out that textField had to be initialized before crepeVal, you would still get a NullPointerException since textField is null after object construction.