how to set DefaultToolTip to a fixed size? - java

I have a custom tooltip class which extends ColumnViewerToolTipSupport. The problem is the tooltip boundary expands to fit the dynamic content. I need to implement a fixed sized toolTip which do not expand based on content size.
How can this be done ??
private static class MyToolTip extends ColumnViewerToolTipSupport {
public static final void enableFor(ColumnViewer viewer, int style) {
new MyToolTip(viewer, style, false);
}
private MyToolTip(ColumnViewer viewer, int style, boolean manualActivation) {
super(viewer, style, manualActivation);
setHideOnMouseDown(false);
}
#Override
protected Composite createViewerToolTipContentArea(Event event, ViewerCell cell, Composite parent) {
String text = getText(event);
if (text == null || text.isEmpty()) {
return super.createViewerToolTipContentArea(event, cell, parent);
}
ScrolledComposite scrolledComposite = new ScrolledComposite(parent,SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL);
final Composite comp = new Composite(scrolledComposite, SWT.NONE);
comp.getShell().setBackgroundMode(SWT.INHERIT_FORCE);
GridLayout gridLayout = new GridLayout(1, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
comp.setLayout(gridLayout);
comp.setLayoutData(new GridData(GridData.FILL_BOTH));
scrolledComposite.setContent(comp);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
scrolledComposite.setMinSize(comp.computeSize(150, 100));
StyledText styledText = new StyledText(comp, SWT.BORDER);
styledText.setText(text);
StyleRange style = new StyleRange();
style.start = 0;
style.length = text.indexOf(":");
style.fontStyle = SWT.BOLD;
styledText.setStyleRange(style);
String lineSep = System.getProperty("line.separator");
Matcher matcher = Pattern.compile("(" + lineSep + ")" + ".*?:").matcher(text);
while (matcher.find()) {
style = new StyleRange();
style.start = matcher.start();
style.length = matcher.end() - matcher.start();
style.fontStyle = SWT.BOLD;
}
return scrolledComposite;
}
}

Related

Create GridLayout With Rows of Equal Height

I want to have a composite with some labels, and all the labels should have the same height, but they should be vertically centered.
So far I have the following:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Composite composite = new Composite(shell, SWT.VERTICAL);
composite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).equalWidth(true).spacing(0, 0).create());
for (int i = 0; i < 10; i++) {
final Label label = new Label(composite, SWT.WRAP);
label.setAlignment(SWT.CENTER);
label.setText(i < 5 ? "small " + i : "a very big text for the row that is named " + i);
label.setToolTipText(label.getText());
label.setLayoutData(GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).grab(true, true).create());
}
shell.setSize(100, 600);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
As you can see, the labels are vertically centered in their rows, but the ones which wrap take more space than the other ones.
If I add hint(SWT.DEFAULT, 60) to the GridData, I can force the labels to have the same height, but then they won't be vertically centered anymore.
I could probably wrap all the labels in composites, set the height hint on the composite and center the labels, but let's see of there is another option first.
How do I create vertically centered rows of equal height?
Since you're trying to uniformly arrange widgets which may be different sizes, I think a good option would be to place each Label into a Composite. That way each Composite can have the same size, and the Label will be centered within.
By adding a ControlListener to the parent Composite, you can check the size of each child Composite, then set the height hint of each child to be the height of the largest child:
public static void main(final String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Composite composite = new Composite(shell, SWT.VERTICAL);
composite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).equalWidth(true).spacing(0, 0).create());
final List<Composite> children = new ArrayList<Composite>();
for (int i = 0; i < 10; i++) {
final Composite c = new Composite(composite, SWT.BORDER);
c.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
c.setLayout(new GridLayout());
final Label label = new Label(c, SWT.WRAP);
label.setAlignment(SWT.CENTER);
label.setText(i < 5 ? "small " + i : "a very big text for the row that is named " + i);
label.setToolTipText(label.getText());
label.setLayoutData(GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).grab(true, true).create());
children.add(c);
}
composite.addControlListener(new ControlAdapter() {
#Override
public void controlResized(final ControlEvent e) {
int maxHeight = 0;
for (final Composite c : children) {
if (c.getClientArea().height > maxHeight) {
maxHeight = c.getClientArea().height;
}
}
for (final Composite c : children) {
((GridData) c.getLayoutData()).heightHint = maxHeight;
}
}
});
shell.setSize(100, 600);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
Result:
And after resizing:

Label cut off when changing text using SWT

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

SWT Label with horizontal line not showing correctly

I'm trying to display a label in a 2-columned GridLayout. I can't seem to make it work to display both text and the horizontal line underneath:
public void foo(){
popupShell = new Shell(Display.getDefault(), SWT.NO_TRIM | SWT.ON_TOP | SWT.MODELESS);
//popupShell.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
popupShell.setLayout(createNoMarginLayout(2, false));
Label history = new Label(popupShell, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL);
history.setText("History");
history.setVisible(true);
Label fill = new Label(popupShell, SWT.NONE);
fill.setSize(0,30);
}
public static GridLayout createNoMarginLayout(int numColumns, boolean makeColumnsEqualWidth) {
GridLayout layout = new GridLayout(numColumns, makeColumnsEqualWidth);
layout.verticalSpacing = 0;
layout.horizontalSpacing = 0;
layout.marginTop = 0;
layout.marginBottom = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginWidth = 0;
layout.marginHeight = 0;
return layout;
}
What I'm getting is just the line with no text.
What am I doing wrong?
A Label with the SWT.SEPARATOR style does not display any text value. You must use a separate control to display the text.
From the Label source, showing that setText is completely ignored for SWT.SEPARATOR:
public void setText (String string) {
checkWidget();
if (string == null) error (SWT.ERROR_NULL_ARGUMENT);
if ((style & SWT.SEPARATOR) != 0) return;
...

Tooltip in other colums with Java SWT?

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

Checkbox Compilation Error

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.

Categories