Search Results

Search found 31 results on 2 pages for 'instantiationexception'.

Page 1/2 | 1 2  | Next Page >

  • Why am I having this InstantiationException in Java when accessing final local variables?

    - by Oscar Reyes
    I was playing with some code to make a "closure like" construct ( not working btw ) Everything looked fine but when I tried to access a final local variable in the code, the exception InstantiationException is thrown. If I remove the access to the local variable either by removing it altogether or by making it class attribute instead, no exception happens. The doc says: InstantiationException Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to: - the class object represents an abstract class, an interface, an array class, a primitive type, or void - the class has no nullary constructor What other reason could have caused this problem? Here's the code. comment/uncomment the class attribute / local variable to see the effect (lines:5 and 10 ). import javax.swing.*; import java.awt.event.*; import java.awt.*; class InstantiationExceptionDemo { //static JTextField field = new JTextField();// works if uncommented public static void main( String [] args ) { JFrame frame = new JFrame(); JButton button = new JButton("Click"); final JTextField field = new JTextField();// fails if uncommented button.addActionListener( new _(){{ System.out.println("click " + field.getText()); }}); frame.add( field ); frame.add( button, BorderLayout.SOUTH ); frame.pack();frame.setVisible( true ); } } class _ implements ActionListener { public void actionPerformed( ActionEvent e ){ try { this.getClass().newInstance(); } catch( InstantiationException ie ){ throw new RuntimeException( ie ); } catch( IllegalAccessException ie ){ throw new RuntimeException( ie ); } } } Is this a bug in Java? edit Oh, I forgot, the stacktrace ( when thrown ) is: Caused by: java.lang.InstantiationException: InstantiationExceptionDemo$1 at java.lang.Class.newInstance0(Class.java:340) at java.lang.Class.newInstance(Class.java:308) at _.actionPerformed(InstantiationExceptionDemo.java:25)

    Read the article

  • when to use the abstract factory pattern?

    - by hguser
    Hi: I want to know when we need to use the abstract factory pattern. Here is an example,I want to know if it is necessary. The UML THe above is the abstract factory pattern, it is recommended by my classmate. THe following is myown implemention. I do not think it is necessary to use the pattern. And the following is some core codes: package net; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class Test { public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { DaoRepository dr=new DaoRepository(); AbstractDao dao=dr.findDao("sql"); dao.insert(); } } class DaoRepository { Map<String, AbstractDao> daoMap=new HashMap<String, AbstractDao>(); public DaoRepository () throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { Properties p=new Properties(); p.load(DaoRepository.class.getResourceAsStream("Test.properties")); initDaos(p); } public void initDaos(Properties p) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String[] daoarray=p.getProperty("dao").split(","); for(String dao:daoarray) { AbstractDao ad=(AbstractDao)Class.forName(dao).newInstance(); daoMap.put(ad.getID(),ad); } } public AbstractDao findDao(String id) {return daoMap.get(id);} } abstract class AbstractDao { public abstract String getID(); public abstract void insert(); public abstract void update(); } class SqlDao extends AbstractDao { public SqlDao() {} public String getID() {return "sql";} public void insert() {System.out.println("sql insert");} public void update() {System.out.println("sql update");} } class AccessDao extends AbstractDao { public AccessDao() {} public String getID() {return "access";} public void insert() {System.out.println("access insert");} public void update() {System.out.println("access update");} } And the content of the Test.properties is just one line: dao=net.SqlDao,net.SqlDao So any ont can tell me if this suitation is necessary?

    Read the article

  • JSP cant find bean Class using "" modifiers

    - by Ravana
    Hey I'm using Netbeans for my IDE and I'm getting an error when I try to run my EJB program. I get an error when I declare and give the path of the class in my JSP to a bean. <jsp:useBean id="book" class="BookBean.Book" scope="application" /> <jsp:setProperty name="book" property="*" /> When I run the program I get this error javax.servlet.ServletException: java.lang.InstantiationException: class BookBean.Book : java.lang.IllegalAccessException: Class java.beans.Beans can not access a member of class BookBean.Book with modifiers "" and java.lang.InstantiationException: class BookBean.Book : java.lang.IllegalAccessException: Class java.beans.Beans can not access a member of class BookBean.Book with modifiers "" I removed the "" and put in '' to see if that works, but it doesn't. Any idea? I also put a breakpoint there and it def. is the root of the problem. Thanks.

    Read the article

  • Is it a missing implementation with JPA implementation of hibernate??

    - by Jegan
    Hi all, On my way in understanding the transaction-type attribute of persistence.xml, i came across an issue / discrepency between hibernate-core and JPA-hibernate which looks weird. I am not pretty sure whether it is a missing implementation with JPA of hibernate. Let me post the comparison between the outcome of JPA implementation and the hibernate implementation of the same concept. Environment Eclipse 3.5.1 JSE v1.6.0_05 Hibernate v3.2.3 [for hibernate core] Hibernate-EntityManger v3.4.0 [for JPA] MySQL DB v5.0 Issue 1.Hibernate core package com.expt.hibernate.core; import java.io.Serializable; public final class Student implements Serializable { private int studId; private String studName; private String studEmailId; public Student(final String studName, final String studEmailId) { this.studName = studName; this.studEmailId = studEmailId; } public int getStudId() { return this.studId; } public String getStudName() { return this.studName; } public String getStudEmailId() { return this.studEmailId; } private void setStudId(int studId) { this.studId = studId; } private void setStudName(String studName) { this.studName = stuName; } private void setStudEmailId(int studEmailId) { this.studEmailId = studEmailId; } } 2. JPA implementaion of Hibernate package com.expt.hibernate.jpa; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "Student_Info") public final class Student implements Serializable { @Id @GeneratedValue @Column(name = "STUD_ID", length = 5) private int studId; @Column(name = "STUD_NAME", nullable = false, length = 25) private String studName; @Column(name = "STUD_EMAIL", nullable = true, length = 30) private String studEmailId; public Student(final String studName, final String studEmailId) { this.studName = studName; this.studEmailId = studEmailId; } public int getStudId() { return this.studId; } public String getStudName() { return this.studName; } public String getStudEmailId() { return this.studEmailId; } } Also, I have provided the DB configuration properties in the associated hibernate-cfg.xml [in case of hibernate core] and persistence.xml [in case of JPA (hibernate entity manager)]. create a driver and perform add a student and query for the list of students and print their details. Then the issue comes when you run the driver program. Hibernate core - output Exception in thread "main" org.hibernate.InstantiationException: No default constructor for entity: com.expt.hibernate.core.Student at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:84) at org.hibernate.tuple.PojoInstantiator.instantiate(PojoInstantiator.java:100) at org.hibernate.tuple.entity.AbstractEntityTuplizer.instantiate(AbstractEntityTuplizer.java:351) at org.hibernate.persister.entity.AbstractEntityPersister.instantiate(AbstractEntityPersister.java:3604) .... .... This exception is flashed when the driver is executed for the first time itself. JPA Hibernate - output First execution of the driver on a fresh DB provided the following output. DEBUG SQL:111 - insert into student.Student_Info (STUD_EMAIL, STUD_NAME) values (?, ?) 17:38:24,229 DEBUG SQL:111 - select student0_.STUD_ID as STUD1_0_, student0_.STUD_EMAIL as STUD2_0_, student0_.STUD_NAME as STUD3_0_ from student.Student_Info student0_ student list size == 1 1 || Jegan || [email protected] second execution of the driver provided the following output. DEBUG SQL:111 - insert into student.Student_Info (STUD_EMAIL, STUD_NAME) values (?, ?) 17:40:25,254 DEBUG SQL:111 - select student0_.STUD_ID as STUD1_0_, student0_.STUD_EMAIL as STUD2_0_, student0_.STUD_NAME as STUD3_0_ from student.Student_Info student0_ Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.InstantiationException: No default constructor for entity: com.expt.hibernate.jpa.Student at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614) at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:76) at driver.StudentDriver.main(StudentDriver.java:43) Caused by: org.hibernate.InstantiationException: No default constructor for entity: com.expt.hibernate.jpa.Student .... .... Could anyone please let me know if you have encountered this sort of inconsistency? Also, could anyone please let me know if the issue is a missing implementation with JPA-Hibernate? ~ Jegan

    Read the article

  • Examples of bad variable names and reasons [on hold]

    - by user470184
    I'll start with a class in the jdk package : public final class Sdp { should be : public final class SocketsDirectProtocol { Sdp is class name, this is ambigious, should be : Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null); should be : Class<?> clazz = Class.forName("java.net.SdpSocketImpl", true, null); cl is ambiguous private static void setAccessible(final AccessibleObject o) { should be : private static void setAccessible(final AccessibleObject accessibleObject) { There are various other examples in this class, do you have similar and/or differing examples of variables that were named badly ? package com.oracle.net; public final class Sdp { private Sdp() { } /** * The package-privage ServerSocket(SocketImpl) constructor */ private static final Constructor<ServerSocket> serverSocketCtor; static { try { serverSocketCtor = (Constructor<ServerSocket>) ServerSocket.class.getDeclaredConstructor(SocketImpl.class); setAccessible(serverSocketCtor); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } /** * The package-private SdpSocketImpl() constructor */ private static final Constructor<SocketImpl> socketImplCtor; static { try { Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null); socketImplCtor = (Constructor<SocketImpl>)cl.getDeclaredConstructor(); setAccessible(socketImplCtor); } catch (ClassNotFoundException e) { throw new AssertionError(e); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } private static void setAccessible(final AccessibleObject o) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { o.setAccessible(true); return null; } }); } /** * SDP enabled Socket. */ private static class SdpSocket extends Socket { SdpSocket(SocketImpl impl) throws SocketException { super(impl); } } /** * Creates a SDP enabled SocketImpl */ private static SocketImpl createSocketImpl() { try { return socketImplCtor.newInstance(); } catch (InstantiationException x) { throw new AssertionError(x); } catch (IllegalAccessException x) { throw new AssertionError(x); } catch (InvocationTargetException x) { throw new AssertionError(x); } } /** * Creates an unconnected and unbound SDP socket. The {@code Socket} is * associated with a {@link java.net.SocketImpl} of the system-default type. * * @return a new Socket * * @throws UnsupportedOperationException * If SDP is not supported * @throws IOException * If an I/O error occurs */ public static Socket openSocket() throws IOException { SocketImpl impl = createSocketImpl(); return new SdpSocket(impl); } /** * Creates an unbound SDP server socket. The {@code ServerSocket} is * associated with a {@link java.net.SocketImpl} of the system-default type. * * @return a new ServerSocket * * @throws UnsupportedOperationException * If SDP is not supported * @throws IOException * If an I/O error occurs */ public static ServerSocket openServerSocket() throws IOException { // create ServerSocket via package-private constructor SocketImpl impl = createSocketImpl(); try { return serverSocketCtor.newInstance(impl); } catch (IllegalAccessException x) { throw new AssertionError(x); } catch (InstantiationException x) { throw new AssertionError(x); } catch (InvocationTargetException x) { Throwable cause = x.getCause(); if (cause instanceof IOException) throw (IOException)cause; if (cause instanceof RuntimeException) throw (RuntimeException)cause; throw new RuntimeException(x); } } /** * Opens a socket channel to a SDP socket. * * <p> The channel will be associated with the system-wide default * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}. * * @return a new SocketChannel * * @throws UnsupportedOperationException * If SDP is not supported or not supported by the default selector * provider * @throws IOException * If an I/O error occurs. */ public static SocketChannel openSocketChannel() throws IOException { FileDescriptor fd = SdpSupport.createSocket(); return sun.nio.ch.Secrets.newSocketChannel(fd); } /** * Opens a socket channel to a SDP socket. * * <p> The channel will be associated with the system-wide default * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}. * * @return a new ServerSocketChannel * * @throws UnsupportedOperationException * If SDP is not supported or not supported by the default selector * provider * @throws IOException * If an I/O error occurs */ public static ServerSocketChannel openServerSocketChannel() throws IOException { FileDescriptor fd = SdpSupport.createSocket(); return sun.nio.ch.Secrets.newServerSocketChannel(fd); } }

    Read the article

  • SAX parser does not resolve filename

    - by phantom-99w
    Another day, another strange error with SAX, Java, and friends. I need to iterate over a list of File objects and pass them to a SAX parser. However, the parser fails because of an IOException. However, the various File object methods confirm that the file does indeed exist. The output which I get: 11:53:57.838 [MainThread] DEBUG DefaultReactionFinder - C:\project\trunk\application\config\reactions\TestReactions.xml 11:53:57.841 [MainThread] ERROR DefaultReactionFinder - C:\project\trunk\application\config\reactions\null (The system cannot find the file specified) So the problem is obviously that null in the second line. I've tried nearly all variations of passing the file as a parameter to the parser, including as a String (both from getAbsolutePath() and entered by hand), as a URI and, even more weirdly, as a FileInputStream (for this I get the same error, except that the entire relative path gets reported as null, so C:\project\trunk\null). All that I can think of is that the SAXParserFactory is incorrectly configured. I have no idea what is wrong, though. Here is the code concerned: SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); try { parser = factory.newSAXParser(); } catch (ParserConfigurationException e) { throw new InstantiationException("Error configuring an XML parser. Given error message: \"" + e.getMessage() + "\"."); } catch (SAXException e) { throw new InstantiationException("Error creating a SAX parser. Given error message: \"" + e.getMessage() + "\"."); } ... for (File f : fileLister.getFileList()) { logger.debug(f.getAbsolutePath()); try { parser.parse(f, new ReactionHandler(input)); //FileInputStream fs = new FileInputStream(f); //parser.parse(fs, new ReactionHandler(input)); //fs.close(); } catch (IOException e) { logger.error(e.getMessage()); throw new ReactionNotFoundException("An error occurred processing file \"" + f + "\"."); } ... } I have made no special provisions to provide a custom SAX parser implementation: I use the system default. Any help would be greatly appreciated!

    Read the article

  • Getting default value for java primitive types

    - by ripper234
    I have a java primitive type at hand: Class c = int.class; // or long.class, or boolean.class I'd like to get a 'default value' for this class - specifically the value is assigned to fields of this type if they are not initialized. E.g., '0' for a number, 'false' for a boolean. Is there a generic way to do this? I tried c.newInstance() But I'm getting an InstantiationException, and not a default instance.

    Read the article

  • How to get Rid of this strange Border on JButton in Windows System look and Feel?

    - by Timo J.
    I have a small Problem with the Layout of my Frame. As You could see in a picture (if i would have my 10 rep ;) ) there is a small Border around my JButtons. I'm already searching long time on this topic and i finally decided to ask for help, i'm just out of ideas. Is this Part of the Windows Theme which shouldn't be changed? It just doesnt fit into my current Layout, as I'm Listing TextBoxes and Comboboxes on Page Axis without any Border. I would be very happy if there is solution for this issue. Thanks in advance! EDIT 1: I do not mean the Focus Border. I like the Highlighting of a focussed Element. What i mean is the Border in the Background Color which causes a small distance of background-colored space beetween a JButton and another Element. (Picture on Personnal Webspace: http://tijamocobs.no-ip.biz/border_jbutton.png) EDIT 2: I'm using the Windows 8 Look and Feel but saw this Problem on Windows 7 Look and Feel, too. short Example import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class TestFrame extends JFrame { public TestFrame(){ setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)); for (int i = 0; i < 3; i++) { JButton btn = new JButton("."); // not working: // btn.setBorder(null); // btn.setBorder(BorderFactory.createEmptyBorder()); add(btn); } pack(); } public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); TestFrame tiss = new TestFrame(); tiss.setVisible(true); } } Example Code (long version): import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class TestFrame extends JFrame { public TestFrame(){ JPanel muh = new JPanel(); muh.setLayout(new BoxLayout(muh, BoxLayout.PAGE_AXIS)); for (int i = 0; i < 3; i++) { Container c = new JPanel(); c.setLayout(new BoxLayout(c, BoxLayout.LINE_AXIS)); Box bx = Box.createHorizontalBox(); final String[] tmp = {"anything1","anything2"}; JComboBox<String> cmbbx = new JComboBox<String>(tmp); cmbbx.setMinimumSize(new Dimension(80,20)); bx.add(cmbbx); JButton btn = new JButton("."); btn.setMinimumSize(new Dimension(cmbbx.getMinimumSize().height,cmbbx.getMinimumSize().height)); btn.setPreferredSize(new Dimension(30,30)); btn.setMaximumSize(new Dimension(30,30)); bx.add(btn); c.setMaximumSize(new Dimension(Integer.MAX_VALUE,30)); c.add(new JLabel("Just anything")); c.add(bx); muh.add(c); } add(muh,BorderLayout.CENTER); pack(); } public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); TestFrame tiss = new TestFrame(); tiss.setVisible(true); } }

    Read the article

  • Single Table Per Class Hierarchy with an abstract superclass using Hibernate Annotations

    - by Andy Hull
    I have a simple class hierarchy, similar to the following: @Entity @Table(name="animal") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="animal_type", discriminatorType=DiscriminatorType.STRING) public abstract class Animal { } @Entity @DiscriminatorValue("cat") public class Cat extends Animal { } @Entity @DiscriminatorValue("dog") public class Dog extends Animal { } When I query "from Animal" I get this exception: "org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: Animal" If I make Animal concrete, and add a dummy discriminator... such as @DiscriminatorValue("animal")... my query returns my cats and dogs as instances of Animals. I remember this being trivial with HBM based mappings but I think I'm missing something when using annotations. Can anyone help? Thanks!

    Read the article

  • [Java] Type safety: Unchecked cast from Object

    - by Matthew
    Hi, I try to cast an object to my Action class, but it results in a warning: Type safety: Unchecked cast from Object to Action<ClientInterface> Action<ClientInterface> action = null; try { Object o = c.newInstance(); if (o instanceof Action<?>) { action = (Action<ClientInterface>) o; } else { // TODO 2 Auto-generated catch block throw new InstantiationException(); } [...] Thank you for any help

    Read the article

  • Accessing constructor from abstract base class with reflection

    - by craesh
    Hi! I'm playing around with Java's Reflection. I have an abstract class Base with a constructor. abstract class Base { public Base( String foo ) { // do some magic } } I have some further classes extending Base. They don't contain much logic. I want to instantiate them with Base's constructor, without having to write some proxy contructors in those derived classes. And of course, I want to instantiate those derived classes with Reflection. Say: Class cls = SomeDerivedClass.class; Constructor constr; constr = cls.getConstructor( new Class[] { String.class } ); // will return null Class clsBase = Base.class; constr = clsBase.getConstructor( new Class[] { String.class } ); // ok Base obj = (Base) constr.newInstance( new Object[] { "foo" } ); // will throw InstantiationException because it belongs to an abstract class Any ideas, how I can instantiate a derived class with Base's constructor? Or must I declare those dumb proxy constructors?

    Read the article

  • Android App Crashes On Second Run

    - by user1091286
    My app runs fine on first run. On the Menu I added two choices options and quit. options which set up a new intent who goes to a PreferenceActivity and quit which simply call: "android.os.Process.killProcess(android.os.Process.myPid());" On the second time I run my app (after I quit from inside the emulator) it crashes.. Ideas? the menu is called by the foolowing code: @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu , menu); return true; } - @Override public boolean onOptionsItemSelected(MenuItem item) { // Set up a new intent between the updater service and the main screen Intent options = new Intent(this, OptionsScreenActivity.class); // Switch case on the options switch (item.getItemId()) { case R.id.options: startActivity(options); return true; case R.id.quit: android.os.Process.killProcess(android.os.Process.myPid()); return true; default: return false; } Code for SeekBarPreference: package com.testapp.logic; import com.testapp.R; import android.content.Context; import android.content.res.TypedArray; import android.preference.Preference; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class SeekBarPreference extends Preference implements OnSeekBarChangeListener { private final String TAG = getClass().getName(); private static final String ANDROIDNS="http://schemas.android.com/apk/res/android"; private static final String PREFS="com.testapp.logic"; private static final int DEFAULT_VALUE = 5; private int mMaxValue = 100; private int mMinValue = 1; private int mInterval = 1; private int mCurrentValue; private String mUnitsLeft = ""; private String mUnitsRight = ""; private SeekBar mSeekBar; private TextView mStatusText; public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); initPreference(context, attrs); } public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initPreference(context, attrs); } private void initPreference(Context context, AttributeSet attrs) { setValuesFromXml(attrs); mSeekBar = new SeekBar(context, attrs); mSeekBar.setMax(mMaxValue - mMinValue); mSeekBar.setOnSeekBarChangeListener(this); } private void setValuesFromXml(AttributeSet attrs) { mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 100); mMinValue = attrs.getAttributeIntValue(PREFS, "min", 0); mUnitsLeft = getAttributeStringValue(attrs, PREFS, "unitsLeft", ""); String units = getAttributeStringValue(attrs, PREFS, "units", ""); mUnitsRight = getAttributeStringValue(attrs, PREFS, "unitsRight", units); try { String newInterval = attrs.getAttributeValue(PREFS, "interval"); if(newInterval != null) mInterval = Integer.parseInt(newInterval); } catch(Exception e) { Log.e(TAG, "Invalid interval value", e); } } private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) { String value = attrs.getAttributeValue(namespace, name); if(value == null) value = defaultValue; return value; } @Override protected View onCreateView(ViewGroup parent){ RelativeLayout layout = null; try { LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); layout = (RelativeLayout)mInflater.inflate(R.layout.seek_bar_preference, parent, false); } catch(Exception e) { Log.e(TAG, "Error creating seek bar preference", e); } return layout; } @Override public void onBindView(View view) { super.onBindView(view); try { // move our seekbar to the new view we've been given ViewParent oldContainer = mSeekBar.getParent(); ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer); if (oldContainer != newContainer) { // remove the seekbar from the old view if (oldContainer != null) { ((ViewGroup) oldContainer).removeView(mSeekBar); } // remove the existing seekbar (there may not be one) and add ours newContainer.removeAllViews(); newContainer.addView(mSeekBar, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } catch(Exception ex) { Log.e(TAG, "Error binding view: " + ex.toString()); } updateView(view); } /** * Update a SeekBarPreference view with our current state * @param view */ protected void updateView(View view) { try { RelativeLayout layout = (RelativeLayout)view; mStatusText = (TextView)layout.findViewById(R.id.seekBarPrefValue); mStatusText.setText(String.valueOf(mCurrentValue)); mStatusText.setMinimumWidth(30); mSeekBar.setProgress(mCurrentValue - mMinValue); TextView unitsRight = (TextView)layout.findViewById(R.id.seekBarPrefUnitsRight); unitsRight.setText(mUnitsRight); TextView unitsLeft = (TextView)layout.findViewById(R.id.seekBarPrefUnitsLeft); unitsLeft.setText(mUnitsLeft); } catch(Exception e) { Log.e(TAG, "Error updating seek bar preference", e); } } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newValue = progress + mMinValue; if(newValue > mMaxValue) newValue = mMaxValue; else if(newValue < mMinValue) newValue = mMinValue; else if(mInterval != 1 && newValue % mInterval != 0) newValue = Math.round(((float)newValue)/mInterval)*mInterval; // change rejected, revert to the previous value if(!callChangeListener(newValue)){ seekBar.setProgress(mCurrentValue - mMinValue); return; } // change accepted, store it mCurrentValue = newValue; mStatusText.setText(String.valueOf(newValue)); persistInt(newValue); } public void onStartTrackingTouch(SeekBar seekBar) {} public void onStopTrackingTouch(SeekBar seekBar) { notifyChanged(); } @Override protected Object onGetDefaultValue(TypedArray ta, int index){ int defaultValue = ta.getInt(index, DEFAULT_VALUE); return defaultValue; } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if(restoreValue) { mCurrentValue = getPersistedInt(mCurrentValue); } else { int temp = 0; try { temp = (Integer)defaultValue; } catch(Exception ex) { Log.e(TAG, "Invalid default value: " + defaultValue.toString()); } persistInt(temp); mCurrentValue = temp; } } } Logcat: E/AndroidRuntime( 4525): FATAL EXCEPTION: main E/AndroidRuntime( 4525): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ui.testapp/com.logic.testapp.SeekBarPreferen ce}: java.lang.InstantiationException: can't instantiate class com.logic.testapp.SeekBarPreference; no empty constructor E/AndroidRuntime( 4525): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879) E/AndroidRuntime( 4525): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980) E/AndroidRuntime( 4525): at android.app.ActivityThread.access$600(ActivityThread.java:122) E/AndroidRuntime( 4525): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146) E/AndroidRuntime( 4525): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime( 4525): at android.os.Looper.loop(Looper.java:137) E/AndroidRuntime( 4525): at android.app.ActivityThread.main(ActivityThread.java:4340) E/AndroidRuntime( 4525): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 4525): at java.lang.reflect.Method.invoke(Method.java:511) E/AndroidRuntime( 4525): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) E/AndroidRuntime( 4525): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) E/AndroidRuntime( 4525): at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime( 4525): Caused by: java.lang.InstantiationException: can't instantiate class com.logic.testapp.SeekBarPreference; no empty construc tor E/AndroidRuntime( 4525): at java.lang.Class.newInstanceImpl(Native Method) E/AndroidRuntime( 4525): at java.lang.Class.newInstance(Class.java:1319) E/AndroidRuntime( 4525): at android.app.Instrumentation.newActivity(Instrumentation.java:1023) E/AndroidRuntime( 4525): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870) E/AndroidRuntime( 4525): ... 11 more W/ActivityManager( 84): Force finishing activity com.ui.testapp/com.logic.testapp.SeekBarPreference W/ActivityManager( 84): Force finishing activity com.ui.testapp/.MainScreen I/WindowManager( 84): createSurface Window{41a90320 paused=false}: DRAW NOW PENDING W/ActivityManager( 84): Activity pause timeout for ActivityRecord{4104a848 com.ui.testapp/com.logic.testapp.SeekBarPreference} W/NetworkManagementSocketTagger( 84): setKernelCountSet(10021, 1) failed with errno -2 I/WindowManager( 84): createSurface Window{412bcc10 com.android.launcher/com.android.launcher2.Launcher paused=false}: DRAW NOW PENDING W/NetworkManagementSocketTagger( 84): setKernelCountSet(10045, 0) failed with errno -2 I/Process ( 4525): Sending signal. PID: 4525 SIG: 9 I/ActivityManager( 84): Process com.ui.testapp (pid 4525) has died. I/WindowManager( 84): WIN DEATH: Window{41a6c9c0 com.ui.testapp/com.ui.testapp.MainScreen paused=true}

    Read the article

  • JDK7?????

    - by Todd Bao
    ??JSR 334,JDK 7?????????????,???:1. switch????String????:    public static void switchString(String s){        switch (s){        case "db": ...        case "wls": ...        case "idm": ...        case "soa": ...        case "fa": ...        default: ...        }    }2. ?????????? - "0b"???"_"???,?????????? a. ???????????, 0b: ????????????:        byte b1 = 0b00100001;     // New        byte b2 = 0x21;        // Old        byte b3 = 33;        // Old b. ??????????????,?????,????????????:    long phone_nbr = 021_1111_2222;3. ???????????? - "?? new",????????:        ArrayList<String> al1 = new ArrayList<String>();    // Old        ArrayList<String> al2 = new ArrayList<>();        // New4. ????reflect?????????? - ReflectOperationException,????:    ClassNotFoundException,     IllegalAccessException,     InstantiationException,     InvocationTargetException,     NoSuchFieldException,     NoSuchMethodException5. catch????????,?????????,????????:    try{        // code    }    catch (SQLException | IOException ex) {        // ...    }6. ?????? - ??????????,??????????style:    public void test() throws NoSuchMethodException, NoSuchFieldException{    // ??        try{            // code        }        catch (RelectiveOperationException ex){    // ??            throws ex;        }    }7. ???try()?? - Try with Resources,?????????????(???????????java.lang.AutoCloseable??),???????try?????"("??"{":    try(BufferedReader br = new BufferedReader(new FileReader("/home/oracle/temp.txt"))){        ... br.readLine() ...    }try-with-resources?????catch,??????????catch???????Todd

    Read the article

  • Mapping interface or abstract class component

    - by Yann Trevin
    Please consider the following simple use case: public class Foo { public virtual int Id { get; protected set; } public virtual IBar Bar { get; set; } } public interface IBar { string Text { get; set; } } public class Bar : IBar { public virtual string Text { get; set; } } And the fluent-nhibernate map class: public class FooMap : ClassMap<Foo> { public FooMap() { Id(x => x.Id); Component(x => x.Bar, m => { m.Map(x => x.Text); }); } } While running any query with configuration, I get the following exception: NHibernate.InstantiationException: "Cannot instantiate abstract class or interface: NHMappingTest.IBar" It seems that NHibernate tries to instantiate an IBar object instead of the Bar concrete class. How to let Fluent-NHibernate know which concrete class to instantiate when the property returns an interface or an abstract base class? EDIT: Explicitly specify the type of component by writing Component<Bar> (as suggested by Sly) has no effect and causes the same exception to occur. EDIT2: Thanks to vedklyv and Paul Batum: such a mapping should be soon is now possible.

    Read the article

  • How do I avoid repetition in Java ResourceBundle strings?

    - by Trejkaz
    We had a lot of strings which contained the same sub-string, from sentences about checking the log or how to contact support, to branding-like strings containing the company or product name. The repetition was causing a few issues for ourselves (primarily typos or copy/paste errors) but it also causes issues in that it increases the amount of text our translator has to translate. The solution I came up with went something like this: public class ExpandingResourceBundleControl extends ResourceBundle.Control { public static final ResourceBundle.Control EXPANDING = new ExpandingResourceBundleControl(); private ExpandingResourceBundleControl() { } @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { ResourceBundle inner = super.newBundle(baseName, locale, format, loader, reload); return inner == null ? null : new ExpandingResourceBundle(inner, loader); } } ExpandingResourceBundle delegates to the real resource bundle but performs conversion of {{this.kind.of.thing}} to look up the key in the resources. Every time you want to get one of these, you have to go: ResourceBundle.getBundle("com/acme/app/Bundle", EXPANDING); And this works fine -- for a while. What eventually happens is that some new code (in our case autogenerated code which was spat out of Matisse) looks up the same resource bundle without specifying the custom control. This appears to be non-reproducible if you write a simple unit test which calls it with and then without, but it occurs when the application is run for real. Somehow the cache inside ResourceBundle ejects the good value and replaces it with the broken one. I am yet to figure out why and Sun's jar files were compiled without debug info so debugging it is a chore. My questions: Is there some way of globally setting the default ResourceBundle.Control that I might not be aware of? That would solve everything rather elegantly. Is there some other way of handling this kind of thing elegantly, perhaps without tampering with the ResourceBundle classes at all?

    Read the article

  • hadoop implementing a generic list writable

    - by Guruprasad Venkatesh
    I am working on building a map reduce pipeline of jobs(with one MR job's output feeding to another as input). The values being passed around are fairly complex, in that there are lists of different types and hash maps with values as lists. Hadoop api does not seem to have a ListWritable. Am trying to write a generic one, but it seems i can't instantiate a generic type in my readFields implementation, unless i pass in the class type itself: public class ListWritable<T extends Writable> implements Writable { private List<T> list; private Class<T> clazz; public ListWritable(Class<T> clazz) { this.clazz = clazz; list = new ArrayList<T>(); } @Override public void write(DataOutput out) throws IOException { out.writeInt(list.size()); for (T element : list) { element.write(out); } } @Override public void readFields(DataInput in) throws IOException{ int count = in.readInt(); this.list = new ArrayList<T>(); for (int i = 0; i < count; i++) { try { T obj = clazz.newInstance(); obj.readFields(in); list.add(obj); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } But hadoop requires all writables to have a no argument constructor to read the values back. Has anybody tried to do the same and solved this problem? TIA.

    Read the article

  • Problem with 2 levels of inheritance in hibernate mapping

    - by Seth
    Here's my class structure: class A class B extends A class C extends A class D extends C class E extends C And here are my mappings (class bodies omitted for brevity): Class A: @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @MappedSuperclass @DiscriminatorColumn( name="className", discriminatorType=DiscriminatorType.STRING ) @ForceDiscriminator public abstract class A Class B: @Entity @DiscriminatorValue("B") public class B extends A Class C: @Entity @DiscriminatorValue("C") @MappedSuperclass @DiscriminatorColumn( name="cType", discriminatorType=DiscriminatorType.STRING ) @ForceDiscriminator public abstract class C extends A Class D: @Entity @DiscriminatorValue("D") public class D extends C Class E: @Entity @DiscriminatorValue("E") public class E extends C I've got a class F that contains a set of A: @Entity public class F { ... @OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL) @JoinTable( name="F_A", joinColumns = @JoinColumn(name="A_ID"), inverseJoinColumns = @JoinColumn(name="F_ID") ) private Set<A> aSet = new HashSet<A>(); ... The problem is that whenever I add a new E instance to aSet and then call session.saveOrUpdate(fInstance), hibernate saves with "A" as the discrimiator string. When I try to access the aSet in the F instance, I get the following exception (full stacktrace ommitted for brevity): org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: path.to.class.A Am I mapping the classes incorrectly? How am I supposed to map multiple levels of inheritance? Thanks for the help!

    Read the article

  • No operations allowed after statement closed issue

    - by Washu
    I have the next methods in my singleton to execute the JDBC connections public void openDB() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException { Class.forName("com.mysql.jdbc.Driver").newInstance(); String url = "jdbc:mysql://localhost/mbpe_peru";//mydb conn = DriverManager.getConnection(url, "root", "admin"); st = conn.createStatement(); } public void sendQuery(String query) throws SQLException { st.executeUpdate(query); } public void closeDB() throws SQLException { st.close(); conn.close(); } And I'm having a problem in a void where i have to call this twice. private void jButton1ActionPerformed(ActionEvent evt) { Main.getInstance().openDB(); Main.getInstance().sendQuery("call insertEntry('"+EntryID()+"','"+SupplierID()+"');"); Main.getInstance().closeDB(); Main.getInstance().openDB(); for(int i=0;i<dataBox.length;i++){ Main.getInstance().sendQuery("call insertCount('"+EntryID()+"','"+SupplierID()+"','"+BoxID()+"'); Main.getInstance().closeDB(); } } I have already tried to keep the connection open and send the 2 querys and after that closed and it didnt work... The only way it worked was to not use the methods, declare the commands for the connection and use different variables for the connection and the statement. I thought that if i close the Connecion and the Statement I could use the variable once again since is a method but I'm not able to. Is there any way to solve this using my methods for the JDBC connection?

    Read the article

  • Java program will read from database, but not write to it

    - by ck1221
    I have a Java program that successfully connects to a mysql database that is hosted on godaddy's server. I can read from that db with out issue, however, when I try to write to it with INSERT or UPDATE for example, the query does not execute. I am using the 'admin' account that I set up through godaddy, I realize this is not the root account. I have checked and verified that the connection is not read only, and have logged out of phpmyadmin while the query ran. I'm not sure what else I can try or if anyone has experienced this issue. Maybe a setting to the connection I have failed to set? Or maybe its not possible since the db is hosted on godaddy's servers? Any help is great! Thanks. Here is some relevant code: Connection to db: Connection con; public DBconnection(String url, String user, String pass) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection (url,user,pass); if(!con.isClosed()) System.out.println("connecton open"); } catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} } Send Query: public ResultSet executeQuery(String query) { ResultSet rs = null; try { Statement stmt = (Statement) con.createStatement(); rs = stmt.executeQuery(query); //while(rs.next()) //System.out.println(rs.getString("ticket_num")); } catch (SQLException e) {} return rs; } Insert Query (works in phpmyadmin): conn.executeQuery("INSERT INTO tickets VALUES(55555,'12/01/2012','me','reports','test','','','0','Nope')");

    Read the article

  • Problem with Java FX Look and Feel

    - by drachenfels
    Hi, I was looking at some of the examples from the Deitel and Deitel's book for Programming in Java, and one of the first examples is a very simple Swing display. Hence this snippet of code : import javax.swing.*; public class cdea { public static void main(String args[]){ JOptionPane.showMessageDialog(null,"\"Welcome to Java Programming!\""); System.exit(0); //end method main } } I read some stuff regarding how one can get native UI look and feel by using UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); to the program. However, when I just add this to my main method, it gives me a host of errors. Specifically : Multiple markers at this line - Unhandled exception type IllegalAccessException - Unhandled exception type InstantiationException - Unhandled exception type ClassNotFoundException - Unhandled exception type UnsupportedLookAndFeelException However when I use it as part of a try/catch exception loop (is that what it is called?) as detailed on http://stackoverflow.com/questions/1590863/getting-java-applications-to-look-native-on-windows-how , I get the program running properly. Could anyone tell me in simple language why this is so? As in, why can't I directly get the System look and feel; why do I have to use it with exception handling? I'm new to Java, and OOP in general, so I'm sorry if I'm being too simplistic.

    Read the article

  • Reflection to access advanced telephony features

    - by Tyler
    I am trying to use reflection to access some advanced features of the telephony api not published. Currently I am having trouble instantiating a serviceManager object that is needed to get the "phone" service as a binder which I can then use to instantiate a telephony object which is needed to make a call, end call, etc... currently when I make the call serviceManagerObject = tempInterfaceMethod.invoke(null, new Object[] { new Binder() }); it returns a nullPointerException. I believe this has to due with creating a new Binder instead of sending the appropriate binder (which I am unsure of which one is appropriate) public void placeReflectedCall() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException { String serviceManagerName = "android.os.IServiceManager"; String serviceManagerNativeName = "android.os.ServiceManagerNative"; String telephonyName = "com.android.internal.telephony.ITelephony"; Class telephonyClass; Class telephonyStubClass; Class serviceManagerClass; Class serviceManagerStubClass; Class serviceManagerNativeClass; Class serviceManagerNativeStubClass; Method telephonyCall; Method telephonyEndCall; Method telephonyAnswerCall; Method getDefault; Method[] temps; Constructor[] serviceManagerConstructor; // Method getService; Object telephonyObject; Object serviceManagerObject; String number = "1111111111"; telephonyClass = Class.forName(telephonyName); telephonyStubClass = telephonyClass.getClasses()[0]; serviceManagerClass = Class.forName(serviceManagerName); serviceManagerNativeClass = Class.forName(serviceManagerNativeName); Method getService = // getDefaults[29]; serviceManagerClass.getMethod("getService", String.class); Method tempInterfaceMethod = serviceManagerNativeClass.getMethod( "asInterface", IBinder.class); // this does not work serviceManagerObject = tempInterfaceMethod.invoke(null, new Object[] { new Binder() }); IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone"); Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class); telephonyObject = serviceMethod .invoke(null, new Object[] { retbinder }); telephonyCall = telephonyClass.getMethod("call", String.class); telephonyEndCall = telephonyClass.getMethod("endCall"); telephonyAnswerCall = telephonyClass.getMethod("answerRingingCall"); telephonyCall.invoke(telephonyObject, number); } Thanks in advance for any answers.

    Read the article

  • jframe adding own design jinternal frame error

    - by Van Minh
    I designed a title bar color on my JInternal frame. Then I took attempt to add it to my JFrame, but I cannot. Here is the code of my title bar: public class MyIFtitleBar extends BasicInternalFrameTitlePane { public MyIFtitleBar(JInternalFrame jif) { super(jif); } protected void paintTitleBackground(Graphics g){ g.setColor(Color.pink); g.fillRect(0, 0, getWidth(), getHeight()); } } Here is my JInternal frame. I tried running it in its psvm method, that worked! public class FitnessProg_Frame extends javax.swing.JInternalFrame { public FitnessProg_Frame() { initComponents(); this.setUI(new BasicInternalFrameUI(this){ @Override protected JComponent createNorthPane(JInternalFrame jif) { return new MyIFtitleBar(jif); } }); } @SuppressWarnings("unchecked") private void initComponents() { setBackground(new java.awt.Color(255, 255, 255)); setBorder(new javax.swing.border.MatteBorder(null)); setTitle("Fitness Progarm"); setPreferredSize(new java.awt.Dimension(507, 304)); pack(); } } But when I add it to my JFrame I get an error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Here is my JFrame code: public class NewJFrame extends javax.swing.JFrame { public NewJFrame() { initComponents(); FitnessProg_Frame ff = new FitnessProg_Frame(); ff.setVisible(true); mydes.add(ff); // this line made errors } @SuppressWarnings("unchecked") private void initComponents() { mydes = new javax.swing.JDesktopPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout mydesLayout = new javax.swing.GroupLayout(mydes); mydes.setLayout(mydesLayout); mydesLayout.setHorizontalGroup( mydesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); mydesLayout.setVerticalGroup( mydesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); getContentPane().add(mydes, java.awt.BorderLayout.CENTER); pack(); } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } private javax.swing.JDesktopPane mydes; }

    Read the article

  • javafx tableview get selected data from ObservableList

    - by user3717821
    i am working on a javafx project and i need your help . while i am trying to get selected data from table i can get selected data from normal cell but can't get data from ObservableList inside tableview. code for my database: -- phpMyAdmin SQL Dump -- version 4.0.4 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 10, 2014 at 06:20 AM -- Server version: 5.1.33-community -- PHP Version: 5.4.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `test` -- -- -------------------------------------------------------- -- -- Table structure for table `customer` -- CREATE TABLE IF NOT EXISTS `customer` ( `col0` int(11) NOT NULL, `col1` varchar(255) DEFAULT NULL, `col2` int(11) DEFAULT NULL, PRIMARY KEY (`col0`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `customer` -- INSERT INTO `customer` (`col0`, `col1`, `col2`) VALUES (12, 'adasdasd', 231), (22, 'adasdasd', 231), (212, 'adasdasd', 231); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; my javafx codes: import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import javafx.application.Application; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TablePosition; import javafx.scene.control.TableView; import javafx.scene.control.TableView.TableViewSelectionModel; import javafx.scene.control.cell.ChoiceBoxTableCell; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.StringConverter; class DBConnector { private static Connection conn; private static String url = "jdbc:mysql://localhost/test"; private static String user = "root"; private static String pass = "root"; public static Connection connect() throws SQLException{ try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); }catch(ClassNotFoundException cnfe){ System.err.println("Error: "+cnfe.getMessage()); }catch(InstantiationException ie){ System.err.println("Error: "+ie.getMessage()); }catch(IllegalAccessException iae){ System.err.println("Error: "+iae.getMessage()); } conn = DriverManager.getConnection(url,user,pass); return conn; } public static Connection getConnection() throws SQLException, ClassNotFoundException{ if(conn !=null && !conn.isClosed()) return conn; connect(); return conn; } } public class DynamicTable extends Application{ Object newValue; //TABLE VIEW AND DATA private ObservableList<ObservableList> data; private TableView<ObservableList> tableview; //MAIN EXECUTOR public static void main(String[] args) { launch(args); } //CONNECTION DATABASE public void buildData(){ tableview.setEditable(true); Callback<TableColumn<Map, String>, TableCell<Map, String>> cellFactoryForMap = new Callback<TableColumn<Map, String>, TableCell<Map, String>>() { @Override public TableCell call(TableColumn p) { return new TextFieldTableCell(new StringConverter() { @Override public String toString(Object t) { return t.toString(); } @Override public Object fromString(String string) { return string; } }); } }; Connection c ; data = FXCollections.observableArrayList(); try{ c = DBConnector.connect(); //SQL FOR SELECTING ALL OF CUSTOMER String SQL = "SELECT * from CUSTOMer"; //ResultSet ResultSet rs = c.createStatement().executeQuery(SQL); /********************************** * TABLE COLUMN ADDED DYNAMICALLY * **********************************/ for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){ //We are using non property style for making dynamic table final int j = i; TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1)); if(j==1){ final ObservableList<String> logLevelList = FXCollections.observableArrayList("FATAL", "ERROR", "WARN", "INFO", "INOUT", "DEBUG"); col.setCellFactory(ChoiceBoxTableCell.forTableColumn(logLevelList)); tableview.getColumns().addAll(col); } else{ col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){ public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) { return new SimpleStringProperty(param.getValue().get(j).toString()); } }); tableview.getColumns().addAll(col); } if(j!=1) col.setCellFactory(cellFactoryForMap); System.out.println("Column ["+i+"] "); } /******************************** * Data added to ObservableList * ********************************/ while(rs.next()){ //Iterate Row ObservableList<String> row = FXCollections.observableArrayList(); for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){ //Iterate Column row.add(rs.getString(i)); } System.out.println("Row [1] added "+row ); data.add(row); } //FINALLY ADDED TO TableView tableview.setItems(data); }catch(Exception e){ e.printStackTrace(); System.out.println("Error on Building Data"); } } @Override public void start(Stage stage) throws Exception { //TableView Button showDataButton = new Button("Add"); showDataButton.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { ObservableList<String> row = FXCollections.observableArrayList(); for(int i=1 ; i<=3; i++){ //Iterate Column row.add("asdasd"); } data.add(row); //FINALLY ADDED TO TableView tableview.setItems(data); } }); tableview = new TableView(); buildData(); //Main Scene BorderPane root = new BorderPane(); root.setCenter(tableview); root.setBottom(showDataButton); Scene scene = new Scene(root,500,500); stage.setScene(scene); stage.show(); tableview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observableValue, Object oldValue, Object newValue) { //Check whether item is selected and set value of selected item to Label if (tableview.getSelectionModel().getSelectedItem() != null) { TableViewSelectionModel selectionModel = tableview.getSelectionModel(); ObservableList selectedCells = selectionModel.getSelectedCells(); TablePosition tablePosition = (TablePosition) selectedCells.get(0); Object val = tablePosition.getTableColumn().getCellData(newValue); System.out.println("Selected Value " + val); System.out.println("Selected row " + newValue); } } }); } } please help me..

    Read the article

  • Using JDialog with Tabbed Pane to draw different pictures [migrated]

    - by Bryam Ulloa
    I am using NetBeans, and I have a class that extends to JDialog, inside that Dialog box I have created a Tabbed Pane. The Tabbed Pane contains 6 different tabs, with 6 different panels of course. What I want to do is when I click on the different tabs, a diagram is supposed to be drawn with the paint method. My question is how can I draw on the different panels with just one paint method in another class being called from the Dialog class? Here is my code for the Dialog class: package GUI; public class NewJDialog extends javax.swing.JDialog{ /** * Creates new form NewJDialog */ public NewJDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("FCFS", jPanel1); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SSTF", jPanel2); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("LOOK", jPanel3); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("LOOK C", jPanel4); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SCAN", jPanel5); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SCAN C", jPanel6); getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); jLabel1.setText("Distancia:"); jLabel2.setText("___________"); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addContainerGap(331, Short.MAX_VALUE)) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addContainerGap(15, Short.MAX_VALUE)) ); getContentPane().add(jPanel7, java.awt.BorderLayout.PAGE_START); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JTabbedPane jTabbedPane1; // End of variables declaration } This is another class that I have created for the paint method: package GUI; import java.awt.Graphics; import javax.swing.JPanel; /** * * @author TOSHIBA */ public class Lienzo { private int width = 5; private int height = 5; private int y = 5; private int x = 0; private int x1 = 0; public Graphics Draw(Graphics g, int[] pistas) { //Im not sure if this is the correct way to do it //The diagram gets drawn according to values from an array //The array is not always the same thats why I used the different Panels for (int i = 0; i < pistas.length; i++) { x = pistas[i]; x1 = pistas[i + 1]; g.drawOval(x, y, width, height); g.drawString(Integer.toString(x), x, y); g.drawLine(x, y, x1, y); } return g; } } I hope you guys understand what I am trying to do with my program.

    Read the article

  • How to create a simple adf dashboard application with EJB 3.0

    - by Rodrigues, Raphael
    In this month's Oracle Magazine, Frank Nimphius wrote a very good article about an Oracle ADF Faces dashboard application to support persistent user personalization. You can read this entire article clicking here. The idea in this article is to extend the dashboard application. My idea here is to create a similar dashboard application, but instead ADF BC model layer, I'm intending to use EJB3.0. There are just a one small trick here and I'll show you. I'm using the HR usual oracle schema. The steps are: 1. Create a ADF Fusion Application with EJB as a layer model 2. Generate the entities from table (I'm using Department and Employees only) 3. Create a new Session Bean. I called it: HRSessionEJB 4. Create a new method like that: public List getAllDepartmentsHavingEmployees(){ JpaEntityManager jpaEntityManager = (JpaEntityManager)em.getDelegate(); Query query = jpaEntityManager.createNamedQuery("Departments.allDepartmentsHavingEmployees"); JavaBeanResult.setQueryResultClass(query, AggregatedDepartment.class); return query.getResultList(); } 5. In the Departments entity, create a new native query annotation: @Entity @NamedQueries( { @NamedQuery(name = "Departments.findAll", query = "select o from Departments o") }) @NamedNativeQueries({ @NamedNativeQuery(name="Departments.allDepartmentsHavingEmployees", query = "select e.department_id, d.department_name , sum(e.salary), avg(e.salary) , max(e.salary), min(e.salary) from departments d , employees e where d.department_id = e.department_id group by e.department_id, d.department_name")}) public class Departments implements Serializable {...} 6. Create a new POJO called AggregatedDepartment: package oramag.sample.dashboard.model; import java.io.Serializable; import java.math.BigDecimal; public class AggregatedDepartment implements Serializable{ @SuppressWarnings("compatibility:5167698678781240729") private static final long serialVersionUID = 1L; private BigDecimal departmentId; private String departmentName; private BigDecimal sum; private BigDecimal avg; private BigDecimal max; private BigDecimal min; public AggregatedDepartment() { super(); } public AggregatedDepartment(BigDecimal departmentId, String departmentName, BigDecimal sum, BigDecimal avg, BigDecimal max, BigDecimal min) { super(); this.departmentId = departmentId; this.departmentName = departmentName; this.sum = sum; this.avg = avg; this.max = max; this.min = min; } public void setDepartmentId(BigDecimal departmentId) { this.departmentId = departmentId; } public BigDecimal getDepartmentId() { return departmentId; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public String getDepartmentName() { return departmentName; } public void setSum(BigDecimal sum) { this.sum = sum; } public BigDecimal getSum() { return sum; } public void setAvg(BigDecimal avg) { this.avg = avg; } public BigDecimal getAvg() { return avg; } public void setMax(BigDecimal max) { this.max = max; } public BigDecimal getMax() { return max; } public void setMin(BigDecimal min) { this.min = min; } public BigDecimal getMin() { return min; } } 7. Create the util java class called JavaBeanResult. The function of this class is to configure a native SQL query to return POJOs in a single line of code using the utility class. Credits: http://onpersistence.blogspot.com.br/2010/07/eclipselink-jpa-native-constructor.html package oramag.sample.dashboard.model.util; /******************************************************************************* * Copyright (c) 2010 Oracle. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * @author shsmith ******************************************************************************/ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import javax.persistence.Query; import org.eclipse.persistence.exceptions.ConversionException; import org.eclipse.persistence.internal.helper.ConversionManager; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.jpa.JpaHelper; import org.eclipse.persistence.queries.DatabaseQuery; import org.eclipse.persistence.queries.QueryRedirector; import org.eclipse.persistence.sessions.Record; import org.eclipse.persistence.sessions.Session; /*** * This class is a simple query redirector that intercepts the result of a * native query and builds an instance of the specified JavaBean class from each * result row. The order of the selected columns musts match the JavaBean class * constructor arguments order. * * To configure a JavaBeanResult on a native SQL query use: * JavaBeanResult.setQueryResultClass(query, SomeBeanClass.class); * where query is either a JPA SQL Query or native EclipseLink DatabaseQuery. * * @author shsmith * */ public final class JavaBeanResult implements QueryRedirector { private static final long serialVersionUID = 3025874987115503731L; protected Class resultClass; public static void setQueryResultClass(Query query, Class resultClass) { JavaBeanResult javaBeanResult = new JavaBeanResult(resultClass); DatabaseQuery databaseQuery = JpaHelper.getDatabaseQuery(query); databaseQuery.setRedirector(javaBeanResult); } public static void setQueryResultClass(DatabaseQuery query, Class resultClass) { JavaBeanResult javaBeanResult = new JavaBeanResult(resultClass); query.setRedirector(javaBeanResult); } protected JavaBeanResult(Class resultClass) { this.resultClass = resultClass; } @SuppressWarnings("unchecked") public Object invokeQuery(DatabaseQuery query, Record arguments, Session session) { List results = new ArrayList(); try { Constructor[] constructors = resultClass.getDeclaredConstructors(); Constructor javaBeanClassConstructor = null; // (Constructor) resultClass.getDeclaredConstructors()[0]; Class[] constructorParameterTypes = null; // javaBeanClassConstructor.getParameterTypes(); List rows = (List) query.execute( (AbstractSession) session, (AbstractRecord) arguments); for (Object[] columns : rows) { boolean found = false; for (Constructor constructor : constructors) { javaBeanClassConstructor = constructor; constructorParameterTypes = javaBeanClassConstructor.getParameterTypes(); if (columns.length == constructorParameterTypes.length) { found = true; break; } // if (columns.length != constructorParameterTypes.length) { // throw new ColumnParameterNumberMismatchException( // resultClass); // } } if (!found) throw new ColumnParameterNumberMismatchException( resultClass); Object[] constructorArgs = new Object[constructorParameterTypes.length]; for (int j = 0; j < columns.length; j++) { Object columnValue = columns[j]; Class parameterType = constructorParameterTypes[j]; // convert the column value to the correct type--if possible constructorArgs[j] = ConversionManager.getDefaultManager() .convertObject(columnValue, parameterType); } results.add(javaBeanClassConstructor.newInstance(constructorArgs)); } } catch (ConversionException e) { throw new ColumnParameterMismatchException(e); } catch (IllegalArgumentException e) { throw new ColumnParameterMismatchException(e); } catch (InstantiationException e) { throw new ColumnParameterMismatchException(e); } catch (IllegalAccessException e) { throw new ColumnParameterMismatchException(e); } catch (InvocationTargetException e) { throw new ColumnParameterMismatchException(e); } return results; } public final class ColumnParameterMismatchException extends RuntimeException { private static final long serialVersionUID = 4752000720859502868L; public ColumnParameterMismatchException(Throwable t) { super( "Exception while processing query results-ensure column order matches constructor parameter order", t); } } public final class ColumnParameterNumberMismatchException extends RuntimeException { private static final long serialVersionUID = 1776794744797667755L; public ColumnParameterNumberMismatchException(Class clazz) { super( "Number of selected columns does not match number of constructor arguments for: " + clazz.getName()); } } } 8. Create the DataControl and a jsf or jspx page 9. Drag allDepartmentsHavingEmployees from DataControl and drop in your page 10. Choose Graph > Type: Bar (Normal) > any layout 11. In the wizard screen, Bars label, adds: sum, avg, max, min. In the X Axis label, adds: departmentName, and click in OK button 12. Run the page, the result is showed below: You can download the workspace here . It was using the latest jdeveloper version 11.1.2.2.

    Read the article

1 2  | Next Page >