Is this constructor overloading??
class A
A(){
System.out.println("A is instantiated");
public void A(){
System.out.println("inside the method A of class A");
class B extends A
B(){
System.out.println("B is instantiated");
public void B(){
System.out.println("inside the method B of class B");
public static void main(String[] args) {
A a = new A();
a.A();
B b = new B();
b.A();
b.B();
since i hav given same names to constructor and method in class A and also in class B....i hav doubt whether is constructor overloading or not?
Try compiling this code:
class ObjectOne {
ObjectOne() {}
ObjectOne(int n) {
System.out.println(n);
class ObjectTwo extends ObjectOne {
public static void main(String[] args) {
ObjectTwo obj = new ObjectTwo(9);
}The very first line of any constructor is a call to super. Even if you do not type it, that line is explicitly inserted by the compiler.
So this:
class Foo extends Bar {
Foo() {
System.out.println("Foo");
}becomes
class Foo extends Bar {
Foo() {
super(); // explicit call to super
System.out.println("Foo");
}
Similar Messages
-
Unable to implement Constructor Overloading in an inherited class. Plz Help
Please do compile the program in in order to notice the error.
class EmpDet
int id,age;
String name;
String gender;
EmpDet(int id1,String name1,int age1,String gender1)
this.id = id1;
this.name= name1;
this.age= age1;
this.gender = gender1;
void Id_Name()
System.out.println("EmpId : "+id+" and Name : "+name);
void Gender_Age()
System.out.println("Employee is a "+gender+" and is "+age+" years old.");
class Employee extends EmpDet
String locality;
Employee(int a,String b,int c,String d)
super(a,b,c,d);
Employee(String locality1)// Constructor overloading. My problem.
this.locality = locality1;
void locality()
System.out.println("The employee resides at "+locality);
void DiplayStmt()
System.out.println("DISPLAYING EMPLOYEE DETAILS..");
System.out.println("******************************");
public static void main (String[] args)
Employee det = new Employee(010,"John",32,"M");
Employee addr = new Employee("Tambaram");
addr.DiplayStmt();
det.Id_Name();
det.Gender_Age();
addr.locality();
}Hey Thanks.. I guess what you said makes sense.
I was fiding it hard to agree that there needs to be a match between the Constructors of the Base Class and the Sub Class. I altered the program by adding a constructor in the Base class and using the super(0 function in the Sub class and that seems to work..
class EmpDet
int id,age;
String name;
String gender;
EmpDet(int id1,String name1,int age1,String gender1)
this.id = id1;
this.name= name1;
this.age= age1;
this.gender = gender1;
EmpDet(String addr)
System.out.println("Address is implemented in SubClass");
void Id_Name()
System.out.println("EmpId : "+id+" and Name : "+name);
void Gender_Age()
System.out.println("Employee is a "+gender+" and is "+age+" years old.");
class Employee extends EmpDet
String locality;
Employee(int a,String b,int c,String d)
super(a,b,c,d);
Employee(String locality1) // Constructor Overloading
super(locality1);
this.locality = locality1;
void locality()
System.out.println("The employee resides at "+locality);
void DiplayStmt()
System.out.println("DISPLAYING EMPLOYEE DETAILS..");
System.out.println("******************************");
public static void main (String[] args)
Employee det = new Employee(010,"John",32,"M");
Employee addr = new Employee("Tambaram");
addr.DiplayStmt();
det.Id_Name();
det.Gender_Age();
addr.locality();
Message was edited by:
3402102 -
I am making a program that takes in some information from the user. As an example, the program takes in home phone number and mobile phone number.
I'd like to give the user the option of just not entering in one of those. I could do this with overloading the constructor. Would this be the best way to do this?
It seems to get messy since I have a lot of options that the user could leave out and then obviously need a constructor for each. I would have about four constructors. Is this bad practice? If so, what would be the best way to do this?Since phone numbers are Strings, you could just use one constructor and pass empty strings if necessary,.
-
Help with constuctor, need to rewrite program with this constructor
i need to use this constructor for my Scholar class:
public Scholar(String fullName, double gradePointAverage, int essayScore, boolean scienceMajor){here is the project that i'm doing:
http://www.cs.utsa.edu/~javalab/cs17.../project1.html
here's my code for the Scholar class:package project1;
import java.util.*;
public class Scholar implements Comparable {
private static Random rand;
private String fullName;
private double gradePointAverage;
private int essayScore;
private int creditHours;
private boolean scienceMajor;
private String lastName;
private String firstName;
private double totalScore;
/** Creates a new instance of Scholar */
public Scholar(String lastName, String firstName){
this.fullName = lastName + ", " + firstName;
this.gradePointAverage = gradePointAverage;
this.essayScore = essayScore;
this.creditHours = creditHours;
this.scienceMajor = scienceMajor;
this.rand = new Random();
public String getFullName(){
return fullName;
public double getGradePointAverage(){
return gradePointAverage;
public int getEssayScore(){
return essayScore;
public int getCreditHours(){
return creditHours;
public boolean getScienceMajor(){
return scienceMajor;
public String setFullName(String lastName, String firstName){
fullName = lastName + ", " + firstName;
return fullName;
public double setGradePointAverage(double a){
gradePointAverage = a;
return gradePointAverage;
public int setEssayScore(int a){
essayScore = a;
return essayScore;
public int setCreditHours(int a){
creditHours = a;
return creditHours;
public boolean setScienceMajor(boolean a){
scienceMajor = a;
return scienceMajor;
public void scholarship(){
Random doubleGrade = new Random ();
Random intGrade = new Random ();
gradePointAverage = doubleGrade.nextDouble() + intGrade.nextInt(4);
Random score = new Random();
essayScore = score.nextInt(6);
Random hours = new Random();
creditHours = hours.nextInt(137);
Random major = new Random();
int num1 = major.nextInt(3);
if (num1 == 0)
scienceMajor = true;
else
scienceMajor = false;
public double getScore(){
totalScore = (gradePointAverage*5) + essayScore;
if (scienceMajor == true)
totalScore += .5;
if (creditHours >= 60 && creditHours <90)
totalScore += .5;
else if (creditHours >= 90)
totalScore += .75;
return totalScore;
public int compareTo(Object obj){
Scholar otherObj = (Scholar)obj;
double result = getScore() - otherObj.getScore();
if (result > 0)
return 1;
else if (result < 0)
return -1;
return 0;
public static Scholar max(Scholar s1, Scholar s2){
if (s1.getScore() > s2.getScore())
System.out.println(s1.getFullName() + " scored higher than " +
s2.getFullName() + ".\n");
else
System.out.println(s2.getFullName() + " scored higher than " +
s1.getFullName() + ".\n");
return null;
public static Scholar max(Scholar s1, Scholar s2, Scholar s3){
if (s1.getScore() > s2.getScore() && s1.getScore() > s3.getScore())
System.out.println(s1.getFullName() + " scored the highest" +
" out of all three students.");
else if (s2.getScore() > s1.getScore() && s2.getScore() > s3.getScore())
System.out.println(s2.getFullName() + " scored the highest" +
" out of all three students.");
else if (s3.getScore() > s2.getScore() && s3.getScore() > s1.getScore())
System.out.println(s3.getFullName() + " scored the highest" +
" out of all three students.");
return null;
public String toString(){
return "Student name: " + fullName + " -" + " Grade Point Average: "
+ gradePointAverage + ". " + "Essay Score: " + essayScore + "."
+ " Credit Hours: " + creditHours + ". " + " Science major: "
+ scienceMajor + ".";
}here's my code for the ScholarTester class:package project1;
import java.util.*;
public class ScholarTester {
public static void main(String [] args){
System.out.println("This program was written by Kevin Brown. \n");
System.out.println("--------Part 1--------\n");
Scholar abraham = new Scholar("Lincoln", "Abraham");
abraham.scholarship();
System.out.println(abraham);
/*kevin.setEssayScore(5);
kevin.setGradePointAverage(4.0);
kevin.setCreditHours(100);
kevin.setFullName("Brown", "Kevin J");
kevin.setScienceMajor(true);
System.out.println(kevin);*/
Scholar george = new Scholar("Bush", "George");
george.scholarship();
System.out.println(george + "\n");
System.out.println("--------Part 2--------\n");
System.out.println(abraham.getFullName() + abraham.getScore() + ".");
System.out.println(george.getFullName() + george.getScore() + ".\n");
System.out.println("--------Part 3--------\n");
if(abraham.compareTo(george) == 1)
System.out.println(abraham.getFullName() + " scored higher than " +
abraham.getFullName() + ".\n");
else
System.out.println(abraham.getFullName() + " scored higher than " +
abraham.getFullName() + ".\n");
System.out.println("--------Part 4--------\n");
Scholar.max(abraham, george);
Scholar thomas = new Scholar("Jefferson", "Thomas");
thomas.scholarship();
System.out.println("New student added - " + thomas + "\n");
System.out.println(abraham.getFullName() + " scored " +
abraham.getScore() + ".");
System.out.println(george.getFullName() + " scored " +
george.getScore() + ".");
System.out.println(thomas.getFullName() + " scored " +
thomas.getScore() + ".\n");
Scholar.max(abraham, george, thomas);
}everything runs like it should and the program is doing fine, i just need to change the format of the Scholar constructor and probably other things. Can someone please give me an idea how to fix this.
Thanks for taking your time reading this.then don't reply if you're not going to read it, i
just gave the url, Don't get snitty. I'm just informing you that most people here don't want to click a link and read your whole bloody assignment. If you want help, the burden is on you to make it as easy as possible for people to help you. I was only trying to inform you about what's more likely to get you help. If doing things your way is more important to you than increasing your chances of being helped, that's your prerogative.
so you can get an idea on what
it's about, and yeah i know how to add a constructor,
that's very obvious, That's what I thought, but you seemed to be saying, "How do I add this c'tor?" That's why I was asking for clarification about what specific trouble you're having.
i just want to know how to
implement everything correctly, so don't start
flaming people. I wasn't flaming you in the least. I was informing you of how to improve your chances of getting helped, and asking for clarification about what you're having trouble with. -
Java constructor overload error
I just tried a simple java program and it works on Linux but fails on Mac. Here is the code:
package TestProject;
public class Main {
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
int x =5;
int y = 6;
double a=5.0;
double b=6.0;
testout to1 = new testout(x,y);
testout to2 = new testout(a, b);
System.out.println(to1.getIntResult());
System.out.println(to2.getDoubleResult());
package TestProject;
public class testout {
private int a=0, b=0;
private double c=0.0, d=0.0;
public void testout(int x, int y)
a = x;
b = y;
public testout(double x, double y)
c = x;
d = y;
public double getDoubleResult()
return c + d;
public int getIntResult()
return a + b;
As you see I have a constructor to pass either two ints or two doubles. When I run the program on Linux I get the expected result. When I run on Mac, the getIntResult returns zero. I debugged the program and the int constructor is using the double instead. I verified on both netbeans and eclipse.
Looks like a bug but maybe I am doing something stupid.....Not being a Java developer, only have taken one semester of Java, and not having slept in a Holiday Inn recently, I couldn't tell you if it is a bug or not, but since an int can be freely cast to a double, maybe the Mac OS X JRE is finding the double, double constructor and saying to itself, "self, I can make those ints into doubles, so let's just use this double, double signature. la la la alaalla lla alllaaaaalllaa la al."
If you can find documentation in the Java implementation that directs you use the best constructor vice any appropriate constructor, file a bug report.
I would imagine you should always use the best match, not just one that works. -
How to use this color constructor ?
Color(int rgb)
Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.when i pass in 56, then i get blue. when i pass in 100 or 300, i get black. what is the magic to use this constructor ?
can some1 tell me how to get green or red ?
thanksAs the docs say, the bits 16-23 should contain the red component, the bits 8-15 should contain the green component and the bits 0-7 should contain the blue component. Since we're dealing with bits it's easier to do the work in hex, namely 0xFF0000 = 16711680(base 10) is red, 0xFF00 = 65280(base 10) is green, 0xFFFF00 = 16776960(base 10) is yellow and so on.
-
Passing arraylist between constructors?
Hi guys,
I've pretty new to java, and I think i'm having a little trouble
understanding scope. The program I'm working on is building a jtree
from an xml file, to do this an arraylist (xmlText) is being built and
declared in the function Main. It's then called to an overloaded
constructor which processes the XML into a jtree:
public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
Later, in the second constructor which builds my GUI, I try and call
the same arraylist so I can parse this XML into a set of combo boxes,
but get an error thrown up at me that i'm having a hard time solving- :
public Editor( String title ) throws ParserConfigurationException
// additional code
// Create a read-only combobox- where I get an error.
String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);
JComboBox queryBox = new JComboBox(items);
JComboBox queryBox2 = new JComboBox(items);
JComboBox queryBox3 = new JComboBox(items);
JComboBox queryBox4 = new JComboBox(items);
JComboBox queryBox5 = new JComboBox(items);
This is the way I understand the Arraylist can be converted to a string
to use in the combo boxs. However I get an error thrown up at me here
at about line 206, which as far as I understand, is because when the
overloaded constructor calls the other constructor:
public Editor( String title ) throws ParserConfigurationException -
It does not pass in the variable xmlText.
I'm told that the compiler complains because xmlText is not defined
at that point:
- it is not a global variable or class member
- it has not been passed into the function
and
- it has not been declared inside the current function
Can anyone think of a solution to this problem? As I say a lot of this
stuff is still fairly beyond me, I understand the principles behind the
language and the problem, but the solution has been evading me so far.
If anyone could give me any help or a solution here I'd be very
grateful- I'm getting totally stressed over this.
The code I'm working on is below, I've highlighted where the error
crops up too- it's about line 200-206 area. Sorry for the length, I was
unsure as to how much of the code I should post.
public class Editor extends JFrame implements ActionListener
// This is the XMLTree object which displays the XML in a JTree
private XMLTree XMLTree;
private JTextArea textArea, textArea2, textArea3;
// One JScrollPane is the container for the JTree, the other is for
the textArea
private JScrollPane jScroll, jScrollRt, jScrollUp,
jScrollBelow;
private JSplitPane splitPane, splitPane2;
private JPanel panel;
// This JButton handles the tree Refresh feature
private JButton refreshButton;
// This Listener allows the frame's close button to work properly
private WindowListener winClosing;
private JSplitPane splitpane3;
// Menu Objects
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem newItem, openItem, saveItem,
exitItem;
// This JDialog object will be used to allow the user to cancel an exit
command
private JDialog verifyDialog;
// These JLabel objects will be used to display the error messages
private JLabel question;
// These JButtons are used with the verifyDialog object
private JButton okButton, cancelButton;
private JComboBox testBox;
// These two constants set the width and height of the frame
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 450;
* This constructor passes the graphical construction off to the
overloaded constructor
* and then handles the processing of the XML text
public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
this( title );
textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
for ( int i = 1; i < xmlText.size(); i++ )
textArea.append( ( String )xmlText.get( i ) + "\n" );
try
XMLTree.refresh( textArea.getText() );
catch( Exception ex )
String message = ex.getMessage();
System.out.println( message );
}//end try/catch
} //end Editor( String title, String xml )
* This constructor builds a frame containing a JSplitPane, which in
turn contains two
JScrollPanes.
* One of the panes contains an XMLTree object and the other contains
a JTextArea object.
public Editor( String title ) throws ParserConfigurationException
// This builds the JFrame portion of the object
super( title );
Toolkit toolkit;
Dimension dim, minimumSize;
int screenHeight, screenWidth;
// Initialize basic layout properties
setBackground( Color.lightGray );
getContentPane().setLayout( new BorderLayout() );
// Set the frame's display to be WIDTH x HEIGHT in the middle of
the screen
toolkit = Toolkit.getDefaultToolkit();
dim = toolkit.getScreenSize();
screenHeight = dim.height;
screenWidth = dim.width;
setBounds( (screenWidth-FRAME_WIDTH)/2,
(screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
FRAME_HEIGHT );
// Build the Menu
// Build the verify dialog
// Set the Default Close Operation
// Create the refresh button object
// Add the button to the frame
// Create two JScrollPane objects
jScroll = new JScrollPane();
jScrollRt = new JScrollPane();
// First, create the JTextArea:
// Create the JTextArea and add it to the right hand JScroll
textArea = new JTextArea( 200,150 );
jScrollRt.getViewport().add( textArea );
// Next, create the XMLTree
XMLTree = new XMLTree();
XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION
XMLTree.setShowsRootHandles( true );
// A more advanced version of this tool would allow the JTree to
be editable
XMLTree.setEditable( false );
// Wrap the JTree in a JScroll so that we can scroll it in the
JSplitPane.
jScroll.getViewport().add( XMLTree );
// Create the JSplitPane and add the two JScroll objects
splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
jScrollRt );
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
jScrollUp = new JScrollPane();
jScrollBelow=new JScrollPane();
// Here is were the error is coming up
String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);
JComboBox queryBox = new JComboBox(items);
JComboBox queryBox2 = new JComboBox(items);
JComboBox queryBox3 = new JComboBox(items);
JComboBox queryBox4 = new JComboBox(items);
JComboBox queryBox5 = new JComboBox(items);
* I'm adding the scroll pane to the split pane,
* a panel to the top of the split pane, and some uneditible
combo boxes
* to them. Then I'll rearrange them to rearrange them, but
unfortunately am getting an error thrown up above.
panel = new JPanel();
panel.add(queryBox);
panel.add(queryBox2);
panel.add(queryBox3);
panel.add(queryBox4);
panel.add(queryBox5);
jScrollUp.getViewport().add( panel );
// Now building a text area
textArea3 = new JTextArea(200, 150);
jScrollBelow.getViewport().add( textArea3 );
splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
jScrollUp, jScrollBelow);
splitPane2.setPreferredSize( new Dimension(300, 200) );
splitPane2.setDividerLocation(100);
splitPane2.setOneTouchExpandable(true);
// in here can change the contents of the split pane
getContentPane().add(splitPane2,BorderLayout.SOUTH);
// Provide minimum sizes for the two components in the split pane
minimumSize = new Dimension(200, 150);
jScroll.setMinimumSize( minimumSize );
jScrollRt.setMinimumSize( minimumSize );
// Provide a preferred size for the split pane
splitPane.setPreferredSize( new Dimension(400, 300) );
// Add the split pane to the frame
getContentPane().add( splitPane, BorderLayout.CENTER );
//Put the final touches to the JFrame object
validate();
setVisible(true);
// Add a WindowListener so that we can close the window
winClosing = new WindowAdapter()
public void windowClosing(WindowEvent e)
verifyDialog.show();
addWindowListener(winClosing);
} //end Editor()
* When a user event occurs, this method is called. If the action
performed was a click
* of the "Refresh" button, then the XMLTree object is updated using
the current XML text
* contained in the JTextArea
public void actionPerformed( ActionEvent ae )
if ( ae.getActionCommand().equals( "Refresh" ) )
try
XMLTree.refresh( textArea.getText() );
catch( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
else if ( ae.getActionCommand().equals( "OK" ) )
exit();
else if ( ae.getActionCommand().equals( "Cancel" ) )
verifyDialog.hide();
}//end if/else if
} //end actionPerformed()
// Program execution begins here. An XML file (*.xml) must be passed
into the method
public static void main( String[] args )
String fileName = "";
BufferedReader reader;
String line;
ArrayList xmlText = null;
Editor Editor;
// Build a Document object based on the specified XML file
try
if( args.length > 0 )
fileName = args[0];
if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
".xml" ) )
reader = new BufferedReader( new FileReader( fileName )
xmlText = new ArrayList();
while ( ( line = reader.readLine() ) != null )
xmlText.add( line );
} //end while ( ( line = reader.readLine() ) != null )
// The file will have to be re-read when the Document
object is parsed
reader.close();
// Construct the GUI components and pass a reference to
the XML root node
Editor = new Editor( "Editor 1.0", xmlText );
else
help();
} //end if ( fileName.substring( fileName.indexOf( '.' )
).equals( ".xml" ) )
else
Editor = new Editor( "Editor 1.0" );
} //end if( args.length > 0 )
catch( FileNotFoundException fnfEx )
System.out.println( fileName + " was not found." );
exit();
catch( Exception ex )
ex.printStackTrace();
exit();
}// end try/catch
}// end main()
// A common source of operating instructions
private static void help()
System.out.println( "\nUsage: java Editor filename.xml" );
System.exit(0);
} //end help()
// A common point of exit
public static void exit()
System.out.println( "\nThank you for using Editor 1.0" );
System.exit(0);
} //end exit()
class newMenuHandler implements ActionListener
public void actionPerformed( ActionEvent ae )
textArea.setText( "" );
try
// Next, create a new XMLTree
XMLTree = new XMLTree();
XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION );
XMLTree.setShowsRootHandles( true );
// A more advanced version of this tool would allow the JTree
to be editable
XMLTree.setEditable( false );
catch( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
}//end actionPerformed()
}//end class newMenuHandler
class openMenuHandler implements ActionListener
JFileChooser jfc;
Container parent;
int choice;
openMenuHandler()
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = openItem.getParent();
}//end openMenuHandler()
public void actionPerformed( ActionEvent ae )
// Displays the jfc and sets the dialog to 'open'
choice = jfc.showOpenDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
String fileName, line;
BufferedReader reader;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
reader = new BufferedReader( new FileReader( fileName ) );
textArea.setText( reader.readLine() + "\n" );
while ( ( line = reader.readLine() ) != null )
textArea.append( line + "\n" );
} //end while ( ( line = reader.readLine() ) != null )
// The file will have to be re-read when the Document
object is parsed
reader.close();
XMLTree.refresh( textArea.getText() );
catch ( Exception ex )
String message = ex.getMessage();
ex.printStackTrace();
}//end try/catch
jfc.setCurrentDirectory( new File( fileName ) );
} //end if ( choice == JFileChooser.APPROVE_OPTION )
}//end actionPerformed()
}//end class openMenuHandler
class saveMenuHandler implements ActionListener
JFileChooser jfc;
Container parent;
int choice;
saveMenuHandler()
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = saveItem.getParent();
}//end saveMenuHandler()
public void actionPerformed( ActionEvent ae )
// Displays the jfc and sets the dialog to 'save'
choice = jfc.showSaveDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
String fileName;
File fObj;
FileWriter writer;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
writer = new FileWriter( fileName );
textArea.write( writer );
// The file will have to be re-read when the Document
object is parsed
writer.close();
catch ( IOException ioe )
ioe.printStackTrace();
}//end try/catch
jfc.setCurrentDirectory( new File( fileName ) );
} //end if ( choice == JFileChooser.APPROVE_OPTION )
}//end actionPerformed()
}//end class saveMenuHandler
class exitMenuHandler implements ActionListener
public void actionPerformed( ActionEvent ae )
verifyDialog.show();
}//end actionPerformed()
}//end class exitMenuHandler
class XmlFileFilter extends javax.swing.filechooser.FileFilter
public boolean accept( File fobj )
if ( fobj.isDirectory() )
return true;
else
return fobj.getName().endsWith( ".xml" );
}//end accept()
public String getDescription()
return "*.xml";
}//end getDescription()
}//end class XmlFileFilter
} //end class Editor
Sorry if this post has been a bit lengthy, any help you guys could give
me solving this would be really appreciated.
Thanks,
Iain.Hey. Couple pointers:
When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
That way people don't have to wade through irrelevant stuff and
they have an easier time helping.
http://homepage1.nifty.com/algafield/sscce.html
As for your problem, this is a scope issue. You declare an
ArrayList xmlText in main(). That means that everywhere after
the declaration in main(), you can reference your xmlText.
So far so good. Then, inside main(), you call
Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
Editor(String title, ArrayList xmlText) [which happens to be a
constructor, but that's not important]. When you do that, you
make the two variables title and xmlText available to the whole
Editor(String, ArrayList) method.
This is where you get messed up. You invoke another method
from inside Editor(String, ArrayList). When you call
this(title);you're invoking the method Editor(String title). You aren't passing
in your arraylist, though. You've got code in the Editor(String) method
which is trying to reference xmlText, but you'd need to pass in
your ArrayList in order to do so.
My suggestion would be to merge the two constructor methods into
one, Editor(String title, ArrayList xmlText). -
Hi,
I am trying to write a class in ABAP. And I need to overload my constructor. I have tried this overloading operation by SE80 transaction. But ABAP says "There is already a constructor". Is it not possible to overload a method/constructor in ABAP?
Thanks.Hi,
ABAP does not provide overloading of methods/constructors in a way we know from other OO languages (eg. Java). You cannot write a method with the same name but different signature. You can only override methods in subclass using REDEFIITION key word but signature must stay the same.
You can also provide a different constructor in sub class but the first statement in this constructor must be a call to constructor of super-class. But only one constructor can exist.
Here is an example:
*& Report ZCL_OVR *
REPORT zcl_ovr .
* CLASS lcl_a DEFINITION
CLASS lcl_a DEFINITION.
PUBLIC SECTION.
METHODS:
constructor,
do_sth IMPORTING iv_a TYPE i
RETURNING value(ov_b) TYPE i.
ENDCLASS. "lcl_a DEFINITION
* CLASS lcl_a IMPLEMENTATION
CLASS lcl_a IMPLEMENTATION.
METHOD constructor.
ENDMETHOD. "constructor
METHOD do_sth.
ov_b = 2 * iv_a.
ENDMETHOD. "do_sth
ENDCLASS. "lcl_a IMPLEMENTATION
* CLASS lcl_b DEFINITION
CLASS lcl_b DEFINITION INHERITING FROM lcl_a.
PUBLIC SECTION.
METHODS:
constructor IMPORTING iv_a TYPE i,
do_sth REDEFINITION.
PRIVATE SECTION.
DATA lv_c TYPE i.
ENDCLASS. "lcl_b DEFINITION
* CLASS lcl_b IMPLEMENTATION
CLASS lcl_b IMPLEMENTATION.
METHOD constructor.
CALL METHOD super->constructor.
me->lv_c = iv_a.
ENDMETHOD. "constructor
METHOD do_sth.
ov_b = 2 * iv_a + lv_c.
ENDMETHOD. "do_sth
ENDCLASS. "lcl_b IMPLEMENTATION -
Constructor Method parameter problem
I write my class whit this constructor method.
public Immobile(int id, String complesso, String tipoed,double prezzo) {
this.id = id;
this.complesso = complesso;
this.tipoed =tipoed;
this.prezzo = prezzo;
in my app i want to create an object of Immobile class:
Immobile imm = new Immobile(1,"nuovo",null,2);
Always is ok
if I don't want to pass the String parameter I set it whit null.
But if I don't want to pass an integer like first parameter, or double like prezzo parameter, How can I do this?
I don't want to use Overloading of method because if the Immobile class have for example 30 parameter, i don't want to write 30 constructor method.
There is any possibility?I think that my design is ok.Two competent developers and me disagree with you.Sign me in here. Every time I get code with methods with more than 4 parameters I shudder.
A class with 30 constructor parameters is probably a class with 30 fields and more often than not those class fields can be refactored in smaller classes, like ...
I think that made a class User whit parameter Name,
Surname, address, telefon, fax is ok
and i think that a user probably haven't a fax.
I think that one way can be to use all the parameter
like String, that accept null, next, casting orsome
conversion before insert in a database
What do you think about this?Surname, address, telephone and fax give you 30
variables? What are you doing, show a small piece of
relevant code....
class ContactInfo class for tel, fax, mail, pager.
class Adress for City, street, country, etc.
and so on.
I don't know if BiggDaddy 's sugestion comes in hand in any problem solution but I know that it can very easily come out of hand, I worked on a system where everything was passed down through 2 parameters, that where in fact 2 arrays of parameters.
The system was a mess, very hard to understand and to test, and bugs popped around in production time.
May the code be with you. -
Does this code:
public class BadAttributeExceptionClass extends Exception
public BadAttributeExceptionClass()
super("An exception has occured while trying to set an attribute value.");
public BadAttributeExceptionClass(String message)
super(message);
public BadAttributeExceptionClass(String badAttribute,int value)
super("The user has tried to enter an invalid value for the attribute "+badAttribute+
" . The value "+value+" is out of range.");
public BadAttributeExceptionClass(String badAttribute,double value)
super("The user has tried to enter an invalid value for the attribute "+badAttribute+
" . The value "+value+" is out of range.");
public BadAttributeExceptionClass(String badAttribute,String value)
super("The user has tried to enter an invalid value for the attribute "+badAttribute+
" . The value "+value+" is out of range.");
satisfy this requirement:
BadAttributeValueException Class
You will be creating several constructors for this class.
Default Constructor
This constructor will pass a string to its superclass that states that an error has occurred while trying to set an attribute value. This will be used as the generic message when no additional information is passed to this class.
One String Argument Constructor
This constructor will just take whatever string is passed to it as an argument and send it on to its super class. This allows the user of this class to customize their error message anyway that they want
Overloaded Two Argument Constructors
You will create the following 2-argument constructors:
Arg 1 Arg 2 Description
String int Used when integer attributes are attempting to be initialized
String double Used when double attributes are attempting to be initialized
String String Used when string attributes are attempting to be initialized
The first argument is the name of the attribute and the second argument is the bad value that wasn?t accepted in the mutator for this attribute.
These constructors will be used to pass the name of the attribute and the bad value. Three different constructors are needed since your attributes have different data types. This will provide as much feedback as possible to the users of the multiple constructors.
You need to create a string that tells the user that:
? An error has occurred
? The name of the attribute
? The value that was incorrect.
You will then pass this string to the super class constructor.
Thx for any help !!Could be wrong but it sounds like you need the message plus both the attribute and value for the last three constructors. If so:
public class BadAttributeExceptionClass extends Exception
private static final String MESSAGE = "An exception has occured while trying to set an attribute value. The user has tried to enter an invalid value for the attribute ";
public BadAttributeExceptionClass()
super(MESSAGE);
public BadAttributeExceptionClass(String message)
super(message);
public BadAttributeExceptionClass(String badAttribute,int value)
this(badAttribute, value);
public BadAttributeExceptionClass(String badAttribute,double value)
this(badAttribute, value);
public BadAttributeExceptionClass(String badAttribute,String value)
super(MESSAGE+badAttribute+". The value "+value+" is out of range.");
}Message was edited by:
abillconsl -
Anyone's mini throw up this video pattern?
Brand new Mac mini 5,1 running 10.7.2. Randomly, it will crash every few hours and throw up this semi-checkboard pattern on my monitor, which is a Samsung 2333SW.
The dark areas are approx. 2" x 2" and they're made up of a series of horizontal 1/4" lines made up of vertical lines or static. Kind of looks like a bar code. If I'm doing something with audio, like listening to a podcast, when the crash occurs the audio screeches and sounds a bit like old dialup modems but 1,000 times worse. I have to reboot to get the computer working again.
The monitor has DVI-D and VGA, so I'm using Apple-supplied adapters. I've tried HDMI-to-DVI and Mini DisplayPort-to-VGA. Same problem. I've also tried different resolutions. I've reinstalled Lion. I've reset the SMC. All software and firmware is up to date.
The monitor works with other Apple computers, though they're running 10.6 and 10.5.
It may be coincidence, but the one possible consistency is the pattern appears during seemingly minor tasks - browsing the web, listening to podcasts, sitting idle in the finder, playing music, etc. It's occurred on a fresh install where I haven't so much as changed a system preference. But I've watched movies all day during holiday break and the issue never popped up. I've played games for 4-5 hours without issue. I ran iTunes for an entire day with the visualizer running and had no issue.
Any ideas or similar experiences before I bring it in to the Apple Store? Thanks.Thank you for discussin, jtlipowski!
I've been mistaken - i use not smcFanControl, but FanControl 1.2 I'm going to deinstall it and use smcFanControl.
But before this I set fan to 3600 RPM, let me see what will happen.
Do you use APC PowerChute Software? It's very interesting - when i used it Mac mini never crashes like this. But this software overloads CPU very much - the load of CPU increases from 5% to 90%. And the temperature raise significantly and no Fan Control could not reduce it. So i turn it off, but the problems with this crash appears.
Could it be due to bad temperature heat removal? May be it's necesary to check th CPU cooling system... -
Networking - Why Doesn't This Work?
Hey all
Just wondering if any of you have any ideas why this code isn't working properly - for the Client to connect the Server has to be restarted. Is there a solution to this problem?
The Client Class:
import java.awt.Container;
import java.awt.Color;
import java.awt.Font;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JColorChooser;
import javax.swing.ButtonGroup;
import javax.swing.Box;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.BoxLayout;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import java.io.*;
import java.net.*;
* This is the user class and holds all the details for the GUI. The gui contains listeners
* ans it sends messages to the server and also recieves messages from the server. This class
* works primarily with the ClienttoServer class.
* Help was used to create this class, mainly from the Java GUI devlopment book by Varan Piroumian
* as this hsowed the basic components needed to create a GUI and which imports were the most essential
* in order to have an interactive interface for the chat application.
public class Client extends JFrame implements ActionListener
private static final long serialVersionUID = 1L;
private JTextArea conversationDisplay;
private JTextField createMsg, hostfield, portnumfd, usernamey;
private JScrollPane scrolly;
private JLabel hosty, portnum, convoLabel, msgLabel, netwrk, netwrk2, talk2urself, fonts, nickName, ustatus, econs;
private JPanel lpanel, rpanel, lpanel1, lpanel2, lpanel3, lpanel4, lpanel5, rpanel1, rpanel2, rpanel3, rpanel4, rpanel5;
private JButton sendMsgButton, colourButton, exitButton, connect, dropconnection;
private JRadioButton talk2urselfOn, talk2urselfOff;
private JComboBox fontcombiBox, statusbox, emoticons;
private JColorChooser colourchoo;
private Container theWholeApp;
private String username;
private PrintWriter writer;
private Socket socky;
//for the self comm button
private boolean talktoself = true;
//used as when a msg is sent to the server the name & msg are sent in 2 parts (\n function) i.e
//2 different messages. So in self comm mode then the next message needs to be ignored
private boolean ignoreyourself = false;
* The Constructor or the class
public Client()
makeGUI();
System.out.println("Loading the GUI....");
* Creates the GUI for the user to see/use
public void makeGUI()
//create the whole window
JFrame.setDefaultLookAndFeelDecorated(true);
//set the title of the whole app
this.setTitle("Welcome To Elliot's Chat Network...");
//set the app window size
this.setSize(600, 575);
//create the outer container for the app
theWholeApp = getContentPane();
//make new gridbag layout
GridBagLayout layoutgridbag = new GridBagLayout();
//create some restraints for this...
GridBagConstraints gbconstraints = new GridBagConstraints();
//make the app use this gridbag layout
theWholeApp.setLayout(layoutgridbag);
//this is where elements are added into the application's window
//creates and adds the convo label
convoLabel = new JLabel("Your Conversation:");
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 0;
gbconstraints.gridheight = 1;
gbconstraints.gridwidth = 1;
gbconstraints.weightx = 5;
gbconstraints.weighty = 1;
gbconstraints.anchor = GridBagConstraints.WEST;
layoutgridbag.setConstraints(convoLabel, gbconstraints);
theWholeApp.add(convoLabel);
//create & add the exit button
exitButton = new JButton("Exit");
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 10;
gbconstraints.gridy = 0;
gbconstraints.gridheight = 1;
gbconstraints.gridwidth = 1;
gbconstraints.weightx = 1;
gbconstraints.weighty = 1;
gbconstraints.anchor = GridBagConstraints.EAST;
layoutgridbag.setConstraints(exitButton, gbconstraints);
theWholeApp.add(exitButton);
exitButton.addActionListener(this);
//create & add the txt area
conversationDisplay = new JTextArea(15,15);
scrolly = new JScrollPane(conversationDisplay);
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 1;
gbconstraints.gridheight = 4;
gbconstraints.gridwidth = 11;
gbconstraints.weightx = 10;
gbconstraints.weighty = 20;
gbconstraints.anchor = GridBagConstraints.WEST;
gbconstraints.fill = GridBagConstraints.BOTH;
gbconstraints.insets = new Insets(10, 10, 15, 15);
//so the clients cant write in the display area...
conversationDisplay.setEditable(false);
layoutgridbag.setConstraints(scrolly, gbconstraints);
theWholeApp.add(scrolly);
//create & add the nick name area
nickName = new JLabel("Your nick \nthis is required");
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 5;
gbconstraints.gridheight = 1;
gbconstraints.gridwidth = 1;
gbconstraints.weightx = 5;
gbconstraints.weighty = 1.5;
gbconstraints.anchor = GridBagConstraints.WEST;
gbconstraints.fill = GridBagConstraints.HORIZONTAL;
gbconstraints.insets = new Insets(3, 10, 0, 0);
layoutgridbag.setConstraints(nickName, gbconstraints);
theWholeApp.add(nickName);
//create & add the nick name box
usernamey = new JTextField(10);
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 6;
gbconstraints.gridheight = 1;
gbconstraints.gridwidth = 1;
gbconstraints.weightx = 1;
gbconstraints.weighty = 1;
gbconstraints.anchor = GridBagConstraints.WEST;
gbconstraints.fill = GridBagConstraints.HORIZONTAL;
gbconstraints.insets = new Insets(0, 10, 0, 0);
layoutgridbag.setConstraints(usernamey, gbconstraints);
theWholeApp.add(usernamey);
//create & add the your message label
msgLabel = new JLabel("Your Message:");
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 7;
gbconstraints.gridheight = 1;
gbconstraints.gridwidth = 1;
gbconstraints.weightx = 1;
gbconstraints.weighty = 1;
gbconstraints.anchor = GridBagConstraints.WEST;
gbconstraints.fill = GridBagConstraints.BOTH;
gbconstraints.insets = new Insets(0, 10, 0, 0);
layoutgridbag.setConstraints(msgLabel, gbconstraints);
theWholeApp.add(msgLabel);
//create & add the create message box
createMsg = new JTextField(15);
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 8;
gbconstraints.gridheight = 2;
gbconstraints.gridwidth = 10;
gbconstraints.weightx = 10;
gbconstraints.weighty = 1;
gbconstraints.anchor = GridBagConstraints.WEST;
gbconstraints.fill = GridBagConstraints.HORIZONTAL;
gbconstraints.insets = new Insets(3, 10, 0, 0);
layoutgridbag.setConstraints(createMsg, gbconstraints);
theWholeApp.add(createMsg);
createMsg.addActionListener(this);
createMsg.setActionCommand("Press Enter!");
//create & add the send message button
sendMsgButton = new JButton("Send Msg");
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 10;
gbconstraints.gridy = 8;
gbconstraints.gridheight = 1;
gbconstraints.gridwidth = 1;
gbconstraints.weightx = 1;
gbconstraints.weighty = 1;
gbconstraints.anchor = GridBagConstraints.EAST;
layoutgridbag.setConstraints(sendMsgButton, gbconstraints);
theWholeApp.add(sendMsgButton);
sendMsgButton.addActionListener(this);
//create & add the left panel
lpanel = new JPanel();
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 10;
gbconstraints.gridheight = 3;
gbconstraints.gridwidth = 4;
gbconstraints.weightx = 5;
gbconstraints.weighty = 0;
gbconstraints.anchor = GridBagConstraints.WEST;
gbconstraints.insets = new Insets(0, 10, 0, 0);
layoutgridbag.setConstraints(lpanel, gbconstraints);
theWholeApp.add(lpanel);
//create & add the right panel
rpanel = new JPanel();
gbconstraints = new GridBagConstraints();
gbconstraints.gridx = 5;
gbconstraints.gridy = 10;
gbconstraints.gridheight = 3;
gbconstraints.gridwidth = 4;
gbconstraints.weightx = 5;
gbconstraints.weighty = 0;
gbconstraints.anchor = GridBagConstraints.EAST;
layoutgridbag.setConstraints(rpanel, gbconstraints);
theWholeApp.add(rpanel);
//add to the left JPanel - set the layout for this
lpanel.setLayout(new BoxLayout(lpanel, BoxLayout.Y_AXIS));
//add panels into this left panel...
lpanel1 = new JPanel();
lpanel2 = new JPanel();
lpanel3 = new JPanel();
lpanel4 = new JPanel();
lpanel5 = new JPanel();
lpanel.add(lpanel1);
lpanel.add(lpanel2);
lpanel.add(lpanel3);
lpanel.add(lpanel4);
lpanel.add(lpanel5);
//set FlowLyout for each of these panels
lpanel1.setLayout(new FlowLayout(FlowLayout.LEFT));
lpanel2.setLayout(new FlowLayout(FlowLayout.LEFT));
lpanel3.setLayout(new FlowLayout(FlowLayout.LEFT));
lpanel4.setLayout(new FlowLayout(FlowLayout.LEFT));
lpanel5.setLayout(new FlowLayout(FlowLayout.LEFT));
//add in the network items...
netwrk = new JLabel("Network Details:");
lpanel1.add(netwrk);
//create and add instructions for this
netwrk2 = new JLabel("Please enter the details for \nthe person you want to chat to...");
lpanel2.add(netwrk2);
//create/add the ip addy label
hosty = new JLabel("Host:");
lpanel3.add(hosty);
lpanel3.add(Box.createRigidArea(new Dimension(5,0)));
hostfield = new JTextField("Enter Hostname",10);
lpanel3.add(hostfield);
//port num next
portnum = new JLabel("Port Number:");
lpanel4.add(portnum);
lpanel4.add(Box.createRigidArea(new Dimension(5, 0)));
portnumfd = new JTextField("2250", 10);
lpanel4.add(portnumfd);
//create & add the connect butt
connect = new JButton("Connect");
lpanel5.add(connect);
dropconnection = new JButton("Disconnect");
lpanel5.add(dropconnection);
connect.addActionListener(this);
dropconnection.addActionListener(this);
//start the creation of the right hand panel.
rpanel.setLayout(new BoxLayout(rpanel, BoxLayout.Y_AXIS));
//create the panels again
rpanel1 = new JPanel();
rpanel2 = new JPanel();
rpanel3 = new JPanel();
rpanel4 = new JPanel();
rpanel5 = new JPanel();
rpanel.add(rpanel1);
rpanel.add(rpanel2);
rpanel.add(rpanel3);
rpanel.add(rpanel4);
rpanel.add(rpanel5);
rpanel1.setLayout(new FlowLayout(FlowLayout.LEFT));
rpanel2.setLayout(new FlowLayout(FlowLayout.LEFT));
rpanel3.setLayout(new FlowLayout(FlowLayout.LEFT));
rpanel4.setLayout(new FlowLayout(FlowLayout.LEFT));
rpanel5.setLayout(new FlowLayout(FlowLayout.LEFT));
//now start putting things into them again
//add in the font settings
String[] fonty = {"Normal", "Bold", "Italic"};
fonts = new JLabel("Set your text style:");
fontcombiBox = new JComboBox(fonty);
rpanel2.add(fonts);
rpanel2.add(Box.createRigidArea(new Dimension(4,0)));
rpanel2.add(fontcombiBox);
//default text will be plain..
fontcombiBox.setSelectedIndex(0);
String[] userstatus = {"Online", "Away", "Be Right Back", "Busy", "Out To Lunch", "On The Phone"};
ustatus = new JLabel("Select a status:");
statusbox = new JComboBox(userstatus);
rpanel2.add(ustatus);
rpanel2.add(Box.createRigidArea(new Dimension(2,0)));
rpanel2.add(statusbox);
//add in some emotion to the conversations
String[] emotion = {"Angry", "Happy", "Sad", "Crying", "Shocked", "Laughing", "Laughing My Ass Off!"};
econs = new JLabel("Select an emoticon:");
emoticons = new JComboBox(emotion);
rpanel3.add(econs);
rpanel3.add(Box.createRigidArea(new Dimension(3,0)));
rpanel3.add(emoticons);
//self comm options
talk2urself = new JLabel("Set Self Communication Mode:");
rpanel4.add(talk2urself);
talk2urselfOn = new JRadioButton("On", true);
rpanel4.add(talk2urselfOn);
rpanel4.add(Box.createRigidArea(new Dimension(4, 0)));
talk2urselfOff = new JRadioButton("Off", false);
rpanel4.add(talk2urselfOff);
//create a group that will hold both these buttons together
ButtonGroup groupy = new ButtonGroup();
//add them to the group
groupy.add(talk2urselfOn);
groupy.add(talk2urselfOff);
//create and add the change backgrd button
colourButton = new JButton("Alter Background");
rpanel5.add(colourButton);
//add in some listeners
talk2urselfOn.addActionListener(this);
talk2urselfOff.addActionListener(this);
fontcombiBox.addActionListener(this);
colourButton.addActionListener(this);
statusbox.addActionListener(this);
//add in the 'X' button in the top right corner of app
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//put all elements together
this.pack();
//show the GUI for the user..
this.show();
* Creates a new client and GUI as its the main method
public static void main(String args[])
new Client();
* This method listens for actions selected by the user and then performs the
* necessary tasks in order for the correct events to take place...!
* This method was mainly created thanks to the Developing Java GUI book which has already
* been mentioned as it covers listeners and event handling...
public void actionPerformed(ActionEvent event)
//if the send button is clicked or if hard carriage return after message
if((event.getSource() == (sendMsgButton)) || (event.getSource().equals(createMsg)))
//if theres no text dont send message
if(createMsg.getText().equals(""))
JOptionPane.showMessageDialog(this, "There's no text to send!");
else
String str = createMsg.getText();
printMessage(str);
//if the exit button is clicked
if(event.getSource() == (exitButton))
//quit the chat app
JOptionPane.showMessageDialog(this, "Thanks For Using Elliot's Chat Network! \nSee You Again Soon!");
System.exit(0);
//if the self comm option is turned on
if(event.getSource() == (talk2urselfOn))
talktoself = true;
JOptionPane.showMessageDialog(this, "You have begun self communication \nmessages you send are now displayed");
//if the self comm option is turned off
if(event.getSource() == (talk2urselfOff))
talktoself = false;
JOptionPane.showMessageDialog(this, "You have stopped self communication \nmessages you send are no longer displayed");
//for the normal font option
if(fontcombiBox.getSelectedItem().equals("Plain"))
//makes a new font style plain...
conversationDisplay.setFont(new Font("simple", Font.PLAIN, 12));
createMsg.setFont(new Font("simple", Font.PLAIN, 12));
//for the bold font option
if(fontcombiBox.getSelectedItem().equals("Bold"))
conversationDisplay.setFont(new Font("simple", Font.BOLD, 12));
createMsg.setFont(new Font("simple", Font.BOLD, 12));
//for the italic font option
if(fontcombiBox.getSelectedItem().equals("Italic"))
conversationDisplay.setFont(new Font("simple", Font.ITALIC, 12));
createMsg.setFont(new Font("simple", Font.ITALIC, 12));
* //the status events if they didnt create null points...
if(statusbox.getSelectedItem().equals("Online"))
String status = "<Online>";
printMessage(status);
if(statusbox.getSelectedItem().equals("Away"))
String status = "<Away>";
printMessage(status);
if(statusbox.getSelectedItem().equals("Be Right Back"))
String status = "<Be Right Back>";
printMessage(status);
if(statusbox.getSelectedItem().equals("Busy"))
String status = "<Busy>";
printMessage(status);
if(statusbox.getSelectedItem().equals("Out To Lunch"))
String status = "<Out To Lunch>";
printMessage(status);
if(statusbox.getSelectedItem().equals("On The Phone"))
String status = "<On The Phone>";
printMessage(status);
//the emoticons events...
if(emoticons.getSelectedItem().equals("Angry"))
String status = "<Angry>";
printMessage(status);
if(emoticons.getSelectedItem().equals("Sad"))
String status = "<Sad>";
printMessage(status);
if(emoticons.getSelectedItem().equals("Shocked"))
String status = "<Shocked>";
printMessage(status);
if(emoticons.getSelectedItem().equals("Happy"))
String status = "<Happy>";
printMessage(status);
if(emoticons.getSelectedItem().equals("Crying"))
String status = "<Crying>";
printMessage(status);
if(emoticons.getSelectedItem().equals("Laughing"))
String status = "<Laughing>";
printMessage(status);
if(emoticons.getSelectedItem().equals("Laughing My Ass Off!"))
String status = "<Laughing My Ass Off!>";
printMessage(status);
//if the colour button is clicked
if(event.getSource() == colourButton)
//create a new colour chooser
colourchoo = new JColorChooser();
//create the dialog its shown in
JColorChooser.createDialog(colourButton, "Choose your background colour", true, colourchoo, this, this);
//now show the dialog
Color col = JColorChooser.showDialog(sendMsgButton, "Choose your background colour", Color.GRAY);
//when a colour is chosen it becomes the bg colour
theWholeApp.setBackground(col);
rpanel1.setBackground(col);
rpanel2.setBackground(col);
rpanel3.setBackground(col);
rpanel4.setBackground(col);
rpanel5.setBackground(col);
lpanel1.setBackground(col);
lpanel2.setBackground(col);
lpanel3.setBackground(col);
lpanel4.setBackground(col);
lpanel5.setBackground(col);
//if the connect button is clicked
if(event.getSource() == (connect))
//get the txt entered into ip addy field & port num fields with a text check...
if(hosty.getText().equals("") || portnumfd.getText().equals("") || nickName.getText().equals(""))
JOptionPane.showMessageDialog(this, "You cant connect! \nThis is because the either the \n0 - HostName\n 0 - Port Number \n0 - Your Nick \nIs Missing...");
else
//get details and connect
username = nickName.getText();
String ipay = hostfield.getText();
String porty = portnumfd.getText();
connectto(ipay,porty);
* This method is similar to an append method in that it allows msgs recieved by the server to
* be displayed in the conversation window. It also deals with the self comm mode as if its disabled
* then no messages from the sender will be displayed.
public void moveTextToConvo(String texty)
//check
if(ignoreyourself == true)
ignoreyourself = false;
else
//If self comm is on the send message as normal
if(talktoself)
conversationDisplay.setText(conversationDisplay.getText() + texty);
else
//check message isnt sent by the current client - if it is ignore it!
if(texty.startsWith(nickName.getText()))
ignoreyourself = true;
else
conversationDisplay.setText(conversationDisplay.getText() + texty);
//allows the scroll pane to move automatically with the conversation
conversationDisplay.setCaretPosition(conversationDisplay.getText().length());
* This method (connectto) is called if the button's clicked and also sets up a relation
* between the client and clienttoserver class
public void connectto(String ipa,String portNO)
//portNO needs to be changed from string to int
int portNum = new Integer(portNO).intValue();
try
//creates a socket
socky = new Socket(ipa, portNum);
writer = new PrintWriter(socky.getOutputStream(), true);
ClienttoServer cts = new ClienttoServer(socky, this);
cts.runit();
//give user a prompt
JOptionPane.showMessageDialog(this, "You're now connected!");
catch(UnknownHostException e)
System.err.println("Unknown host...");
//prompt the user
JOptionPane.showMessageDialog(this, "Failed to connect! \nPlease try again...");
catch(IOException e)
System.err.println("Could Not Connect!");
//prompt user
JOptionPane.showMessageDialog(this, "Error! \nCould not connect - please try again!");
* This method sends msgs from current client to server, sends username and then the message.
* This is split into two different messages as the "\n" is used.
public void printMessage(String mess)
writer.println(usernamey.getText() + " says: \n" + mess);
//then clear the text in the message creation area...
createMsg.setText("");
* Accessor method to retrieve userName
public String getUName()
return username;
* Disconnect this user from the server so that they can no longer recieve/send messages
public void dropconnection()
try
//Start to close everything - informing user
writer.close();
socky.close();
//Give the user info on whats happening
JOptionPane.showMessageDialog(this, "You are now disconnected \nYou will no longer be able to \nsend and recieve messages");
System.out.println("A user has left the conversation...");
catch (IOException e)
System.err.println("IOException " + e);
The Server Class:
import java.net.*;
import java.io.*;
* This class works in sync with the ServertoClient class in order to read
* messages from clients and then send back out to all the active clients. Due to
* the usage of threading multiple clients can use this server.
* Once again some of this code is from Florians 2005 tutorial work.
public class Server
private ServerSocket server;
private ServertoClient threads[];
private static int portNo = 2250;
private static String Host = ""; //find method to retrieve ip
private int maxPeeps = 20; //20 people can talk together but this can be altered
* 1st Constructor - has no params
public Server()
* 2nd Constructor - allows for port number setting
public Server(int portnumber)
portNo = portnumber;
* 3rd Constructor - allows for port number & max users
public Server(int portnumber, int maxiusers)
portNo = portnumber;
maxPeeps = maxiusers;
* This method is to constantly listen for possible messages from clients
public void listener()
//set the time out of method to just under a minute
final int waitingTime = 500000000;
//a boolean variable to keep it waiting
boolean keepWait = true;
//create a threads array of length maxpeeps
threads = new ServertoClient[maxPeeps];
//define a variable that will be used as a count of the no of threads
int x = 0;
try
//open a new socket on this port number
server = new ServerSocket(portNo);
catch (IOException e)
System.err.println("IOException " + e);
return;
//while the keepWait is true and the no. of threads is less than the max...
while(keepWait && x < maxPeeps)
try
//set the timeout, this is the waitingTime (50 secs)
server.setSoTimeout(waitingTime);
//listen for connection to accept
Socket socky = server.accept();
System.out.println("A New User Has Connected");
//creates a new thread and adds it to array
threads[x] = new ServertoClient(this, socky);
//the thread begins
threads[x].start();
catch (InterruptedIOException e)
System.err.println("The Connection Timed Out...");
keepWait = false;
catch (IOException e)
System.err.println("IOException " + e);
x++; //increment no. of threads
//if waitingTime is reached or there are too many threads then server closes
try
server.close();
catch(IOException e)
System.err.println("IOException " + e);
return;
* This prints the string to all active threads
public void printAll(String printy)
for(int x = 0; x < threads.length; x++)
if(threads[x] !=null && threads[x].isAlive())
threads[x].sendMsg(printy);
* Main method for the server, creates a new server and then continues to listen
* for messages from different users
public static void main(String[] args)
Server chatsession = new Server();
System.out.println("The Server Is Now Running on port NO: " + portNo);
System.out.println("And IP Address: " + Host);
chatsession.listener();
[/code
The ServertoClient Classimport java.lang.Thread;
import java.net.*;
import java.io.*;
* This is the ClienttoServer class that acts as an intermediary between the server
public class ClienttoServer extends Thread
private Socket socky;
private BufferedReader bready;
private boolean active;
private Client client;
* This is the constructor to create a new client service
public ClienttoServer(Socket socket, Client cli)
socky = socket;
active = false;
client = cli;
//try to read from the client
try
bready = new BufferedReader(new InputStreamReader(socky.getInputStream()));
catch (IOException e)
System.err.println("IOException " + e);
* This method reads in from the client
public void runit()
active = true;
while(active == true)
{//continue to read in and then change the text in the conversation window
try
String message = bready.readLine();
client.moveTextToConvo(message + "\n");
catch (IOException e)
System.err.println("IOException " + e);
active = false;
And finaly the servertoclient class
import java.net.*;
import java.io.*;
import java.lang.Thread;
* This clas provides the services that the server uses
public class ServertoClient extends Thread
private Socket socky;
private Server server;
private BufferedReader bready;
private PrintWriter writer;
* This constructor sets up the socket
public ServertoClient(Server theServer, Socket theSocket)throws IOException
socky = theSocket;
server = theServer;
//sets up the i/o streams
writer = new PrintWriter(socky.getOutputStream(), true);
bready = new BufferedReader(new InputStreamReader(socky.getInputStream()));
* This method keeps listening until user disconnects
public void run()
boolean keepRunning = true;
try
//keep listening 'til user disconnects
while(keepRunning = true)
final String tempmsg = bready.readLine();
//is there a message (if yes then print it!)
if(tempmsg == null)
else
server.printAll(tempmsg);
dropconnection();
catch (IOException e)
System.err.println("IOException in thread " + Thread.currentThread() + ": " + e);
* This method is for when a user disconnects from the server...
public void dropconnection()
try
bready.close();
writer.close();
socky.close();
catch (IOException e)
System.err.println("IOException in thread " + Thread.currentThread() + ": " + e);
System.out.println("A User Has Disconnected...");
* This method prints the message
public void sendMsg(String msg)
writer.println(msg);
}Thats it any help would be much appreciated
Cheers.Like the previous poster indicated: try to find a minimal example that shows the error your experiencing.
One thing that seems bogus is the Server.listener() method. For one thing, it can increment x even if no new connection has been established (e.g., x will be incremented if an exception is caught). -
System Overload & How to get the best G4 Performance
Okay all you Logic and OSX Gurus. I need your help. I've finally made the LOGIC leap from OS9 and have hit the SYSTEM OVERLOAD wall like many of you before me.
I've been pouring over this, and many other Forums and Blogs, for about two weeks now, and have tried many of the fixes / solutions to no avail. I estimate I'm now getting about 25% of my OS9 Logic performance from Logic in OSX.
One specific case in point is this. A four minute song sketch. No tempo changes. Four midi tracks, 6 Audio instruments and 2 EFX (1 Guitar Amp Pro, 1 Space Designer that's no even being used).
I have unsuccessfully tried to Bounce this to disc for two weeks now. The AUDIO and DISK I/O Meters barely register until the GUITAR AMP PRO track brings the AUDIO METER up to about 1/3rd usage. At various points in the Bounce the G4 will completely FREEZE, and I will have manually restart.
THINGS I HAVE TRIED, and continue to try are:
- Repairing Permissions
- Trashing Preferences
- Updating MOTU Drivers
- Changing Processor performance setting - which I cannot do BTW, because my system does not seem to support this option.
- Closing all Widgets
- Freeing up more Space on my Mac OSx startup disk (I now have 78.41 Gig available on a 114.49 Gig drive)
- Run Cocktail to clean up System logs and temporary files
- FREEZING TRACKS as a temporary 'fix'. This did nothing BTW but add more strain to the CPU and I still had about 1/3rd the usage with my GUITAR AMP Plugin (and it still crashed).
- Increased AUDIO BUFFER to 1024
So, (and I guess this is really two sides of the same question)...
1) How do I FIX this SYSTEM OVERLOAD problem, and
2) How do I "optimize" my Dual 1.25 G4 in order to get the best performance possible out of LOGIC PRO?
OTHER QUESTIONS I HAVE ARE:
- Does the G4 have the processing power needed to run LOGIC PRO?
- I'm confident adding RAM will "help" (can't hurt), but am I really dealing with a RAM Problem here or, again, can these processors really handle it?
BTW - I'm not looking for an excuse to go shopping for a Quad G5 (I mean who needs an excuse... . But, I'm really trying to determine if at the end of the day I will spend money on RAM, Hard Drives, whatever..., and then still be frustrated and end up shopping.
- Are SCSI drives a problem with Tiger / Logic? These Cheetah drives are fast (10,000 RPM), reliable, and have been great drives to record on. I'm trying to do this simple bounce to one of the Cheetahs and as I said it's just not happening.
- Does the startup volume size effect performance?
- Does the amount of free space on the start up drive effect performance?
- Firewire 400 vs 800? My sample library is on the Firewire drive, and I'm thinking this does not pull a lot on the CPU as these get loaded into memory before playing? Am I right about that? It is Firewire 400.
A long letter and a lot of questions. I thank you all in advance for any answers, guidance or direction you can give. Please also let me know if there is something I HAVEN'T asked, looked at or should be doing.
Best,
Kevin
Kevin Saunders Hayes
SYSTEM SPECS
Machine Name: Power Mac G4
Machine Model: PowerMac3,6
CPU Type: PowerPC G4 (3.3)
Number Of CPUs: 2
CPU Speed: 1.25 GHz
L2 Cache (per CPU): 256 KB
L3 Cache (per CPU): 2 MB
Memory: 1 GB
Bus Speed: 167 MHz
Boot ROM Version: 4.4.8f2
Logic 7.1.1 (885)
Pro Application Support 3.1
MOTU 896 - Latest drivers
2 - Seagate Cheetah 9 gig SCSI drives
1 - Oxford Firewire (Up to 400 Mb/sec) with EXS Library
G4 Duel 1.25 Mac OS X (10.4.3)And after months of using Express, and a week of
using Logic, I hadn't had a system overload until
today. Now I'm having them all the time. It wasn't a
set up change, it wasn't running on the battery, it
wasn't running software monitoring, it's set up with
512 i/o buffer, medium processor buffer. And it
wasn't brought on by number of tracks - that's for
sure. After it started happenind and I took a break &
came back, I was sitting on my couch, Powerbook in
my lap, tapping a beat in with the onscreen
keyboard.... a SINGLE instrument, mind you. NO plugs,
no other tracks of ANY kind. And it happened.
There's a lot of great, relevant and very helpful info on this forum and it all helps and it all counts. But..... so many people are suffering this when moving up to Pro 7 from either Pro 6 or Express. One expects a change in system load when a major update comes along but more and more people are reporting that simply recording 1 or 2 tracks of audio, pure, no plug-ins or EQ is causing an overload whereas in the previous version(s) this was easily accomodated. This, you may have guessed, has happened to me as well. Are we to accept in 1 version increment (albeit a major one) there is such a massive increase in demand from hardware that you cannot record a pure no-plug-in stereo track? When going back to 6.4.3 it will happily record 8 at once, let you EQ and reverb and then do another 8 AND then another. With no troble at all.
It is pointing more and more towards fundamental flaws in the programming. Did L7 come out too soon? Are we just beta testing what is pro software? We are only on 7.1.1 and 6 went to 6.4.3 but at no stage was it this bad at the fundamentals of what the App is for. I love Logic, I really do, but I think, even with all the great help we are fighting what Apple should be addressing. Not that you can find/contact/talk to or get any sort of response from them.
I have tried but have gone back to 6.4.3 until 7.1.2 or even 7.2 appears, but I'm not paying for 7.2. My £200 upgrade from 6.4.3 is now sitting on a shelf desperately wanting to use it. -
Hi!
My program is ok but I have problem with my second constructor without
parameter. How do I write this constructor? toString method is ok and can reache first constructor but not the second constructor. and how do I call it in my main method.
class ComplexNumber
private double re;
private double imag;
public ComplexNumber ( double real, double imaginary )
re=real;
imag=imaginary;
public ComplexNumber()
re= ;
imag= ;
public double getReal( )
return re;
public double getImaginary( )
return imag;
public ComplexNumber add ( ComplexNumber x )
ComplexNumber newComplex = new ComplexNumber();
ComplexNumber MyComplex = this;
newComplex.re = MyComplex.re+x.re;
newComplex.imag = MyComplex.imag+x.imag;
return newComplex;
public static final ComplexNumber add ( ComplexNumber x, ComplexNumber y )
ComplexNumber newComplex = new ComplexNumber();
newComplex.re = x.re+y.re;
newComplex.imag = x.imag+y.imag;
return newComplex;
public static final ComplexNumber sub ( ComplexNumber x, ComplexNumber y )
ComplexNumber newComplex = new ComplexNumber();
newComplex.re = x.re-y.re;
newComplex.imag = x.imag-y.imag;
return newComplex;
public static final ComplexNumber mult ( ComplexNumber x, ComplexNumber y )
ComplexNumber newComplex = new ComplexNumber();
newComplex.re = x.re * y.re - x.imag* y.imag;
newComplex.imag= x.re * y.imag + x.imag * y.re;
return newComplex;
/* public static final ComplexNumber div ( ComplexNumber x, ComplexNumber y)
public String toString()
if(imag< 0)
return re+" - " +(-imag)+" i ";
if(imag== 0)
return re+ " ";
if(re== 0)
return imag+" i ";
return re+" + " +imag+" i ";
public static void main(String[]args )
ComplexNumber com1 = new ComplexNumber(5,-6);
ComplexNumber com2 = new ComplexNumber(-3,4);
ComplexNumber myCom = new ComplexNumber();
System.out.println(" COMPLEX NUMBERS ");
System.out.println("--------------------------------------");
System.out.println(" Complex number 1: "+ com1);
System.out.println(" Complex number 2: "+ com2);
System.out.println("======================================");
System.out.println();
System.out.println(" Complex nbr1 + nbr2: "+ add(com1,com2));
System.out.println();
System.out.println(" Complex nbr1 - nbr2: "+ sub(com1, com2));
System.out.println();
System.out.println(" Complex nbr1 * nbr2: "+ mult(com1, com2));
System.out.println();
//System.out.println(" Complex nbr1 / nbr2: "+ divide(com1, com2));
System.out.println();
System.out.println("======================================");
System.out.println(" Complex nbr1 + nbr2: "+ com1.add(com2));
System.out.println(myCom.getReal());
System.out.println(myCom.getImaginary());
Now my constructor is ok but How can I count different
complex nbrs with this constructor. I mean in main metod.
public ComplexNumber()
re=4;
imag=5;
public ComplexNumber add ( )
ComplexNumber newComplex1 = new ComplexNumber();
ComplexNumber newComplex2 = new ComplexNumber();
ComplexNumber newComplex3 = new ComplexNumber();
newComplex1.re = newComplex2.getReal()+newComplex3.getReal();
newComplex1.imag= newComplex2.getImaginary( )+newComplex3.getImaginary( );
return newComplex1;
// main method
System.out.println(" Complex nbr1 + nbr2: "+myCom); -
JSR 82 problem with RemoteDevice constructor
Hi,
I am currently developing a Bluetooth PC/side application that i want to use to connect to a specific BD_ADDR (a smartphone). I am using Blue Cove SDK at the moment. I inherited the class RemoteDevice to construct a remote device object based on it's BD_ADDR. the codes are:
package test1;
import javax.bluetooth.*;
public class MyRemoteDevice extends RemoteDevice {
public MyRemoteDevice (String address) {
super(address);
}the problem is when i call this constructor and use it for service search request (using DiscoveryAgent.searchServices) it keeps generating error.
I am rather desperate, so any help is most welcome. probably u guys have another alternatives to connect to a specific BD_ADDR and service?
Kind Regards,
budabudHow do I get access to the source code of JSR 82?
Maybe you are looking for
-
Hi , I m creating a ALV report ,in that using set PF status i created push button , in alv output list if i click the push button pop up screen will come in that popup screen it displays the previous PF status, how to add my own PF status in that pop
-
System locks up during multiple Podcast downloads
I am using the latest 7.7 (43) iTunes and found that when I download Podcasts using the setting "Allow simultaneous downloads" my entire system totally locks up after about 1/2 hr. It's not just the Beachball effect but the whole computer just freeze
-
Final cut 604 won't let me import dv avi files
i just get file error, denied 0 recognized, unknown messages when i try to bring them in. these are straight dv avi files. qtplayer opens and plays them fine. i tried changing permissions so everybody can access them. no luck. the project is a dv pro
-
Should I learn Dreamweaver or FrontPage to make web pages?
Should I learn Dreamweaver or FrontPage to make web pages? Both Dreamweaver and FrontPage are WYSIWYG (What You See Is What You Get) web page editors. For basic web page development, either one will do the job. In a review in the October 2001 issue o
-
I know my iMac has a digital color meter in it (finder, utilities, digitalcolor meter. But its giving me sort of funky readings off my photo's. I'm making a zone system for my camera for a class (ugh awful assignment). I have Aperture, can I see the