Hey guys I have no Idea what happen? I add birthdays but if call them with getHashMap for example I cant get the elements in the class swingmenu. I just have thoughts about the Problem. I think its because I call new Event in a class and where I output the hashmap in a different class I call new Event too. But I dont know if I am right?
Maybe any Solution would help me. If you have Question then please ask me. For me its important to learn something new. There are some short coded showen because its not relevant. I debug the class swingFormatFunction and find out that the the instance event is null.
This part dont get added into my HashMap.
public class swingFormatFunction{
private Event event = new Event();
public void geburtstageFormatieren(String content) {
String formatContent = content.replace(';', ' ');
for (String s : formatContent.split("\n")) {
event.addBirthday(s.substring(0, 5).toString(), new Event(s.substring(12).toString()));
}
}
}
That is my menu where I call a Menuitem and click "ok". This function works fine I get the elements outputted.
public class swingMenu{
okBTN.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == okBTN) {
dialog.dispose();
JDialog dialog = new JDialog();
dialog.setModal(true);
dialog.setTitle("Calendar Special Events");
int yearNumber = Integer.parseInt((String) yearCombobox.getSelectedItem());
JTextArea textArea = new JTextArea();
Event event = new Event(yearNumber);
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry entry : event.getEventMap().entrySet()) {
stringBuilder.append(entry.getKey() + " : " + entry.getValue() + "\n");
}
textArea.setText(stringBuilder.toString());
dialog.setContentPane(textArea);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setResizable(true);
textArea.setEditable(false);
dialog.setVisible(true);
}
}
});
That is my Event class. This class contains my HashMap where I work with it.
public class Event{
private HashMap<String, Event> eventMap = new HashMap<>();
public Event(String name) {
this.name = name;
}
public Event(int year) {
addStrongMoveableHolidayInMap(year);
}
public Event() {
}
private void addMoveableHoliday(int year) {
/* Bewegliche Feiertage */
/*Rose monday (-48)*/
int daynumberOfEasterSunday = calenderFunction.easterSunday(year) - 48;
String gregorDate = calenderFunction.kalenderDatumFuerJD(daynumberOfEasterSunday);
String day = gregorDate.substring(0, 2);
String month = gregorDate.substring(3, 5);
String date = day + "." + month;
this.eventMap.put(date, new Event("Rosenmontag"));
}
private void addStrongHoliday(int year) {
/* Feste Feiertage */
this.eventMap.put("24.12", new Event("1. Weihnachtstag"));
}
void addStrongMoveableHolidayInMap(int year) {
addStrongHoliday(year);
addMoveableHoliday(year);
}
public void addBirthday(String year, Event event) {
this.eventMap.put(year, event);
}
public HashMap<String, Event> getEventMap() {
return eventMap;
}
}
I hope you guys can help me.
Best Regards
Manuellsen
The two event objects are totally independent.
The first one in swingFormatFunction is a instance attribute and the second one in ActionListener is a local variable.
The Event's eventMap attribute is also an instance attribute, so each Event object has its own map. Maybe you want to share one eventMap accross all events.
Related
I am often struggling with the same problem of custom Objects that creates a e.g. gui Component. And I never know what is the best way to get from the gui Component back to the object.
So multiple hacks and tricks are welcome.
Let me explain it to you:
This is my custom Object I need to find afterwards
public class MyObject {
int yearOfBirth;
String name;
public MyObject(int yearOfBirth, String name) {
this.yearOfBirth = yearOfBirth;
this.name = name;
}
public int getYearOfBirth() {
return yearOfBirth;
}
public Component getPanel() {
Component panel1 = makeTextPanel("This is the personal tab of "+name);
return panell;
}
}
This is where I need to find it through the Tab I am focusing
public class MyTabControl implements ChangeListener {
JTabbedPane myTabPane = new JTabbedPane();
public MyTabControl(){
//This will add a Listener for clicking on one Tab
myTabPane.addChangeListener(this);
}
public void oneMoreTab(MyObject myObject) {
myTabPane.addTab(myObject.name, myObject.getPanel())
}
public void stateChanged(ChangeEvent arg0) {
System.out.println("Focus of Tab changed");
int actualFocusedTabIndex = myTabPane.getSelectedIndex();
Component acutalFocusedComponent = myTabPane.getComponentAt(actualFocusedTabIndex);
//This works fine, I can get the Tab. Or at least the Component.
//But how do I get the yearOfBirth or better the Object itself?
int yearOfBirthOfTheSelectedTab = ???
}
}
This is just the main function
public static void main(String[] args) {
//Commands to start and create the GUI
MyTabControl myTabControl = new MyTabControl();
MyObject mother = new MyObject(1960, "Helen");
myTabControl.oneMoreTab(mother);
MyObject father = new MyObject(1955, "James");
myTabControl.oneMoreTab(father);
}
EDIT:
1 not working solution: Extend Component class
I have tried to extend the class Component. But this will create a failure (see comment in code):
public class ComponentWithExtras extends Component {
MyObject myObject;
public void addMyObject(MyObject myObject) {
this.myObject = myObject;
}
}
// The following line will create failure: Can't cast Component to ComponentWithExtras
ComponentWithExtras componentWithExtras = (ComponentWithExtras) myObject.getPanel();
componentWithExtras.addMyObject(myObject);
myTabPane.addTab(myObject.name, componentWithExtras);
I have an abstract GUI parent class handling a click event.
public abstract class GUI implements Listener {
private final Inventory inventory;
public GUI(Player player) {
Bukkit.getPluginManager().registerEvents(this, NPCs.getPlugin());
ItemStack fillerItem = new ItemStack(getFiller());
ItemMeta fillerItemMeta = fillerItem.getItemMeta();
fillerItemMeta.setDisplayName("");
fillerItem.setItemMeta(fillerItemMeta);
int inventorySize = (getFunctionalItems().size()>=54) ? 54 : getFunctionalItems().size()+(9-getFunctionalItems().size()%9)*Math.min(1, getFunctionalItems().size()%9);
inventory = Bukkit.createInventory(player, inventorySize, getName());
for(int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, fillerItem);
}
for(int i = 0; i < getFunctionalItems().size(); i++) {
inventory.setItem(i, getFunctionalItems().get(i));
}
}
#EventHandler
public void onClick(InventoryClickEvent event) {
handle(event);
}
public abstract ArrayList<ItemStack> getFunctionalItems();
public abstract String getName();
protected abstract void handle(InventoryClickEvent event);
public Material getFiller() {
return Material.GRAY_STAINED_GLASS_PANE;
}
public Inventory getInventory() {
return inventory;
}
protected final ItemStack createFunctionalItem(String name, Material material) {
ItemStack itemStack = new ItemStack(material);
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.setDisplayName(name);
itemStack.setItemMeta(itemMeta);
return itemStack;
}
}
In my child class it gets handled like following
#Override
public void handle(InventoryClickEvent event) {
ItemStack clicked = event.getCurrentItem();
Player player = (Player) event.getWhoClicked();
MainGUI mainGUI = new MainGUI(player);
NameGUI nameGUI = new NameGUI(player);
SkinGUI skinGUI = new SkinGUI(player);
//Main GUI
if(Arrays.equals(event.getClickedInventory().getContents(), mainGUI.getInventory().getContents())) {
switch(clicked.getItemMeta().getDisplayName()) {
case "Set Name" -> player.openInventory(nameGUI.getInventory());
case "Set Skin" -> player.openInventory(skinGUI.getInventory());
}
event.setCancelled(true);
}
}
But if I test it gets called 2 times on the first click and on the following so many times it even forces my game to crash. I know I can just put in a delay but I really want to know why this is the case.
Thank you
It's running multiple times because you are adding each new GUI to listener.
For example, here:
MainGUI mainGUI = new MainGUI(player);
NameGUI nameGUI = new NameGUI(player);
SkinGUI skinGUI = new SkinGUI(player);
You are creating 3 GUIs, so 3 new inventory click event register in listener.
To fix this, I suggest you to :
Make ONE class that receive InventoryClickEvent event, and call GUI that you be called.
For example, you have a list with all GUI:
public static List<GUI> ALL_GUIS = new ArrayList<>();
Then, you should have a way to determine in which inventory the player clicked, such as:
Inventory name. Not very good solution if this can change, but easier to create and use
Inventory holder like this:
public class MainGUIHolder implements InventoryHolder {
#Override
public Inventory getInventory() {
return null;
}
}
Now use it like that:
Inventory mainInv = Bukkit.createInventory(new MainGUIHolder(), 9, "My inv");
You can check with inventory instanceof MainGUIHolder, then get the holder instance with maybe some object that is currently edited by the player
Don't create multiple times GUI instance. For me, it's not a good way, and I think it's better to do like this :
MainGUI mainGUI = GuiManager.getMainGUID(); // here get the alone main GUI instance
// now use it
There is a vey nice libray(https://github.com/Applandeo/Material-Calendar-View) for customizing the android calenderview . Like for example, for adding events to the calenderview there is class named Eventday.java, which takes calender object and a drawable object as parameters to initialize. I wish it could have take a string value too so that i can also store a descrption of the event, because there is no point in adding events to the calender if one cannot add details about the event(string datatype). Can some one provide a workaround for my problem?
List<EventDay> events = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
//we cannot details about the event(string data) while initializing the EventDay class
events.add(new EventDay(calendar, R.drawable.absentic));
First Make a Custom Class
import com.applandeo.materialcalendarview.EventDay;
import java.util.Calendar;
public class MyEventDay extends EventDay implements Parcelable {
private String mNote;
public MyEventDay(Calendar day, int imageResource, String note) {
super(day, imageResource);
mNote = note;
}
public String getNote() {
return mNote;
}
private MyEventDay(Parcel in) {
super((Calendar) in.readSerializable(), in.readInt());
mNote = in.readString();
}
public static final Creator<MyEventDay> CREATOR = new Creator<MyEventDay>() {
#Override
public MyEventDay createFromParcel(Parcel in) {
return new MyEventDay(in);
}
#Override
public MyEventDay[] newArray(int size) {
return new MyEventDay[size];
}
};
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeSerializable(getCalendar());
parcel.writeInt(getImageResource());
parcel.writeString(mNote);
}
#Override
public int describeContents() {
return 0;
}
}
Adding Event In Calender
mEventDays.add(new MyEventDay(calender, R.drawable.ic_note_sticky, "I am Event");
For Retriving String
calendarView.setOnDayClickListener(new OnDayClickListener() {
#Override
public void onDayClick(EventDay eventDay) {
Log.e("Event",((MyEventDay) eventDay).getNote()+" <--");
}
});
Its Work For me , I Hope its Helpfull to you also
I used this method to display small popup note when user clicks on any date.
Declared: Map<Date,String> eventNotes = new HashMap<>()
While updating calendar events for every date, populated the eventNotes with required notes and date as key
In Calendar setOnDayClickListener retrieved eventNote using the key eventDay.getCalendar().getTime()
Then used a dialog popup to show that note
I'm trying to build a simple java application using Spring Boot and Vaadin.
I need to add a table on UI like this: https://www.screencast.com/t/1c4xkr4IE
It could be extended by periods.
Looks like Vaadin Grid element perfectly fits my requirements, but it adds my rows as columns. Is it possible to reverse grid or maybe there is another way to build needed table?
UPDATE
Here are my code:
#SpringComponent
#UIScope
public class MyDataEditor extends VerticalLayout {
private final MyDataRepository repository;
private MyData myData;
TextField month = new TextField("Period");
TextField numberOfWorkers = new TextField(" Number of workers");
TextField numberOfNewcomers = new TextField("Number of newcomers");
TextField numberOfDismissals = new TextField("Number of dismissals");
Button save = new Button("Save");
Button cancel = new Button("Cancel");
Button delete = new Button("Delete");
CssLayout actions = new CssLayout(save, cancel, delete);
Binder<MyData> binder = new Binder<>(MyData.class);
#Autowired
public MyDataEditor(MyDataRepository repository) {
this.repository = repository;
addComponents(month, numberOfWorkers, numberOfNewcomers, numberOfDismissals, actions);
binder.bindInstanceFields(this);
setSpacing(true);
actions.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
save.setStyleName(ValoTheme.BUTTON_PRIMARY);
save.setClickShortcut(ShortcutAction.KeyCode.ENTER);
save.addClickListener(e -> repository.save(myData));
delete.addClickListener(e -> repository.delete(myData));
cancel.addClickListener(e -> editInputData(myData));
setVisible(false);
}
public interface ChangeHandler {
void onChange();
}
public final void editMyData(MyData c) {
if (c == null) {
setVisible(false);
return;
}
final boolean persisted = c.getMonth() != null;
if (persisted) {
myData = repository.findOne(c.getMonth());
} else {
myData = c;
}
cancel.setVisible(persisted);
binder.setBean(myData);
save.focus();
periodId.selectAll();
}
public void setChangeHandler(ChangeHandler h) {
save.addClickListener(e -> h.onChange());
delete.addClickListener(e -> h.onChange());
}
}
#SpringUI
#Theme("valo")
public class VaadinUI extends UI {
private final MyDataRepository repo;
private final MyDataEditor editor;
final Grid<MyData> grid;
private final Button addNewBtn;
#Autowired
public VaadinUI(MyDataRepository repo, MyDataEditor editor) {
this.repo = repo;
this.editor = editor;
this.grid = new Grid<>(MyData.class);
this.addNewBtn = new Button("Add new month");
}
#Override
protected void init(VaadinRequest request) {
grid.setHeight(300, Unit.PIXELS);
grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");
grid.asSingleSelect().addValueChangeListener(e -> {
editor.editMyData(e.getValue());
});
addNewBtn.addClickListener(e -> editor.editMyData(new MyData()));
editor.setChangeHandler(() -> {
editor.setVisible(false);
grid.setItems(repo.findAll());
});
}
}
So what I mean by this question is that I set
grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");
and do not find out method like setRows, so my table looks like: https://www.screencast.com/t/ndDY6tXp, but should be like on first picture.
I do believe there is no way to solve it elegantly without CSS or extending the client grid component.
What you could do though is add your data using
List<MyData> data = repo.findAll();
for(int i = 0; i < data.size(); i++)
grid.addColumn(i)
//String[] months = data.map(x -> x.month).collect(Collectors.toArray)
//String[] nrWork = data.map(x -> x.nrWork).collect(Collectors.toArray)
grid.addRow(months)
grid.addRow(nrWork)
I believe the Vaadin grid (or table) component was designed having the table concept as a starting point. Hence you'd have a unified structure defined by the columns and display any number of same-type data elements, 1 per row. And as far as I know, up to 8.0.4, you can't rotate the structure.
Furthermore, from the user experience perspective, if you have multiple time periods, it'll be easier to scroll them vertically (with the mouse wheel) than horizontally, so I'd suggest discussing the possibility of displaying them just as you started, with the "month", "numberOfWorkers", "numberOfNewcomers" and "numberOfDismissals" columns, and supplying rows of MyData. This also makes it easier to sort, filter, add or edit selected items, whereas for the workaround below, you'd have to do something extra.
If for some reason that's not acceptable at all, you should be able to fake the feature you want with a bit of work (see below sample), but performance and usability wise, there's no guarantees... after all, this is not what it's been designed for.
Code
package com.example.grid;
import com.vaadin.data.ValueProvider;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Notification;
import com.vaadin.ui.VerticalLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Function;
public class HorizontalGrid extends VerticalLayout {
private static final String ROW_CAPTION = "row-caption";
public HorizontalGrid() {
// basic grid setup without column header
Grid<HorizontalDisplayAdapter> grid = new Grid<>();
grid.setSizeFull();
grid.setSelectionMode(Grid.SelectionMode.NONE);
grid.removeHeaderRow(0);
// load some data from the DB or someplace else
List<PeriodSummary> periods = loadPeriods();
// add row headers
grid.addColumn(HorizontalDisplayAdapter::getCaption).setId(ROW_CAPTION).setWidth(150);
// add a column for each period
for (int i = 0; i < periods.size(); i++) {
// save the column index so we ca figure out what to edit later
grid.addColumn(new AdapterValueProvider(i)).setId(String.valueOf(i)).setWidth(60);
}
// wrap the data in "horizontal display adapters"
grid.setItems(
new HorizontalDisplayAdapter("Period", periods, PeriodSummary::getPeriod),
new HorizontalDisplayAdapter("Workers", periods, PeriodSummary::getWorkers),
new HorizontalDisplayAdapter("Newcomers", periods, PeriodSummary::getNewcomers),
new HorizontalDisplayAdapter("Dismissals", periods, PeriodSummary::getDismissals)
);
// retrieve the correct period summary to edit, based on the column that was clicked (unless it's the header)
grid.addItemClickListener(event -> {
if (!ROW_CAPTION.equals(event.getColumn().getId())) {
Integer columnIndex = Integer.valueOf(event.getColumn().getId());
Notification.show("Editing " + event.getItem().getSummary(columnIndex), Notification.Type.ERROR_MESSAGE);
}
});
// freeze first column for scrolling purposes
grid.setFrozenColumnCount(1);
addComponent(grid);
setSizeFull();
}
// generate some dummy data to simulate loading from the DB
private List<PeriodSummary> loadPeriods() {
Random random = new Random();
ArrayList<PeriodSummary> periodSummaries = new ArrayList<>();
for (int i = 0; i < 100; i++) {
periodSummaries.add(new PeriodSummary(i, random.nextInt(100), random.nextInt(100), random.nextInt(100)));
}
return periodSummaries;
}
// adapter to display data in a "horizontal format"
public class HorizontalDisplayAdapter {
// row caption
private final String caption;
// periods for each column
private final List<PeriodSummary> periods;
// used for brevity, a class hierarchy is probably more elegant
private Function<PeriodSummary, Integer> valueExtractor;
public HorizontalDisplayAdapter(String caption, List<PeriodSummary> periods, Function<PeriodSummary, Integer> valueExtractor) {
this.caption = caption;
this.periods = periods;
this.valueExtractor = valueExtractor;
}
public String getCaption() {
return caption;
}
public PeriodSummary getSummary(int columnIndex) {
return periods.get(columnIndex);
}
// extract the data for a certain column
public Integer getValue(int columnIndex) {
return valueExtractor.apply(periods.get(columnIndex));
}
}
// basic bean
public class PeriodSummary {
int period;
int workers;
int newcomers;
int dismissals;
public PeriodSummary(int period, int workers, int newcomers, int dismissals) {
this.period = period;
this.workers = workers;
this.newcomers = newcomers;
this.dismissals = dismissals;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getWorkers() {
return workers;
}
public void setWorkers(int workers) {
this.workers = workers;
}
public int getNewcomers() {
return newcomers;
}
public void setNewcomers(int newcomers) {
this.newcomers = newcomers;
}
public int getDismissals() {
return dismissals;
}
public void setDismissals(int dismissals) {
this.dismissals = dismissals;
}
#Override
public String toString() {
return "PeriodSummary{" +
"period=" + period +
", workers=" + workers +
", newcomers=" + newcomers +
", dismissals=" + dismissals +
'}';
}
}
// value provider for the horizontal display adapters
private class AdapterValueProvider implements ValueProvider<HorizontalDisplayAdapter, Integer> {
// column index is used to retrieve data from the correct summary
private int columnIndex;
public AdapterValueProvider(int columnIndex) {
this.columnIndex = columnIndex;
}
#Override
public Integer apply(HorizontalDisplayAdapter horizontalDisplayAdapter) {
return horizontalDisplayAdapter.getValue(columnIndex);
}
}
}
Result
I'm a newbie in java and I have a small problem. I want to access a variable in one class from another. I have three classes and I want to be able to access a variable in the main class to enable me read the array.
The error I am getting is
java.lang.SecurityException: MIDlet not constructed by createMIDlet
Please see the example below. Please bear in mind they're all in the same package.
package tungPackage;
import com.sun.lwuit.*;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import javax.microedition.midlet.MIDlet;
public class TungMidlet extends MIDlet implements ActionListener {
private Command back = new Command("Back");
private Command ok = new Command("Ok");
public ActionListener commandlistListener = new ActionListener() {
public void actionPerformed(ActionEvent cmd) {
// check which command cliked
if (cmd.getCommand() == back) {
// go back to previous form
mainForm.show();
} else if (cmd.getCommand() == ok) {
// go forward
}
}
};
private List list;
private Form mainForm;
private Label promptLabel;
private housesClass houseClassObject = new housesClass();
public int counter; //this is the variable I want to access in a class called calculate class object.
private int sumAmmt;
public TungMidlet tungMidletObject;
public calculateClass calculateClassObject;
public TungMidlet() {
Display.init(this);
}
private ActionListener applistListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(list.getSelectedIndex()==0){
counter++;
if (counter>5)
{
//check sum price.
sumAmmt = calculateClassObject.calculateSum();
Dialog x = new Dialog("info");
Label label = new Label("Maximum reached.");
Label label2 = new Label("Sum ammt = "+sumAmmt);
x.addComponent(label);
x.addComponent(label2);
x.addCommand(ok);
x.show();
}
else
{
//calculate the price
String info = houseClassObject.randomHouse();
Dialog x = new Dialog("info");
Label label = new Label(info);
x.addComponent(label);
x.addCommand(ok);
x.show();
}
}
}
};
public void startApp() {
//calculateClassObject = new calculateClass();
//sumAmmt = calculateClassObject.calculate(sumAmmt);
mainForm = new Form("Investment Categories");
promptLabel = new Label("choose category");
list = new List();
list.addItem("House");
list.addItem("Cars");
list.addItem("Schools");
list.addItem("Schools");
list.addItem("Supermarkets");
list.addItem("Stocks");
list.addItem("Land");
list.addActionListener(applistListener);
mainForm.addComponent(promptLabel);
mainForm.addComponent(list);
mainForm.addCommand(back);
mainForm.addCommandListener(commandlistListener);
mainForm.setTransitionInAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 1000));
mainForm.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
The class I want to access the "counter" variable using is shown below.
package tungPackage;
import java.util.Random;
public class housesClass {
public Random generator = new Random();
public String[] houseArray = new String[5];
public housesClass housesClassObject;
public calculateClass calcobj;// = new calculateClass();
public housesClass()
{
}
public String randomHouse() {
housesClassObject = new housesClass();
houseArray[0] = "Bungalow - 20,000,000 Shillings";
houseArray[1] = "Microhouse - 10,000,000 Shillings";
houseArray[2] = "Flat - 200,000,000 shillings";
houseArray[3] = "Garage apartment - 7,000,000 shillings";
houseArray[4] = "Studio apartment - 13,000,000 shillings";
int rnd = generator.nextInt(houseArray.length);
housesClassObject.housePrices(rnd);///noma
String house = houseArray[rnd];
return house;
}
void housePrices(int houseNumber) {
calcobj = new calculateClass();
TungMidlet tungmidobj = new TungMidlet();
int counter = tungmidobj.counter;
int[] housePriceArray = new int[5];
housePriceArray[0] = 20000000;
housePriceArray[1] = 10000000;
housePriceArray[2] = 200000000;
housePriceArray[3] = 7000000;
housePriceArray[4] = 13000000;
int price = housePriceArray[houseNumber];
calcobj.storePrice(counter,price);
}
}
The other supporting class is shown below.
package tungPackage;
public class calculateClass {
int[] storeArray = new int[5];
public calculateClass()
{
}
public void storePrice(int counter, int number2)
{
storeArray[counter] = number2;
}
public int calculateSum()
{
int sum =0;
for(int i=1; i<6; i++){
sum= sum+storeArray[i];
}
return sum;
}
}
Are you getting an error? It looks like your access code should work.
I can't seem to find anywhere that you actually initialise counter though, so maybe your problem is that you need to put counter = 0; somewhere in your code.
Java is also object oriented so you should avoid accessing like the above and make some 'getter and setter' methods:
public int getCounter() {
return counter;
}
and then call int counter = tungmidobj.getCounter();
remove TungMidlet constructor. If there was something useful to do there, you could also declare it protected - but this is not the case with your code snippet, see below.
Wherever you try to invoke that constructor directly, remove code that does this and find another way to do what you need. If needed, study code examples provided in LWUIT Tutorial - Introduction for how typical things are done in LWUIT.
put statement Display.init() in the beginning of the startApp method,
just like it is done in LWUIT Tutorial - Hello, LWUIT! example code
The reason why you are getting SecurityException is because you invoke TungMidlet constructor directly. Don't do that.
MIDP API documentation for MIDlet constructor states:
Throws:
SecurityException - unless the application management software is creating the MIDlet.
one way is
TungMidlet tungMidlet=new TungMidlet();
System.out.println(tungMidlet.counter);
but know encapsulation
second way is
you can make counter private variable and provide setter and getters.
private int counter;
public void setCounter(int counter){
this.counter=counter;
}
public int getCounter(){
return counter;
}
second way is preferred way as it achieves encapsulation