Issue populating JComboBox with array - arrays

I've been working on this for a while but I can't seem to fix the one line that is giving me all the problems. This line "list = new JComboBox(measure);" underneath the array, seems to be giving me the error. I can suppress the error and it runs except the JComboBox does not work properly and gives the error
"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JComboBox cannot be cast to javax.swing.JButton
at cube.actionPerformed(cube.java:132)"
Any help will be greatly appreciated!
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
//#SuppressWarnings("unchecked")
public class cube extends JFrame implements ActionListener{
public static JComboBox list;
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static JTextField d;
public static String measureFinal;
public static String measurement;
//public static String [] measurement = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
public static JFrame main = new JFrame("Volume of Cube");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
cube object = new cube();
}
cube(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.setPreferredSize(new Dimension(400,350));
main.add(myPanel);
a = new JTextField(3);
b = new JTextField(3);
c = new JTextField(3);
d = new JTextField(3);
JButton button1 = new JButton("Solve!");
JButton button2 = new JButton("Back to shape selector");
myPanel.add(new JLabel ("Select the unit of measurement"));
String measure[] = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
list = new JComboBox(measure);
list.setSelectedIndex(0);
list.addActionListener(this);
myPanel.add(list);
myPanel.add(new JLabel ("Enter the height of the box"));
myPanel.add(a);
myPanel.add(new JLabel ("Enter the width of the box"));
myPanel.add(b);
myPanel.add(new JLabel ("Enter the length of the box"));
myPanel.add(c);
myPanel.add(button1);
button1.addActionListener(this);
myPanel.add(button2);
button2.addActionListener(this);
main.pack();
main.setLocation(600,200);
main.setVisible(true);
//tring [] measurement = {"Inches" , "Meters", "Feet"};
//double volume = height * width * length;
//String answer = "The volume of the box is " +volume+ measurement;
}
public void CBSelect(ActionEvent e){
int temp = 0;
temp = list.getSelectedIndex();
//Object temp = e.getSource();
/*
if (e.getSource() == list){
temp = list.getSelectedIndex();
switch(temp){
case 0:
measurement = "Inches";
break;
case 1:
measurement = "Meters";
break;
case 2:
measurement = "Feet";
break;
case 3:
measurement = "Centimeters";
break;
case 4:
measurement = "Millimeters";
break;
case 5:
measurement = "Yards";
break;
}
}
*/
if (temp == 0){
measurement = "Inches";
} else if (temp == 1){
measurement = "Meters";
}else if (temp == 2){
measurement = "Feet";
}else if (temp == 3){
measurement = "Centimeters";
}else if (temp == 4){
measurement = "Millimeters";
}else if (temp == 5){
measurement = "Yards";
}
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
//JComboBox cb = ((JComboBox) e.getSource());
//measureFinal = (String)cb.getSelectedItem();
if (actionCommand == "Solve!"){
double height = Double.parseDouble(a.getText());
double width = Double.parseDouble(b.getText());
double length = Double.parseDouble(c.getText());
double volume = height * width * length;
try{
final ImageIcon icon = new ImageIcon(new URL("http://wiki.fantasticcontraption.com/w/images/0/06/Solved.png"));
JOptionPane.showMessageDialog(this, ("The volume of the box is " +volume+" "+ measurement),"Volume", JOptionPane.PLAIN_MESSAGE, icon);
} catch (MalformedURLException ex){
System.out.println("Image Not Found!");
}
}
if (actionCommand == "Back to shape selector"){
main.dispose();
main.setVisible(false);
}
}
}
UPDATE: Looking back at it I'm now thinking the problem lies within the CBSelect Action Listener.

The thing is, since you do:
list.addActionListener(this);
// some other stuff...
button1.addActionListener(this);
button2.addActionListener(this);
Then source of the events passed to your method cube#actionPerformed can be list, button1 or button2.
So, you have you check the type of the source before casting it to anything and access its properties in the body of your actionPerformed method. You could do it like this:
final Object source = e.getSource();
String actionCommand = null;
if(source instanceof JButton) {
actionCommand = ((JButton) e.getSource()).getActionCommand();
} else if(source instanceof JComboBox<?>) {
actionCommand = ((JComboBox) e.getSource()).getSelectedItem().toString();
}
Cheers!

See if this works like you wanted:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
//#SuppressWarnings("unchecked")
public class cube extends JFrame implements ActionListener{
public static JComboBox list;
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static JTextField d;
public static String measureFinal;
public static String [] measurement = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
public static JFrame main = new JFrame("Volume of Cube");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
cube object = new cube();
}
cube(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.setPreferredSize(new Dimension(400,350));
main.add(myPanel);
a = new JTextField(3);
b = new JTextField(3);
c = new JTextField(3);
d = new JTextField(3);
JButton button1 = new JButton("Solve!");
JButton button2 = new JButton("Back to shape selector");
myPanel.add(new JLabel ("Select the unit of measurement"));
String measure[] = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
list = new JComboBox(measure);
list.setSelectedIndex(0);
list.addActionListener(this);
myPanel.add(list);
myPanel.add(new JLabel ("Enter the height of the box"));
myPanel.add(a);
myPanel.add(new JLabel ("Enter the width of the box"));
myPanel.add(b);
myPanel.add(new JLabel ("Enter the length of the box"));
myPanel.add(c);
myPanel.add(button1);
button1.addActionListener(this);
myPanel.add(button2);
button2.addActionListener(this);
main.pack();
main.setLocation(600,200);
main.setVisible(true);
}
public void CBSelect(ActionEvent e){
int temp = 0;
temp = list.getSelectedIndex();
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
measureFinal = (String)list.getSelectedItem();
if (actionCommand == "Solve!"){
double height = Double.parseDouble(a.getText());
double width = Double.parseDouble(b.getText());
double length = Double.parseDouble(c.getText());
double volume = height * width * length;
try{
final ImageIcon icon = new ImageIcon(new URL("http://wiki.fantasticcontraption.com/w/images/0/06/Solved.png"));
JOptionPane.showMessageDialog(this, ("The volume of the box is " +volume+" "+ measureFinal),"Volume", JOptionPane.PLAIN_MESSAGE, icon);
} catch (MalformedURLException ex){
System.out.println("Image Not Found!");
}
}
if (actionCommand == "Back to shape selector"){
main.dispose();
main.setVisible(false);
}
}
}

Related

A trouble with Uber Clone

Hi Guys: I´m trying with Uber Clone code and I´m using Netbeans . I have two questions:
1).- In the countryPickerForm Listing 4.12 (The Listing number is the book´s listing "Create an Uber Clone..."); Netbeans marks me an error,("Cannot find symbol variable CommonCode"), of course, in the CommonCode object, i don´t know what library to use
´´´
public class CountryPickerForm extends Form{
//#SuppressWarnings("LeakingThisInConstructor")
public CountryPickerForm(Button sourceButton, Resources Flag){
super(BoxLayout.y());
**CommonCode.initBlackTitleForm(this,"Select a Country", val-> search(val));**
Image blankIcon = Image.createImage(100, 70, 0);
´´´
2).- And the second question: What is te correct place to the Listing (5.22) "Toogling the "WhereTo?" UI when focus changes". I placed it Inside the MapForm class outside from any method, but Neatbeans marks me an error: "< identifier > expected. Ilegal start of type "
This is the code:
from.addFocusListener(new FocusListener(){
public void focusGained(Component cmp){
fromSelected.setIcon(square);
if(layer.getComponentCount()> 1){
Component c = layer.getComponentAt(1);
c.setY(getDisplayHeight());
layer.animateUnlayout(200,150,() ->{
c.remove();
revalidate();
});
}
}
public void focusLost(){
fromSelected.setIcon(circle);
}
});
to.addFocusListener(new FocusListener(){
public void focusGained(Component cmp){
fromSelected.setIcon(circle):
toSelected.setIcon(square);
showToNavigationBar(layer);
}
public void focusLost(Component cmp){
toSelecte3dsetIcon(circle);
}
});
Thanks Guys!!!!
CommonCode was somehow lost in one of the edits to the book. It's a part of the downloadable zip listed at the start of the book and should be there. This is the full listing of that class:
package com.codename1.apps.uberclone.forms;
import com.codename1.apps.uberclone.server.UserService;
import com.codename1.components.MultiButton;
import com.codename1.io.Log;
import com.codename1.ui.Button;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Command;
import com.codename1.ui.Container;
import com.codename1.ui.Display;
import com.codename1.ui.FontImage;
import com.codename1.ui.Form;
import com.codename1.ui.Graphics;
import com.codename1.ui.Image;
import com.codename1.ui.Label;
import com.codename1.ui.TextField;
import com.codename1.ui.Toolbar;
import com.codename1.ui.animations.CommonTransitions;
import com.codename1.ui.animations.Transition;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.LayeredLayout;
import com.codename1.ui.plaf.Style;
import com.codename1.util.LazyValue;
import com.codename1.util.SuccessCallback;
import java.io.IOException;
/**
* Common code for construction and initialization of various classes e.g. the side menu logic etc.
*
* #author Shai Almog
*/
public class CommonCode {
private static Image avatar;
public static Image getAvatar(SuccessCallback<Image> avatarChanged) {
if(avatar == null) {
int size = convertToPixels(10);
Image temp = Image.createImage(size, size, 0xff000000);
Graphics g = temp.getGraphics();
g.setAntiAliased(true);
g.setColor(0xffffff);
g.fillArc(0, 0, size, size, 0, 360);
Object mask = temp.createMask();
UserService.fetchAvatar(i -> {
avatar = i.fill(size, size).applyMask(mask);
avatarChanged.onSucess(avatar);
});
if(avatar != null) {
return avatar;
}
Style s = new Style();
s.setFgColor(0xc2c2c2);
s.setBgTransparency(255);
s.setBgColor(0xe9e9e9);
FontImage x = FontImage.createMaterial(FontImage.MATERIAL_PERSON, s, size);
avatar = x.fill(size, size);
if(avatar instanceof FontImage) {
avatar = ((FontImage)avatar).toImage();
}
avatar = avatar.applyMask(mask);
}
return avatar;
}
public static Image setAvatar(String imageFile) {
int size = convertToPixels(10);
Image temp = Image.createImage(size, size, 0xff000000);
Graphics g = temp.getGraphics();
g.setAntiAliased(true);
g.setColor(0xffffff);
g.fillArc(0, 0, size, size, 0, 360);
Object mask = temp.createMask();
try {
Image img = Image.createImage(imageFile);
avatar = img.fill(size, size).applyMask(mask);
} catch(IOException err) {
// this is unlikely as we just grabbed the image...
Log.e(err);
}
return avatar;
}
public static MultiButton createEntry(char icon, String title) {
MultiButton b = new MultiButton(title);
b.setUIID("Container");
b.setUIIDLine1("WhereToButtonLine1");
b.setIconUIID("WhereToButtonIcon");
FontImage.setMaterialIcon(b, icon);
return b;
}
public static MultiButton createEntry(char icon, String title, String subtitle) {
MultiButton b = new MultiButton(title);
b.setTextLine2(subtitle);
b.setUIID("Container");
b.setUIIDLine1("WhereToButtonLineNoBorder");
b.setUIIDLine2("WhereToButtonLine2");
b.setIconUIID("WhereToButtonIcon");
FontImage.setMaterialIcon(b, icon);
return b;
}
public static Label createSeparator() {
Label sep = new Label("", "WhereSeparator");
sep.setShowEvenIfBlank(true);
return sep;
}
public static void constructSideMenu(Toolbar tb) {
Button userAndAvatar = new Button("Shai Almog", "AvatarBlock");
userAndAvatar.setIcon(getAvatar(i -> userAndAvatar.setIcon(i)));
userAndAvatar.setGap(convertToPixels(3));
userAndAvatar.addActionListener(e -> new EditAccountForm().show());
tb.addComponentToSideMenu(userAndAvatar);
MultiButton uberForBusiness = new MultiButton("Do you Uber for business?");
uberForBusiness.setTextLine2("Tap to create your business profile");
uberForBusiness.setUIID("UberForBusinessBackground");
uberForBusiness.setUIIDLine1("UberForBusinessLine1");
uberForBusiness.setUIIDLine2("UberForBusinessLine2");
tb.addComponentToSideMenu(uberForBusiness);
tb.addCommandToSideMenu("Payment", null, e -> {});
tb.addCommandToSideMenu("Your Trips", null, e -> {});
tb.addCommandToSideMenu("Help", null, e -> {});
tb.addCommandToSideMenu("Free Rides", null, e -> {});
tb.addCommandToSideMenu("Settings", null, e -> new SettingsForm().show());
Button legalButton = new Button("Legal", "Legal");
Container legal = BorderLayout.centerCenterEastWest(null, new Label("v4.178.1001", "VersionNumber"), legalButton);
legal.setLeadComponent(legalButton);
legal.setUIID("SideNavigationPanel");
tb.setComponentToSideMenuSouth(legal);
}
/**
* Initializes a form with a black background title animation style
* #param f the form
*/
public static void initBlackTitleForm(Form f, String title, SuccessCallback<String> searchResults) {
Form backTo = getCurrentForm();
f.getContentPane().setScrollVisible(false);
Button back = new Button("", "TitleCommand");
removeTransitionsTemporarily(backTo);
back.addActionListener(e -> backTo.showBack());
back.getAllStyles().setFgColor(0xffffff);
FontImage.setMaterialIcon(back, FontImage.MATERIAL_ARROW_BACK);
f.setBackCommand(new Command("") {
#Override
public void actionPerformed(ActionEvent evt) {
backTo.showBack();
}
});
Container searchBack = null;
if(searchResults != null) {
Button search = new Button("", "TitleCommand");
search.getAllStyles().setFgColor(0xffffff);
FontImage.setMaterialIcon(search, FontImage.MATERIAL_SEARCH);
search.addActionListener(e -> {
});
searchBack = BorderLayout.north(
BorderLayout.centerEastWest(null, search, back));
} else {
searchBack = BorderLayout.north(
BorderLayout.centerEastWest(null, null, back));
}
Label titleLabel = new Label(title, "WhiteOnBlackTitle");
titleLabel.getAllStyles().setMarginTop(back.getPreferredH());
titleLabel.getAllStyles().setMarginUnit(Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
f.getToolbar().setTitleComponent(LayeredLayout.encloseIn(searchBack, titleLabel));
f.getAnimationManager().onTitleScrollAnimation(titleLabel.createStyleAnimation("WhiteOnBlackTitleLeftMargin", 200));
f.setTransitionInAnimator(CommonTransitions.createCover(CommonTransitions.SLIDE_VERTICAL, false, 300));
f.setTransitionOutAnimator(CommonTransitions.createUncover(CommonTransitions.SLIDE_VERTICAL, true, 300));
}
public static void removeTransitionsTemporarily(final Form f) {
final Transition originalOut = f.getTransitionOutAnimator();
final Transition originalIn = f.getTransitionInAnimator();
f.setTransitionOutAnimator(CommonTransitions.createEmpty());
f.setTransitionInAnimator(CommonTransitions.createEmpty());
f.addShowListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
f.setTransitionOutAnimator(originalOut);
f.setTransitionInAnimator(originalIn);
f.removeShowListener(this);
}
});
}
}
The second listing appears in MapForm in showNavigationToolbar. This code goes through some additional refactoring later on and looks like this:
void showNavigationToolbar() {
final Container layer = getLayeredPane(MapForm.class, true);
final Container pinLayer = createPinLayer(layer);
Button back = new Button("", "TitleCommand");
FontImage.setMaterialIcon(back, FontImage.MATERIAL_ARROW_BACK);
CompletionContainer cc = new CompletionContainer();
AutoCompleteAddressInput from = new AutoCompleteAddressInput("Current Location", "From", layer, cc);
AutoCompleteAddressInput to = new AutoCompleteAddressInput("", "Where To?", layer, cc);
from.setCurrentLocation(LocationService.getCurrentLocation());
Image circle = createCircle();
Label fromSelected = new Label(circle);
Label toSelected = new Label(square);
SearchService.nameMyCurrentLocation(LocationService.getCurrentLocation(), name -> from.setTextNoEvent(name));
to.requestFocus();
lastFocused = to;
from.addFocusListener(createFromFocusListener(fromSelected, from, circle));
to.addFocusListener(createToFocusListener(fromSelected, circle, toSelected, to));
addMapListener((source, zoom, center) -> onMapChangeEvent(center));
Container navigationToolbar = BoxLayout.encloseY(back,
BorderLayout.centerCenterEastWest(from, null, fromSelected),
BorderLayout.centerCenterEastWest(to, null, toSelected)
);
navigationToolbar.setUIID("WhereToToolbar");
navigationToolbar.getUnselectedStyle().setBgPainter((g1, rect) ->
paintWhereToToolbarBackground(g1, layer, rect, fromSelected, circle, toSelected)
);
cc.addCompletionListener(e ->
onCompletionEvent(to, from, pinLayer, navigationToolbar, layer));
back.addActionListener(e ->
onBackFromNavigation(pinLayer, navigationToolbar, layer));
layer.add(NORTH, navigationToolbar);
navigationToolbar.setWidth(getDisplayWidth());
navigationToolbar.setHeight(getPreferredH());
navigationToolbar.setY(-navigationToolbar.getHeight());
getAnimationManager().addAnimation(layer.createAnimateLayout(200),
() -> cc.showCompletionBar(layer));
}
private FocusListener createToFocusListener(final Label fromSelected, Image circle, final Label toSelected, AutoCompleteAddressInput to) {
return new FocusListener() {
#Override
public void focusGained(Component cmp) {
fromSelected.setIcon(circle);
toSelected.setIcon(square);
lastFocused = to;
}
#Override
public void focusLost(Component cmp) {
toSelected.setIcon(circle);
}
};
}
private FocusListener createFromFocusListener(final Label fromSelected, AutoCompleteAddressInput from, Image circle) {
return new FocusListener() {
#Override
public void focusGained(Component cmp) {
fromSelected.setIcon(square);
lastFocused = from;
}
#Override
public void focusLost(Component cmp) {
fromSelected.setIcon(circle);
}
};
}

iOS save to storage issue

I've an issue while trying to save an image to the Storage in iOS. Image is downloaded but not saved.
The code is:
Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
TreeModel tm = new TreeModel() {
#Override
public Vector getChildren(Object parent) {
String[] files;
if (parent == null) {
files = FileSystemStorage.getInstance().getRoots();
return new Vector<Object>(Arrays.asList(files));
} else {
try {
files = FileSystemStorage.getInstance().listFiles((String) parent);
} catch (IOException err) {
Log.e(err);
files = new String[0];
}
}
String p = (String) parent;
Vector result = new Vector();
for (String s : files) {
result.add(p + s);
}
return result;
}
#Override
public boolean isLeaf(Object node) {
return !FileSystemStorage.getInstance().isDirectory((String) node);
}
};
Command tree = new Command("Show tree") {
#Override
public void actionPerformed(ActionEvent evt) {
Form treeForm = new Form("Tree", new BorderLayout());
Tree t = new Tree(tm) {
#Override
protected String childToDisplayLabel(Object child) {
String n = (String) child;
int pos = n.lastIndexOf("/");
if (pos < 0) {
return n;
}
return n.substring(pos);
}
};
treeForm.add(BorderLayout.CENTER, t);
Command back = new Command("Back") {
#Override
public void actionPerformed(ActionEvent evt) {
hi.showBack();
}
};
Button backButton = new Button(back);
treeForm.add(BorderLayout.SOUTH, backButton);
treeForm.show();
}
};
hi.getToolbar().addCommandToOverflowMenu(tree);
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
String photoURL = "https://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/400px-AGameOfThrones.jpg";
StringBuilder fsPath = new StringBuilder(FileSystemStorage.getInstance().getAppHomePath());
fsPath.append("400px-AGameOfThrones.jpg");
URLImage background = URLImage.createToStorage(placeholder, fsPath.toString(), photoURL);
background.fetch();
Style stitle = hi.getToolbar().getTitleComponent().getUnselectedStyle();
stitle.setBgImage(background);
stitle.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
stitle.setPaddingUnit(Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
stitle.setPaddingTop(15);
SpanButton credit = new SpanButton("Link");
credit.addActionListener((e) -> Display.getInstance().execute("https://awoiaf.westeros.org/index.php/A_Game_of_Thrones"));
hi.add(new SpanLabel("A")).
add(new Label("B", "Heading")).
add(credit);
ComponentAnimation title = hi.getToolbar().getTitleComponent().createStyleAnimation("Title", 200);
hi.getAnimationManager().onTitleScrollAnimation(title);
hi.show();
Which was taken from https://www.codenameone.com/javadoc/com/codename1/ui/URLImage.html
The tree is only to see if the image was saved in the Storage.
You are mixing Storage & FileSystemStorage which are very different things see this.
You can use storage which is a flat set of "files" and that's what URLImage.createToStorage does. But then you need to use the Storage API to work with that and it might not be visible in the FileSystemStorage API.
Alternatively you might be looking for URLImage.createToFileSystem().

How to design multipane with 3 fragment using Android-PanesLibrary?

Good Day Developers,
I already implement this fantastic library called "Android-PanesLibrary" by Kenrick Rilee. and what i want to achive is something like this.
But i end up doing like this :
my first problem if in showDetails method i delete the comment symbol, it will showing up an error. but if i make the method empty, it will run just like the second image.
my objective is how can this be done just using string array data?
Any ideas or help would be greatly appreciated.
Environment : Windows 7, Android Studio, Genymotion.
This is MainMenuFragment.java :
public class MainMenuFragment extends android.app.ListFragment {
private static int sExampleNum = 0;
protected final String TAG = "mainmenuFragment" ;
#ViewById(R.id.menu_listview)
protected ListView menuListView ;
private View parentView;
int mCurCheckPosition = 0;
public MainMenuFragment() {
super();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Resources res = getResources();
String [] mainmenulistview = res.getStringArray(R.array.listview_main_menu);
ArrayAdapter<String> connectArrayToListView = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_activated_1,mainmenulistview);
setListAdapter(connectArrayToListView);
if (savedInstanceState != null) {
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
// if I un-comment on method bellow, it will result an error.
void showDetails(int index) {
//mCurCheckPosition = index;
//getListView().setItemChecked(index, true);
//PCDesktopFragment_ pcDesktop = (PCDesktopFragment_) getFragmentManager().findFragmentById(R.id.sub_one_fragment);
//if (pcDesktop == null || pcDesktop.getShownIndex() != index) {
// welder_pipe_reg = PCDesktopFragment_.newInstance(index);
// android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
// ft.replace(R.id.sub_one_fragment, pcDesktop);
// ft.commit();
//}
}
}
and then i already create a class called PCDesktopFragment.java that extends ListFragment (this should be showing up on second fragment using listfragment)
#EFragment(R.layout.sub_one_menu)
public class PCDesktopFragment_ extends ListFragment {
View v;
public static int i;
public static PCDesktopFragment_ newInstance(int index){
PCDesktopFragment_ f = new PCDesktopFragment_();
Bundle args = new Bundle();
args.putInt("index", index);
index = i;
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inflater.inflate(R.layout.sub_one_menu, container, false);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (i == 0) {
String [] sub_a = {"Test1","Test2"};
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, sub_a));
}
}
//#ItemClick(R.id.sub_one_listview)
//protected void handleDomainClick(int position) {
// Fragment f = null ;
// if (position == 0) {
// f = new PCDesktopFragment_();
// }
// Activity a = getActivity();
// if (f != null && a != null && a instanceof FragmentLauncher)
// ((FragmentLauncher) a).addFragment(this, f);
//}
}

how to use pos in MigLayout?

This is my code:
public class InfoPanel extends JPanel{
... ... ...
... ... ...
public InfoPanel(){
... ... ...
... ... ...
MigLayout lManager = new MigLayout();
setLayout(lManager);
add(lblName,new CC().pos("50", "80"));
add(txtName, new CC().pos("90","80").width("170").wrap().gap("r"));
add(lblOccupation,"pos 20 100");
add(txtOccupation,"pos 91 100,w 170,wrap,gap r");
and it has the right output.
but I want to use any built in code for calculate pos() for txtName, txtOccupation.
can anybody help me to do that.
From the image as template:
public class MigLayoutTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MigLayoutTest().start();
}
});
}
private void start() {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new MigLayout("wrap 4, debug", "[][fill, grow 1][][fill, grow 4]", ""));
//Declaration
JLabel nameLabel, employmenLabel, ssnLabel, taxIDLabel;
JTextField nameField, ssnField, taxIDField;
JComboBox<String> employmentBox;
JCheckBox checkbox;
JButton save, cancel, upload;
JPanel imagePlaceholder;
//Initialization
nameLabel = new JLabel("Name");
employmenLabel = new JLabel("Employment");
ssnLabel = new JLabel("Social Security Number");
taxIDLabel = new JLabel("tax ID");
nameField = new JTextField();
ssnField = new JTextField();
taxIDField = new JTextField();
save = new JButton("Save");
cancel = new JButton("Cancel");
upload = new JButton("Upload");
checkbox = new JCheckBox("Checkbox");
imagePlaceholder = new JPanel();
employmentBox = new JComboBox<String>();
//Some editing
imagePlaceholder.setBackground(Color.GREEN);
employmentBox.addItem("Some");
employmentBox.addItem("items");
employmentBox.addItem("to");
employmentBox.addItem("fill");
employmentBox.addItem("this");
//Adding to contentPane
contentPane.add(nameLabel, "alignx right");
contentPane.add(nameField, "");
contentPane.add(ssnLabel, "alignx right");
contentPane.add(ssnField, "");
contentPane.add(employmenLabel, "alignx right");
contentPane.add(employmentBox, "");
contentPane.add(upload, "");
contentPane.add(imagePlaceholder, "spany 3, grow");
contentPane.add(checkbox, "split 2");
contentPane.add(taxIDLabel, "");
contentPane.add(taxIDField, "wrap");
contentPane.add(save, "");
contentPane.add(cancel, "growx 0, wrap");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Change length of JTextPane array

I want to create an array of JTextPane that it's size and values change through out the execution of my program, such as arrayList.
Is it possible to do it similar to an arrayList?
I've two JFrames. In the first frame I have a JList with about 100 items.
After selecting any of the items I want to paste them per Drag&Drop to the second frame.
The second frame has a GridBagLayout, hence I want to paste each selected item to an
array of JTextPane after dropping the items.
I want to use JTextPane because I want to format the selected text.
now I found a solution and my code seems to work:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class RefreshPanel {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JTextPane [] textPane;
private JScrollPane scrollbar;
private ArrayList arrayList = new ArrayList();
private JButton newItem = new JButton("new");
private int counter=0;
private GridBagLayout gbl = new GridBagLayout();
RefreshPanel() {
panel.setBackground(Color.WHITE);
panel.setLayout(gbl);
panel.setPreferredSize(new Dimension(100,50));
scrollbar = new JScrollPane(panel);
addButtonListener();
createFrame();
} //constructor
public void addButtonListener() {
newItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
arrayList.add("data");
textPane = new JTextPane[arrayList.size()];
for(int i=0;i<arrayList.size();i++) {
textPane[i]=new JTextPane();
textPane[i].setText((String) arrayList.get(i));
addComponent(panel, gbl, textPane[i], 1, counter, 1, 1,1,1);
counter++;
}
}
});
}
public void addComponent(Container cont,
GridBagLayout gbl,
Component c,
int x, int y,
int width, int height,
double weightx, double weighty) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = width; gbc.gridheight = height;
gbc.weightx = weightx; gbc.weighty = weighty;
gbl.setConstraints( c, gbc );
cont.add( c );
}
public void createFrame() {
frame.getContentPane().setLayout(new FlowLayout());
frame.add(scrollbar);
frame.add(newItem);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300,300));
frame.setVisible(true);
}
public static void main(String [] args) {
new RefreshPanel();
}
}
But there is a little something which won't work: the items appears when I change the size of the frame, but I don't know why... any ideas?
thanks!

Resources