Can someone explain me how to maintain data in array list during the running of app. Let say we have three classes. The main class run the app and the button "Save" add the data in the second class where is declared the private array list. Then when we added the data in array list , we click the button "Next scene". When is opened the second stage which is the third class, there is button "Show", that should show the data which were added in the first class, but it threw error that the array list is empty.
Code:
First class
public void start(Stage primaryStage) {
final Button btn = new Button();
btn.setLayoutX(121);
btn.setLayoutY(125);
btn.setText("Save");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
array.insert(20);
}
});
final Button btn_next = new Button();
btn_next.setLayoutX(btn.getLayoutY());
btn_next.setLayoutY(btn.getLayoutX() + 54);
btn_next.setText("Next Scene");
btn_next.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
secondStage.start();
}
});
Pane root = new Pane();
root.getChildren().add(btn);
root.getChildren().add(btn_next);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Exercise");
primaryStage.setScene(scene);
primaryStage.show();
}
Second class
public class ArrayListClass {
private ArrayList <Integer> array = new ArrayList<>();
private ObservableList name_obs = FXCollections.observableArrayList(array);
public void insert(int maxBound) {
for(int i = 0; i < maxBound; i++) {
name_obs.add(i);
}
}
public Integer show(int i) {
return (Integer) name_obs.get(i);
}
}
Third class
public class SecondStage {
private Stage secondaryStage = new Stage();
ArrayListClass array = new ArrayListClass();
public void start() {
Button btn= new Button();
btn.setText("Show");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println(array.show(5));
}
}
);
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
secondaryStage.setTitle("Exercise");
secondaryStage.setScene(scene);
secondaryStage.show();
}
}
ERROR:
Executing /Users/Jenda/NetBeansProjects/ExerciseArrayList/dist/run542796410/ExerciseArrayList.jar using platform /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/bin/java
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index: 5, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
at exercisearraylist.ArrayListClass.show(ArrayListClass.java:36)
at exercisearraylist.SecondStage$1.handle(SecondStage.java:36)
at exercisearraylist.SecondStage$1.handle(SecondStage.java:31)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8216)
at javafx.scene.control.Button.fire(Button.java:185)
Related
When i create a new tab with a button and in that tab i have a button to pass the data from the textfield in that tab to the textfield in the first created tab but when i switch i got the data data in the textfield in the first tab, but it doesn't display that data in the textfiled
How cai pass data from selected tab natural to first tab she show it on textfield
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
/**
* #author Nguyen Phuc Thinh
*/
public class Test extends JFrame {
private JPanel contentPane;
private JButton btnNewTab;
private JTabbedPane tabbedPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnNewTab = new JButton("New Tab");
btnNewTab.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newTab();
}
});
btnNewTab.setBounds(175, 10, 85, 21);
contentPane.add(btnNewTab);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 60, 416, 193);
contentPane.add(tabbedPane);
}
private void newTab() {
JPanel[] panel = new JPanel[tabbedPane.getTabCount()+1];
JTextField[] txtValue = new JTextField[tabbedPane.getTabCount()+1];
JButton[] btnSend = new JButton[tabbedPane.getTabCount()+1];
for(int i =0; i < tabbedPane.getTabCount()+1; i++) {
panel[i] = new JPanel();
txtValue[i] = new JTextField(10);
btnSend[i] = new JButton();
btnSend[i].setPreferredSize(new Dimension(100, 25));
btnSend[i].setText("Send tab 1");
if(tabbedPane.getTabCount() ==0) {
btnSend[i].setVisible(false);
}
panel[i].add(txtValue[i]);
panel[i].add(btnSend[i]);
btnSend[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
btnSend[0].setText(txtValue[tabbedPane.getSelectedIndex()].getText());
System.out.println(txtValue[tabbedPane.getSelectedIndex()].getText());
}
});
}
tabbedPane.addTab("Tab"+(tabbedPane.getTabCount()+1), null, panel[tabbedPane.getTabCount()], null);
}
}
I am working on android app which fetch data using RecyclerView and Retrofit for parsing JSON Url. I had following tutorial on this Github
My project on Android Studio has no Errors and I'm able to run the Application. But when I open the MainActivity it crashes.
Error that i am get
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
This is the following line is on setUpAndLoadNativeExpressAds
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
This is MainActivity
public class MainActivity extends AppCompatActivity{
public static final int ITEMS_PER_AD = 3;
private static final int NATIVE_EXPRESS_AD_HEIGHT = 150;
private static final String AD_UNIT_ID = ADMOB_NATIVE_MENU_ID;
private StartAppAd startAppAd = new StartAppAd(this);
private RecyclerView mRecyclerView;
private List<Object> mRecyclerViewItems = new ArrayList<>();
private KontenAdapter kontenAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// Use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView.
mRecyclerView.setHasFixedSize(true);
// Specify a linear layout manager.
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
// mRecyclerViewItems = new ArrayList<>();
// Update the RecyclerView item's list with menu items and Native Express ads.
// addMenuItemsFromJson();
loadJSON();
// initData();
setUpAndLoadNativeExpressAds();
}
/**
* Adds Native Express ads to the items list.
*/
private void addNativeExpressAds() {
// Loop through the items array and place a new Native Express ad in every ith position in
// the items List.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = new NativeExpressAdView(MainActivity.this);
mRecyclerViewItems.add(i, adView);
}
}
/**
* Sets up and loads the Native Express ads.
*/
private void setUpAndLoadNativeExpressAds() {
mRecyclerView.post(new Runnable() {
#Override
public void run() {
final float scale = MainActivity.this.getResources().getDisplayMetrics().density;
// Set the ad size and ad unit ID for each Native Express ad in the items list.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
final CardView cardView = (CardView) findViewById(R.id.ad_card_view);
final int adWidth = cardView.getWidth() - cardView.getPaddingLeft()
- cardView.getPaddingRight();
AdSize adSize = new AdSize((int) (adWidth / scale), NATIVE_EXPRESS_AD_HEIGHT);
adView.setAdSize(adSize);
adView.setAdUnitId(AD_UNIT_ID);
}
// Load the first Native Express ad in the items list.
loadNativeExpressAd(0);
}
});
}
/**
* Loads the Native Express ads in the items list.
*/
private void loadNativeExpressAd(final int index) {
if (index >= mRecyclerViewItems.size()) {
return;
}
Object item = mRecyclerViewItems.get(index);
if (!(item instanceof NativeExpressAdView)) {
throw new ClassCastException("Expected item at index " + index + " to be a Native"
+ " Express ad.");
}
final NativeExpressAdView adView = (NativeExpressAdView) item;
// Set an AdListener on the NativeExpressAdView to wait for the previous Native Express ad
// to finish loading before loading the next ad in the items list.
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
// The previous Native Express ad loaded successfully, call this method again to
// load the next ad in the items list.
loadNativeExpressAd(index + ITEMS_PER_AD);
}
#Override
public void onAdFailedToLoad(int errorCode) {
// The previous Native Express ad failed to load. Call this method again to load
// the next ad in the items list.
Log.e("MainActivity", "The previous Native Express ad failed to load. Attempting to"
+ " load the next Native Express ad in the items list.");
loadNativeExpressAd(index + ITEMS_PER_AD);
}
});
// Load the Native Express ad.
adView.loadAd(new AdRequest.Builder().build());
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.myjson.com/") //https://api.myjson.com/bins/v4dzd
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mRecyclerViewItems = new ArrayList<Object>(Arrays.asList(jsonResponse.getKonten()));
addNativeExpressAds();
RecyclerView.Adapter adapter = new KontenAdapter(mRecyclerViewItems, getApplicationContext());
mRecyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
/**
* Adds {#link KontenItem}'s from a JSON file.
*/
private void addMenuItemsFromJson() {
try {
String jsonDataString = readJsonDataFromFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
String menuItemName = menuItemObject.getString("name");
String menuItemDescription = menuItemObject.getString("description");
String menuItemPrice = menuItemObject.getString("price");
String menuItemCategory = menuItemObject.getString("category");
String menuItemImageName = menuItemObject.getString("photo");
String menuItemUrl = menuItemObject.getString("url");
KontenItem kontenItem = new KontenItem(menuItemName, menuItemDescription, menuItemPrice,
menuItemCategory, menuItemImageName, menuItemUrl);
mRecyclerViewItems.add(kontenItem);
}
} catch (IOException | JSONException exception) {
Log.e(MainActivity.class.getName(), "Unable to parse JSON file.", exception);
}
}
/**
* Reads the JSON file and converts the JSON data to a {#link String}.
*
* #return A {#link String} representation of the JSON data.
* #throws IOException if unable to read the JSON file.
*/
private String readJsonDataFromFile() throws IOException {
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null;
inputStream = getResources().openRawResource(R.raw.menu_items_json);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
This is MyAdapter
public class KontenAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// A menu item view type.
private static final int MENU_ITEM_VIEW_TYPE = 0;
// The Native Express ad view type.
private static final int NATIVE_EXPRESS_AD_VIEW_TYPE = 1;
// An Activity's Context.
private final Context mContext;
// The list of Native Express ads and menu items.
private final List<Object> mRecyclerViewItems;
public KontenAdapter(List<Object> recyclerViewItems, Context context) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
}
/**
* The {#link MenuItemViewHolder} class.
* Provides a reference to each view in the menu item view.
*/
public class MenuItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView menuItemName;
private TextView menuItemDescription;
private TextView menuItemPrice;
private TextView menuItemCategory;
private ImageView menuItemImage;
private TextView menuItemUrl;
MenuItemViewHolder(View view) {
super(view);
menuItemImage = (ImageView) view.findViewById(R.id.menu_item_image);
menuItemName = (TextView) view.findViewById(R.id.menu_item_name);
menuItemPrice = (TextView) view.findViewById(R.id.menu_item_price);
menuItemCategory = (TextView) view.findViewById(R.id.menu_item_category);
menuItemDescription = (TextView) view.findViewById(R.id.menu_item_description);
menuItemUrl = (TextView) view.findViewById(R.id.menu_item_url);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent detailIntent = new Intent(v.getContext(), PostActivity.class);
detailIntent.putExtra("name",menuItemName.getText().toString() );
detailIntent.putExtra("url", menuItemUrl.getText().toString());
mContext.startActivity(detailIntent);
}
}
/**
* The {#link NativeExpressAdViewHolder} class.
*/
public class NativeExpressAdViewHolder extends RecyclerView.ViewHolder {
NativeExpressAdViewHolder(View view) {
super(view);
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
/**
* Determines the view type for the given position.
*/
#Override
public int getItemViewType(int position) {
return (position % MainActivity.ITEMS_PER_AD == 0) ? NATIVE_EXPRESS_AD_VIEW_TYPE
: MENU_ITEM_VIEW_TYPE;
}
/**
* Creates a new view for a menu item view or a Native Express ad view
* based on the viewType. This method is invoked by the layout manager.
*/
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.menu_item_container, viewGroup, false);
return new MenuItemViewHolder(menuItemLayoutView);
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// fall through
default:
View nativeExpressLayoutView = LayoutInflater.from(
viewGroup.getContext()).inflate(R.layout.native_express_ad_container,
viewGroup, false);
return new NativeExpressAdViewHolder(nativeExpressLayoutView);
}
}
/**
* Replaces the content in the views that make up the menu item view and the
* Native Express ad view. This method is invoked by the layout manager.
*/
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
KontenItem kontenItem = (KontenItem) mRecyclerViewItems.get(position);
// Get the menu item image resource ID.
String imageName = kontenItem.getImageName();
int imageResID = mContext.getResources().getIdentifier(imageName, "drawable",
mContext.getPackageName());
// Add the menu item details to the menu item view.
menuItemHolder.menuItemImage.setImageResource(imageResID);
menuItemHolder.menuItemName.setText(kontenItem.getName());
menuItemHolder.menuItemPrice.setText(kontenItem.getPrice());
menuItemHolder.menuItemCategory.setText(kontenItem.getCategory());
menuItemHolder.menuItemDescription.setText(kontenItem.getDescription());
menuItemHolder.menuItemUrl.setText(kontenItem.getInstructionUrl());
break;
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// fall through
default:
NativeExpressAdViewHolder nativeExpressHolder =
(NativeExpressAdViewHolder) holder;
NativeExpressAdView adView =
(NativeExpressAdView) mRecyclerViewItems.get(position);
ViewGroup adCardView = (ViewGroup) nativeExpressHolder.itemView;
// The NativeExpressAdViewHolder recycled by the RecyclerView may be a different
// instance than the one used previously for this position. Clear the
// NativeExpressAdViewHolder of any subviews in case it has a different
// AdView associated with it, and make sure the AdView for this position doesn't
// already have a parent of a different recycled NativeExpressAdViewHolder.
if (adCardView.getChildCount() > 0) {
adCardView.removeAllViews();
}
if (adView.getParent() != null) {
((ViewGroup) adView.getParent()).removeView(adView);
}
// Add the Native Express ad to the native express ad view.
adCardView.addView(adView);
}
}
}
KontenItem.java
class KontenItem {
private final String name;
private final String description;
private final String price;
private final String category;
private final String imageName;
private final String instructionUrl;
public KontenItem(String name, String description, String price, String category,
String imageName, String instructionUrl) {
this.name = name;
this.description = description;
this.price = price;
this.category = category;
this.imageName = imageName;
this.instructionUrl = instructionUrl;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getPrice() {
return price;
}
public String getCategory() {
return category;
}
public String getImageName() {
return imageName;
}
public String getInstructionUrl() {
return instructionUrl;
}
}
Thanks in advance!
You are calling addNativeExpressAds() and
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
in different threads. So, mRecyclerViewItems.get(i) is used before its initialization.
I would suggest to use
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mRecyclerViewItems = new ArrayList<Object>(Arrays.asList(jsonResponse.getKonten()));
addNativeExpressAds();
RecyclerView.Adapter adapter = new KontenAdapter(mRecyclerViewItems, getApplicationContext());
mRecyclerView.setAdapter(adapter);
setUpAndLoadNativeExpressAds(); // << ADD THIS METHOD HERE AND REMOVE THE OTHER CALLING
}
Your problem is that mRecyclerViewItems is a zero based array/collection. Yet in setUpAndLoadNativeExpressAds() you will iterate even if you have no elements, and then ask for element 0.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
..
}
you should instead
for (int i = 0; i < mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
..
}
I am working on a eclipse plugin and implementing a custom launcher as per the link https://eclipse.org/articles/Article-Launch-Framework/launch.html .
I have implemented a class BrowsersTab which extends AbstractLaunchConfigurationTab and implemented all the methods. The problem is that when I call the updateLaunchConfigurationDialog(); on the selection event , the 'Apply' Button remains disabled.
Code :
public class BrowsersTab extends AbstractLaunchConfigurationTab {
private Button chrome;
private Button firefox;
private Button safari;
private Button ie;
private Button opera;
private Button android;
private Button ios;
#Override
public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
GridLayout topLayout = new GridLayout();
comp.setLayout(topLayout);
Group fGroup = new Group(comp, SWT.NONE);
fGroup.setFont(parent.getFont());
fGroup.setLayout(new GridLayout(2, true));
fGroup.setText(DialogMessages.browserSelection);
chrome = new Button(fGroup, SWT.CHECK);
chrome.setText("Google Chrome");
chrome.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println("chrome selected");
updateLaunchConfigurationDialog();
}
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
Image chromeIcon= getBrowserIcon("chrome-browser-24X24.png");
if(null!=chromeIcon)
chrome.setImage(chromeIcon);
Combo comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
firefox = new Button(fGroup, SWT.CHECK);
firefox.setText("Mozilla Firefox");
Image firefoxIcon= getBrowserIcon("Firefox-icon.png");
if(null!=firefoxIcon)
firefox.setImage(firefoxIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
safari = new Button(fGroup, SWT.CHECK);
safari.setText("Apple Safari");
Image safariIcon= getBrowserIcon("Safari-icon.png");
if(null!=safariIcon)
safari.setImage(safariIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
ie = new Button(fGroup, SWT.CHECK);
ie.setText("Internet Explorer");
Image ieIcon= getBrowserIcon("Internet-Explorer-icon.png");
if(null!=ieIcon)
ie.setImage(ieIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
opera= new Button(fGroup, SWT.CHECK);
opera.setText("Opera");
Image operaIcon= getBrowserIcon("browser-opera-icon.png");
if(null!=operaIcon)
opera.setImage(operaIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
android= new Button(fGroup, SWT.CHECK);
android.setText("Android");
Image androidIcon= getBrowserIcon("android-platform-icon.png");
if(null!=androidIcon)
android.setImage(androidIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
ios= new Button(fGroup, SWT.CHECK);
ios.setText("Mobile Safari");
Image iosIcon= getBrowserIcon("Apple-grey-icon.png");
if(null!=iosIcon)
ios.setImage(iosIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
}
#Override
public String getName() {
return "Browsers";
}
public Image getBrowserIcon(String name){
Image icon=null;
try {
icon = AbstractUIPlugin.imageDescriptorFromPlugin("SuitACore","icons/"+name).createImage();
} catch (Exception e) {
// Swallow it; we'll do without images
}
return icon;
}
public Image getImage() {
Image tab=null;
try {
tab = AbstractUIPlugin.imageDescriptorFromPlugin("SuitACore","icons/browser.png").createImage();
} catch (Exception e) {
// Swallow it; we'll do without images
}
return tab;
}
public void initializeFrom(ILaunchConfiguration configuration) {
try {
List<String> browsersDefaults = new ArrayList<String>();
browsersDefaults.add("chrome");
List<String> browsers =configuration.getAttribute("browsers", browsersDefaults);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
chrome.setSelection(true);
}
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
List<String> browsers = new ArrayList<String>();
browsers.add("chrome");
configuration.setAttribute("browser",browsers );
}
public void setDefaults(ILaunchConfigurationWorkingCopy arg0) {
}
}
You must call updateLaunchConfigurationDialog() whenever anything changes that might update the Apply button - so all checkboxes and combos.
You must also save everything that changes in the ILaunchConfigurationWorkingCopy in the performApply method. The Apply button state is determined by checking that the working copy is different from the original configuration.
I want to develop a Swing desktop application with jlabel, JDateChooser and a submit button.
I am using below code :
public class Homeg {
public static void main(String args[]) {
JFrame frame=new JFrame("date display");
JDatePickerImpl datePicker;
UtilDateModel model = new UtilDateModel();
model.setDate(1990, 8, 24);
model.setSelected(true);
JDatePanelImpl datePanel = new JDatePanelImpl(model,null);
datePicker = new JDatePickerImpl(datePanel, null);
frame.setLayout(new FlowLayout());
JLabel label=new JLabel("Date");
JButton submit=new JButton("SUBMIT");
frame.add(label);
frame.add(datePicker);
frame.add(submit);
frame.setSize(400,400);
frame.setVisible(true);
}
}
And it is giving output having only JDatechooser.
Instead I wanted a output which must have a JLabel, JDatePicker and a submit button. Here it is showing only JDatePicker.
You should always call pack() before making a call to setVisible();
{
...
frame.setSize(400,400);
frame.pack();
frame.setVisible(true);
}
Then to actuall make the date the submit button submit the date use:
JButton submit= new JButton("SUBMIT");
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Date date = (Date) datePicker.getModel().getValue();
/* do something with 'date' */
}
});
I am sure its very simple but this is my first java class. the user enters a number into the input Jtextfield. the Add button is supposed to add that number to the arraylist. I am having trouble figuring out how to do that exactly. Any help you can give me would be awesome
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ArrayExercise extends JFrame
{
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 300;
private JPanel panel1;
private JPanel panel2;
private JLabel messageLabel;
private JTextField input;
private JTextArea output;
private JButton addButton;
private JButton list;
private JButton rlist;
private JButton clear;
public ArrayExercise()
{
setTitle("Array Exercise");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1();
panel2();
add(panel1, BorderLayout.EAST);
add(panel2, BorderLayout.WEST);
setVisible(true);
input.requestFocus();
}
private void panel1()
{
messageLabel = new JLabel("Input");
input = new JTextField(5);
addButton = new JButton("Add");
list = new JButton("List");
rlist = new JButton("R-List");
clear = new JButton("Clear");
addButton.addActionListener(new ButtonListener());
list.addActionListener(new ButtonListener());
rlist.addActionListener(new ButtonListener());
clear.addActionListener(new ButtonListener());
panel1 = new JPanel();
panel1.setLayout(new GridLayout(6,1));
panel1.add(messageLabel);
panel1.add(input);
panel1.add(addButton);
panel1.add(list);
panel1.add(rlist);
panel1.add(clear);
}
private void panel2()
{
output = new JTextArea(12, 10);
panel2 = new JPanel();
panel2.add(output);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String in;
int number;
int index = 0;
ArrayList<String> list = new ArrayList<>();
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
index++;
in = addButton.getText();
list.add(addButton.getText());
if (index == 9)
{
input.setEditable(false);
addButton.setEnabled(false);
}
output.setText(in + " added.");
input.setText(null);
input.requestFocus();
}
if (actionCommand.equals("List"))
{
for(int x = 0; x <= list.size(); x++)
{
output.setText((x+1)+ ". " + list.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ArrayExercise();
}
}
You have ArrayList list which is not adding any string value to that list and you are trying to run that over loop to get you values. If you are not adding anything to list then how can you extract anything out of it.
ArrayList<String> list = new ArrayList<String>();
For each button attach different actionlistener as all buttons are not supposed to act same way.
To add elements in ArrayList use this
list.add(input.getText()); // adding text entered into input textfield.
Make a list
List item
Make a TextField
Make Button Add Listener to button
Get the text from the text field or text area Add to array list
object
Here is all the work you need to do:
ArrayList<String> arrayObject= new ArrayList<String>();
JButton button = new JButton();
JtextField textBox = new JtextField ();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//inside your action listener:
String add_item_to_array = textBox.getText().trim();
arrayObject.add(add_item_to_array);
}
});