Yes, and also remember to have your main class to ' extends JFrame ' that will take the above effects James advised.
Good luck! :)
Yes, and also remember to have your main class to ' extends JFrame ' that will take the above effects James advised.
Good luck! :)
DaniWebOS,
Going from your first piece of code, you needed to get the radius first before anything else.
All the calculations were otherwise useless as you were multiplying by 0. Then it would have been fine to begin with.
I hope this helps.
Regards,
Cleo
Ah, your correction to my sum made a lot of sense.
I could minus the y co-ordinate from the grid size and the image would be in the right position for each in each case...
for x ..
for y ..
grid[x][gridSize - y]
//paint image here
Thanks for your ideas!
I will actually test this later :)
Fotsung,
I'm assuming that you mean main class by "form" class.
When you are anywhere in the main class, like the event method, you construct another class in your package like so:
OtherClass anyName = new OtherClass();
//OtherClass being the name of your other class
Then, when you want to use a method from that other class you simply write:
anyName.OtherMethod();
//OtherMethod being the name of the other method in the other class!
//include any arguments required for method between the paramaters
When you are returning a result from the other method, the call would be:
int result = anyName.otherClass();
I hope this helps.
Regards,
Cleo
Hi David,
An alternative method instead of having to re-construct the scanner class is changing your while argument.
Where you have while next equals stop, I would have:
while(in.hasNextLine()){
Then you can use if statements to characterise between the types of input:
(inside while)
System.out.print("What is the employees name?");
name=input.nextLine();
if(in.hasNextFloat()) {
System.out.printf("What is %ss salary per hour?", name);
salary=input.nextFloat();
System.out.printf("How many hours did %s work?", name);
hours=input.nextFloat();
System.out.printf("%ss salary for this week is $%.2f", name,hours*salary);
}
You could easily have another if to check whether the input says "stop".
Hope you find this helpful.
Regards,
Cleo
Thank you for your response.
The height of the screen resolution or the grid?
Using the resolution seems a little unreliable as I would have to find the difference based on the grid size...which is going to be dynamically chosen.
For the grid, yes this would work for the position 5,5 of a grid size 5,5, but when the y position = 2, minus by the y grid size 5, this would result in -3, going off the grid.
Am I interpreting this correct?
The alternative method is employing the Scanner class.
Assuming you have completed this with the StringTokenizer class, this is the route I would have went with, and also to give you ideas of methods that can be used.
I prefer to make the variables public within the class:
Public class Test { //Test is the name of your java file, for example.
//Initiate your variables here
Scanner in;
int number;
int total;
When constructing the Scanner can now be used anywhere within the class. In comparison with the StringTokenizer class, you would use the useDelimiter() method instead.
public Test() {
in = new Scanner(System.in);
in.useDelimiter(",");
}
Then when receiving the numbers input with the nextInt() method you could add them up to the total variable. These variables could also be included with the public method or any other functions included within the class.
while(in.hasNextInt()){
number = in.nextInt();
total = total + number;
}
I hope this helps.
Regards,
Cleo
Dear all,
When printing a grid, for example a chess board, I was hoping it wouldn't have the same output as the console.
When I want the position to be grid[x][y] = 5, 5, it will place the counter in the bottom right corner in a 5x5 grid, (5,1) instead of the reverse in the top right corner.
I've used the usual inner for loop stepping through and drawing the line.
Anyone experienced this before and know how to deal with this?
Any advice would be much appreciated.
Thanks,
Cleo
Solved this one:
int result = in.getInt("test");
7
Thanks :)
Thanks James, that's removed the error. I just receive a 'cannot find symbol' message when trying to use the returned value. Do you know how I can use this value from this class in the other class now?
Hi all,
Trying to simply call method, (below) from another class and return the value found by the scanner. Please see below:
public int getInt(String prompt) {
System.out.print(prompt + "a");
//int result = in.nextInt();
if (in.hasNextInt()) {
x = in.nextInt();
y = in.nextInt();
sum = x+y;
System.out.print("sum" + sum);
}
int value = 5+5;
return value;
}
when I run this after compiling with no errors I receive the java.lang.NoSuchMethodError ... getInt(L/java/lang/String;)V at ...
Could you please advise how to return a value from the other class?
Much appreciated,
Hi All,
As shown below, I have already managed to disable all menu items from the QAT. However I would also like the menu option to be completely removed!
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<commands>
<command idMso="ApplicationOptionsDialog" enabled="false"/>
<command idMso="FileExit" enabled="false"/>
<command idMso="Help" enabled = "false"/>
</commands>
<ribbon startFromScratch="true">
<officeMenu>
<button idMso="FileCompactAndRepairDatabase" visible="false"/>
<button idMso="FileOpenDatabase" visible="false"/>
<button idMso="FileNewDatabase" visible="false"/>
<button idMso="QuickAccessToolbarCustomization" visible="false"/>
<button idMso="FileCloseDatabase" visible="false"/>
<splitButton idMso="FileSaveAsMenuAccess" visible="false"/>
</officeMenu>
</ribbon>
</customUI>
Any tips would be much appreciated,
Cleo
Thanks a lot BitBlt! I got it to work using QueryDefs :)
All I had to do is create the temporary table in the backend table, which made updating much easier, rather than updating a remote table with a local table. Then the update worked fine using the QueryDefs method.
Now I just have to do this throughout my whole database, all in the name of security.
There isn't a lot of information on how to do this on the web so I've posted my code syntax for anyone else looking to do this.
Set up the path to the back-end database:
Dim path As String
path = "C:\BackEndDatabase.mdb"
Set the database to the back-end database:
Set db = OpenDatabase(path)
Dim qDef As QueryDef
Create the update query in the back-end database using QueryDefs:
Set qDef = db.QueryDefs("UpdateQueryInBackEnd")
Within my queries that created the temp table, I added IN '"& path &"' to create the temporary table in the back-end database:
DoCmd.RunSQL ("SELECT DISTINCT [TBLs] INTO TEMP IN '" & path & "' FROM [TBLs] IN '" & path & "' WHERE [. . .] ;")
Now when updating the tables using QueryDefs, it worked fine:
qDef.sql = "UPDATE TBL1, TEMP SET TBL1.Score = [TEMP]![NewScore] WHERE [. . .]"
qDef.Execute
qDef.Close
Lesson learned: Insert and Update queries do not work with DoCmd.RunSql when inserting into or updating a remote database. These only work when QueryDefs are used.
Thanks,
Cleo123
Thanks for your help.
Access does not let me use ADO/OLEDB/ADODB .Connection due to the 'user-define type not defined'.
Your syntax does look correct although it's taken out the complexity of the remote and temp local table being in separate locations.
It seems as though manullay coding the backend links is too much trouble for what it's worth. Although it might be easier to run the queries straight from Access...
Hey all,
I have split an Access database not on the server. I have decided to VBA code the links, however I have reached a stall when attempted to VBA code the update query; updating the remote table with data from the local temporary table.
I have tried multiple things and the final state it is in is shown below:
DoCmd.RunSQL ("UPDATE TBLRemote IN '" & path & "', TBLLocal SET " & _
"(TBLRemote.[UpdateField] = [TBLLocal]![UpdateField]+1 WHERE . . .) ;")
path is the connection to the remote database, however this is not correct syntax. I am looking for advise on the correct syntax.
I would like to figure out how this fairly old method was carried out... Tips would be very much appreciated.
I have just solved this - It was relating to something else on the form, or more to the point; assigning variables outside a function - oops!
Sorry guys :)
Morning all,
Unfortunately I am currently working with Access VBA. I have a simple method; moving an object on a form:
button.Top = button.Top - 20
However on click, I receive the 'Invalid Outside Procedure' message, including:
*The exression may not result in the name of the macro, the name of the user defined function or event procedure
*There may have been an error evaluating the function, event or macro
Hope you experts can help :)
I don't think you can edit that. It is very difficult to do it and since it is auto generated you shouldn't. Better start over.
I prefer not to use the GUI builder because it does not allow to create dynamic gui components (a variable number of buttons during run time)
It is better to use it to align the components you want at the Frame and then write code that sets their properties.Where did you wanted to add the scrollbar. For component such as this gui builders can be tricky. I use them only for textboxes or single buttons.
It would take me hours starting over, and I get fed up of setting the co-ordinates of where exactly each component should go, especially when I'm pedantic.
Without getting wrapped up in the huge amount of auto code I have posted, do you know how I would control only this line to work:
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1090, javax.swing.GroupLayout.PREFERRED_SIZE))
For my other classes which I created without NetBeans I have simply used this line:
aFrame.add(new JScrollPane(aPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
And that works.
So do you think there is a way to maybe combine the syntax of the two different lines?
Hi all,
I thought it would be quicker to design using NetBeans, but now I'm finding that it's more trouble to work with NetBeans automatically generated garbage 'code'.
Anyhow, I've tried to remove its automatically generated code for the frame's scrollbar but that just totally messes up the layout of the whole frame; it hasn't even created a jpanel or constructed the class in the usual way so I can't even create my own the scrollBar and add it to the panel in the usual fashion.
Could anyone please advise me on how to edit this garbage below to get the scroll bar working. Would really appreciate it as this is for my dissertation!!
The auto scroll bar code has been put in bold:
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollBar2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(cmdCalendar, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(324, 324, 324)
.addComponent(cmdPreviousWeek, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmdNextWeek, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel9)
.addComponent(jLabel10))
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addComponent(jLabel7))
.addComponent(jLabel8))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
[B] .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1090, javax.swing.GroupLayout.PREFERRED_SIZE))[/B]
// .addComponent(jScrollPane1.VERTICAL_SCROLLBAR_AS_NEEDED, jScrollPane1.HORIZONTAL_SCROLLBAR_AS_NEEDED))
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12))
.addComponent(cmdPreviousWeek, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmdNextWeek, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmdCalendar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jLabel2)
.addGap(134, 134, 134) …
I've tested the statement edited below in mySql and it does return the record I expect. Althout when I try to print out to the terminal, it only gets up to the print out 'STEP 2' :
if(event.getSource() == search) { //if search button is clicked
System.out.print("STEP 1");
System.out.print("criteria" + criteria1);
if(chosenCriteria1.equals(search1)) {
//search 1 = firstname //search string
//chosenCriteria1 = firstname // (from combobox)
criteria1 = 1;
System.out.println("criteria 1: hellooooooo:" +criteria1);
}
if(criteria1 == 1){
getDBConnection();
try {
stmt = conn.createStatement();
if(stmt.execute("SELECT Firstname FROM Clients WHERE Firstname = '"+ searchCriteria1 + "' "))
{
rs = stmt.getResultSet();
System.out.print("STEP 2");
}
while(rs.next()) {
String name = rs.getString("Firstname");
System.out.println("name :" + name);
//Add to record List box
searchListModel.addElement(rs.getString(1).trim());
System.out.print("STEP 3");
}
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
return;
}
And I have added the model to the list :
searchListModel = new DefaultListModel();
searchListModel.addElement("TEST");
searchList = new JList(searchListModel);
"Test" is currently seen in the list box...
Hi developers,
I'm not sure if this is possible, but I've tried to add database elements to a list box.
There are no errors shown, but it simply does not work. Here is the code below:
if(criteria1 == 1){
getDBConnection();
try
{
stmt = conn.createStatement();
if(stmt.execute("SELECT Clients.Firstname FROM Clients WHERE Clients.Firstname= '"+ searchCriteria1 + "' "))
{
rs = stmt.getResultSet();
System.out.print("STEP 2");
}
while(rs.next()) {
//Add to record List box
searchListModel.addElement(rs.getString(1).trim());
System.out.print("STEP 3");
}
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
return;
}
statements, listbox, listmodel and criteria and all been previously initialised.
Thanks in advance,
Cleo
I'm not sure if this is the best way but I would like to display a list of addresses in a combo box where the columns come from different tables such as Countries, Cities and Types (work and home).
I don't want to display the countryID or cityID, etc. but for know I have simply selected all from the address table to start getting this to work.
Problem: From using the code below, only the first column appears.
if(vehicleAccessType == 1) {
getDBConnection();
try {
stmt = conn.createStatement();
if(stmt.execute("SELECT * FROM Collection_Addresses.CollectionAddressID, Collection_Addresses.AddressLine, Collection_Addresses.AddressLine2, Collection_Addresses.Postcode FROM Collection_Addresses, Clients WHERE Collection_Addresses.CollectionAddressID = Clients.CollectionAddressID")) {
rs = stmt.getResultSet();
}
while(rs.next()) {
cbCustomerAddresses.addItem(new AddressComboBoxItem(rs.getInt(1), rs.getString(2).trim(), rs.getString(3).trim(), rs.getString(4).trim());
}
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
return;
}
}
The combo box will display whatever value your toString() method returns, so just alter that method to return any representation you want.
The only purpose in making the TypeEntry structure at all was to associate some ID (or other) value with the label you want to present to the user.
The problem is that I want to show the INT, not a string, so I changed the TypeEntry to this:
class ComboBoxItemID {
private int number;
public ComboBoxItemID(int numberID) {
this.number = numberID;
}
public int getValue2() {
return number;
}
}
Following the same structure as before, but without the String value. When I system print the values selected I get the correct numbers (date and year) but the date and year combo boxes contain the name of my java file followed by $...
The returned object will be a TypeEntry object. You have to cast to that and use its getValue() method.
TypeEntry selectedType = (TypeEntry)combo.getSelectedItem(); int typeValue = selectedType.getValue();
Thanks for the response. Do you also know how you would go about showing only the ID? Since I've used Dates and Years as the ID and I would like to show the list of dates (1,2,3, etc.) and years (2008,2007, etc) in the combo box.
Cleo123
No problem, I fixed the problem!
TypeEntry typeentry = (TypeEntry)cb.getSelectedItem();
Integer Title = typeentry.getValue();
Thanks for the previously posted support :)
Hi Ezzaral,
Can you please explain how you get the Integer of the selected item?
Yes I can return the selected string by
combo.getSelectedItem();
but how do I get it's int returned by the getValue() method?
Thanks in advance,
Cleo123
its actually not a C program.Your program is in C++.Anyways
Which compiler you are using?
post a stand alone code so that we cant check the error!!
Okay, thanks for that, that was a stupid mistake, lol, I have not really got any experience with C++. I'm compiling it from the terminal window with g++ instead now.
If you don't mind, I have a new question with a new error.
I have a few of these:
error: ‘wordPointer’ was not declared in this scope
error: ‘malloc’ was not declared in this scope
so I passed wordPointer as a parameter (char* wordPointer
)
but then found this brought me further errors for each variable I've defined within a structure or the class.
How do I allow these variables to be used publicly?
bool caseInsensitivelyEqual(char* s1, char* s2) {
int i=0;
bool same=true;
while (s1[i] && s2[i] && same) {
same=(tolower(s1[i])==tolower(s2[i]));
i++;
}
if (s1[i] || s2[i]) same=false;
return same;
}
//Here are the variables I am using in my print method.
struct wordRecord {
char* [U]word[/U];
struct wordRecord* [U]next[/U];
};
class spellChecker {
protected:
struct wordRecord* wordList;
public:
spellChecker() {
wordList=NULL;
}
};
and the other 2 variables I am using for my print method are within
my case sensitive spellChecker class
struct wordRecord *root;
struct wordRecord *wordPointer;
root = malloc(sizeof( struct wordRecord));
root -> next = 0;
root -> word = dest;
wordPointer = root;
print method: I have …
Hi everyone, I'm new to C and have been given a C program to complete but found it includes many versions of the titled error for each class file.
Can anyone please explain why it occurs and how I could get rid of them?
Thanks,
Cleo
q2.c:5: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘spellChecker’
Example of a class:
class spellChecker {
protected:
struct wordRecord* wordList;
public:
spellChecker() {
wordList=NULL;
}
};
Sorry...Null Pointer Exception - Exception in thread "main"
I'm not sure if I'm doing this correctly but up to now I get an exception error. Can you see why? :
public void countHeap(){
System.out.println("input data:");
for (int i = 0; i < dataSet.length; i++) {
System.out.print(" "+dataSet[i]);
count++;
}
noDataElements = count;
formHeapTree();
}
public void formHeapTree(){
int unsortedSet[] = new int[noDataElements];
noDataElementsHalf = (noDataElements+1)/2;
System.out.println("\nheap Array");
for (int j = 0; j < unsortedSet.length ; j++) {
for (int i = noDataElementsHalf; i < noDataElements; i++) {
unsortedSet[i] = dataSet[j];
}
System.out.print(" "+ unsortedSet[j]);
}
sortLevel();
for (int j = 0; j < unsortedSet.length ; j++) {
for (int i = 0; i < noDataElementsHalf; i++) {
unsortedSet[i] = dataSet[j];
}
System.out.print(" "+ unsortedSet[j]);
}
}
public void sortLevel(){
System.out.print("\nheap array \n ");
for (int i = unsortedSet.length; i > 0; i--) {
int j = i-1;
//Parent must be smaller than child
if(unsortedSet[j] > unsortedSet[i]) { int temp = unsortedSet[i];
unsortedSet[i] = unsortedSet[j];
unsortedSet[j] = temp;
}
}
}
Thanks for the input, I really appeciate it although I have kept the same vector I already have and used your for vector method which was really beneficial; the canvas now paints more than one rectangle on the canvas!
However all of these rectangles use the same start point...It's to do with my for statement...The answer seems so clear which is why I've replied s late trying to do it sorry but yet I can't pinpoint how to solve it:
for(i = 0; i < vector.size(); i++){
Point a = (Point) vector.get(i);
//Get the top left corner
if (a.x < topLeftPoint.x && a.y < topLeftPoint.y)
topLeftPoint = a;
System.out.println("Top Left" + topLeftPoint);
for(j = 0; j < vector.size(); j++)
{
Point b = (Point) vector.get(j);
//Get the bottom right corner
if (b.x > bottomRightPoint.x && b.y > bottomRightPoint.y) {
bottomRightPoint = b;
System.out.println("Bottom right" + bottomRightPoint);
}
}
This code is under the construction/calculations of the rectangle.
I have two vectors; the first of which stores all 8 points and the second stores the rectangles.
I need a better way of obtaining the topLeftPoint and bottomRightPoint without looking through the for for the highest and lowest out of all points! I'm going to try and use the same method as I just did with the last method..I think this may work..
Cleo
Hi all,
Background:
I am dealing with graphical objects on a canvas in which the user draws four lines and out of these four lines I get the top left corner, bottom right corner and figure out the width and height from these two points.
Problem:
I have completed this but I would also like to use a for loop to get every set of 4 integers in my vector which represent a rectangle and draw it to canvas. Overall printing every rectangle drawn on the canvas. The first rectangle prints fine although the program freezes there after.
Here is the for loop I have tried to use to print of all rectangles drawn on the canvas which currently prints the top left corner point and bottom right corner point out of all rectangles:
for(int z=0; z < 5; z++) {
//for(int i =0 ; i < 5; i++){
rectangle1 = (Point) vector.get(z);
//Point b = (Point) vectorRect.get(i);
graf.drawRect(topLeftPoint.x, topLeftPoint.y, width, height);
}
//z = i+1;
//}
This probably relates to these points which are used prior to calculating the width and height:
bottomRightPoint = (Point) vector.get(0);
topLeftPoint = (Point) vector.get(0);
A similar for loop is probably required; even psuedocode would be very helpful.
Thanks in advance,
Cleo
I've solved it, never mind! Thanks anyway - The empty text was set to null so I just changed null to "" and it worked. I wish the java website said that it made a difference!
Thanks, I got source is cmdSaveSettings so that means theres something wrong with my second if statement?
Sorry I don't understand, message saying program is inside ActionPerformed?
From what I got from that was
JOptionPane.showMessageDialog(add.ActionListener.this)
but thats not even the correct syntax...Sorry I'm new to this, could you explain in a bit more detail?
No that's not it...
I'm trying to show a dialog message if the user clicks a button and a text field is empty.
Action listener -
if(event.getSource() == cmdSaveSettings)
if(txtPlayerOneName.getText().equals(emptyText))
{
JOptionPane.showMessageDialog(null, "alert", "Please enter player one's name", JOptionPane.ERROR_MESSAGE);
}
Ive add an action to listener to the button and the textfield:
(mouse listener also as removes original text on click which works fine)
cmdSaveSettings = new JButton("Save Settings");
this.cmdSaveSettings.addActionListener(this);
txtPlayerOneName = new TextField("Player One", 15);
this.txtPlayerOneName.addMouseListener(this);
this.txtPlayerOneName.addActionListener(this);
I had to repaint after the animation because after the animation played my grid which was painted before hand disappears and I didn't know why so I just added it again which stopped this happening. All of this is under the paint method as the animation involves moving an oval downwards (the dropping of the counter in connect 4). This is called every time the mouse is clicked (the player takes their turn). The buffered image code is also under the paint method and update is called whenever repaint is called:
public void update(Graphics g1)
{
paint(g1);
}
I have called repaint under:
mousemoved to get x and move the counter above the grid (code shown above)
mouseclicked to make the new inserted counter appear in my grid
----Just found the problem!
I also had repaint under action listener which was supposed to be part of the animation code so I commented it and then commented the extra repaint I had after the animation code which got rid of the constant flickering (which is the program being repainted all the time) which occurred after the animation was played.
Now the flickering own happens during the animation as I am repainting the oval to move downwards and whenever I move the mouse (to move the counter that follows the mouse over the grid).
Wish this repainting weren't noticeable, but I have to repaint to show the updated image...Don't think theres anything else I could …
The most illogical thread I've EVER read. Making a virus and then creating an Anti-virus for FREE. Developing a virus at all is kind of silly, not to mention running the code on your main computer.
That's the thing, I already tried bufferGraphics and it did work for everything apart from the animation. The code I have for it is:
// The object we will use to write with instead of the standard screen graphics
Graphics bufferGraphics;
// The image that will contain everything that has been drawn on bufferGraphics
Image offscreen;
//Variable to store width and height of the application
Dimension appSize;
//Get the width and height of the app
appSize = getSize();
// Create an offscreen image to draw on which is the same size as the app
offscreen = createImage(appSize.width,appSize.height);
//Everything that is drawn by bufferGraphics will be done on the offscreen image
bufferGraphics = offscreen.getGraphics();
// Clear everything that has been drawn before
bufferGraphics.clearRect(0,0,appSize.width,appSize.width);
bufferGraphics.drawImage(offscreen,0,0,this);
There were 3 missing lines compared to yours so I tried to add them in but got an out of memory awt Event error so I thought it best to just keep what I've got. Do you know if there
is anything other than this?
I have had to repaint a couple of times because of a moving shape I have added to my program whenever the mouse is clicked. I also have a moving shape that follows the mouse over a grid as well which doesn't help a lot, could you please tell me how to reduce this flickering?
The code I have used for the moving counter is:
/* Show the counter appearing above the columns the mouse is over between the restricted co-ordinates and set the counter to the colour depending on the player turn */
if(xPosCounter >= leftXPos && xPosCounter <= rightXPos)
{
g.setColor(counterColour);
g.fillOval(xPosCounter-(counterWidth/2), yPos - counterHeight*grid[0].length, counterWidth, counterHeight);
}
And for the animation I have used a timer with a delay of 100 frames per second and this is repainted in action performed but what really started the bad flickering was when I had to add a repaint here:
int lowestYPosition = lowestRow;
lowestFallingPosition = (lowestYPosition * (counterHeight + gapBetweenCounterSlots)) + topYPos;
//Droppping counter
if(unfrozen == true && yPositionMovingCounter < lowestFallingPosition) { //Ypos starts at the beginning of the grid and ends at the bottom
startAnimation();
yPositionMovingCounter = yFwdLine (topYPos,15);
g.setColor(Color.red);
g.fillOval (centeredCounterInColumn, yPositionMovingCounter, counterWidth, counterHeight);
repaint();
If I didn't my grid disappeared. I could really do without this flickering because it makes my program look rubbish. Anyone know any methods for this?
This is a connect four game and I'm trying to show the counter falling. What I have so far is this which is in a for loop:
while(fallingCounter == true && x[j][i] < playerTurn)
{
//Move the counter vertically down the grid's rows appearing to fall
fallingCounter();
g.setColor(counterColour);
//counterWidth = counterWidth - 10;
topYPos = topYPos + 10;
//centeredCounterInColumn = centeredCounterInColumn +10;
g.fillOval(centeredCounterInColumn,topYPos, counterWidth, counterHeight);
}
This and similar versions of this, in and outside the for loop and in a do loop have shown the counter rapidly falling continuously showing previous ovals drawn (so it shows the whole falling path like a long rounded line going downwards). It only stops when I say until < grid[0].length in the while/for but I'm still left with the former problem and I want the "animation" to stop before a counter in the column - not just go over already inserted counters in the column till it reaches the bottom. I've been trying this for at least 5 hours now so I really would appreciate help with this one. I really would like to do this.
lol yes I have the right name, I've looked at for a long time and row2 is a panel:
row1 = new JPanel();
row2 = new JPanel();
pNorth.add(row1, BorderLayout.NORTH);
pNorth.add(row2, BorderLayout.SOUTH);
row1.setBackground(Color.white);
row2.setBackground(Color.white);
I don't know, I've tried to resize it to a smaller size now and still doesn't work. I run out of ideas :( I know the panel works because it's added other buttons...
Hi, I've followed the example in my lecture notes and it doesn't work! I want to add an image to a label and then add that label to my sub north panel. I want to do this with creating a new class...I'm not sure if I need an "image loader" or to repaint it from the paint method...This code seemed to work for my lecturer:
logo = new ImageIcon("JavaProgram2/LogoGIF.GIF");
logoLabel = new JLabel(" " + logo);
logoLabel.setOpaque(true);
logoLabel.setBackground(Color.white);
row2.add(logoLabel); //row2 is the name of the panel
The label and logo is initialised at the beginning of my application with the Jlabel and ImageIcon var type, I have imported it, tried it without the file path with solely the file name and have tried different file types. I did look at previous posts about this but the code seemed a bit lengthly considering that I simply want to add an image.
Anyone got any ideas on how I could do this easily?
Thanks a lot guys, it now work and returns 24. If I took the static out it says a non static method cannot be referenced from the static method - makes sense - must be from static to static. I didn't get the beging for the error message before 'at' because as shin' said it was looping and so DOS cuts off the beginning.
I'm really impressed with how it works without a do while/ loop because it's taking away 1 each time to find factorial...quite unsure about that worked (?) but I figured that I didn't need to initialize x to anything because whatever number i put into fact(x) would just override it anyway.
I'm guessing that it calls fact(x) until it reaches 1?
Thanks again for solving the problem(s) and sorry for the late reply I've been doing my 'real' java coursework!
Thanks a lot, return methods kind of represent the value of the method then...But what should I do when the fact(4) statement prints 'at recursiveTest.fact(recursiveTest.java:31)' ?
That's all of the code - it's just a small example to understand how recursion/return values works.
I have been trying to write simple return statements and print the result of the return. I have read books such as O-Reily and have used examples but find that the examples don't work either so I guess I just need human communication!!
First I have tried this return method - no errors:
public class recursiveTest {
public static int fact(int x)
{
x = 5;
if(x==1 || x==0) return x;
else {
return x * fact(x-1);
}
}
public static void main(String args[]){
}
}
Isn't the return supposed to print to system out? If it isn't I also wrote a method to print factorial(x) but that is usually an unreachable statement and a missing return. So how do you print the return value :icon_confused: ? Is anyone able to explain?
import mypackage.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.event.MouseInputListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.awt.Color;
import java.awt.Shape;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Point2D;
import javax.swing.JApplet;
import javax.swing.*;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class ProgramProj extends JFrame implements ActionListener, MouseInputListener
{
JPanel pNorth;
JPanel row1;
JPanel row2;
JPanel pSouth;
JPanel pEast;
JPanel pWest;
JPanel pCenter;
JFrame frame;
CircleComponent mycounter;
Boolean c;
Shape[][] grid; // Grid array
int rw; // Grid circles width
int rh; // Grid circles height
int GapConstant; // Gap between each circle in the grid
int xpos; // x position of grid
int ypos; // y position of grid
int xcolpos; // Position of where column chosen
int ycolpos; // Position of where column chosen
int xposcounter; // Position of the moving counter
int cypos;
int leftxpos;
int rightxpos;
int counterxpos;
int[][] x;
/* if(xcolpos >= xpos -(GapConstant/2) && xcolpos <= xpos + (rw+(GapConstant/2)))
{
System.out.println("Column 1");
}
else
{
System.out.println("Not Column 1");
}
*/
public class MouseMovedListener implements MouseMotionListener
{
public void mouseMoved(MouseEvent e)
{
}
//http://hivemind.apache.org/hivemind1/hivemind/apidocs/src-html/org/apache/hivemind/HiveMind.html#line.158
public void mouseDragged(MouseEvent e) {}
}
public void mouseClicked(MouseEvent e)
{
xcolpos = e.getX(); //get the x coordinate after mouse is clicked on the applet
calculatecolumn(); //call the calculate column method
}
public void mouseMoved(MouseEvent e) {
xposcounter = e.getX();
for(int i = 0; i <= grid.length; i++)
{
//Center the grid
leftxpos = pCenter.getWidth()/2 - ((GapConstant*(grid.length)+(grid.length*rw))/2) + rw*i + GapConstant*i;
rightxpos = leftxpos +rw;
//Show the counter appearing above …
I'm a little lost now. When I get rid of extends JComponent it doesn't like "pCenter.add(mycounter);" but even when I have got that it's not doing anything; not even letting a circle appear. I haven't used the same x,y,h,w attributes as in the class because the variables I want to use are in the main class and it has problems when I try to use them in the separate CircleComponent class. I haven't defined the same variables from the main class into the separate class just in case the value of the variables change.
My center panel doesn't have it's very own paintComponent() method because its just under public ProgramProj() {pNorth = new JPanel(); ...} My application does have its own public void paint (Graphics graf) but I don't know how it can draw the circle based on the x position of the mouse as it needs MouseMoved(MouseEvent e).
I am actually trying to make a connect 4 game where the counter moves above the grid where the mouse is over the grid.
Ok, you're doing something quite different than I assumed. I'm not sure how you are placing that component withing whatever container you're using, but the paintComponent() method will need to use the Graphics2D.draw(java.awt.Shape) method to render the ellipse
public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.setColor (Color.red); playerCounter = new Ellipse2D.Double(30,30,30,30); g2d.draw(playerCounter); }
Your mouseMoved event will need to postion/size that component as needed in the container and then call repaint() for that container.
Edit: Post collision there, you figured out the Graphics2D part I see. How are you placing this component? It will have to be in a container of some sort for it to be rendered.
I'm using panels as my container...Will panels work for this? I've replaced the code with your paintComponent code...Still no errors but not working. I've tried placing the actual circle to the center panel using "pCenter.add(mycounter);" and refreshing both in the MouseMoved method and within the public void init() method just in case.
P.S. I've also set my locations of the circle "mycounter = new CircleComponent(xposcounter,ypos,rw,rh);" (xposcounter is the position of the mouse, rw = width, rh = height)