Unable to add objects which extend a JPanel to my JFrame class - object

I'm working on a game and I'm trying to add a JPanel to the JFrame. I have a separate class which extends JPanel and I create a new object which again, extends JPanel.
However, I get this error: "The method add(Component) in the type Container is not applicable for the arguments (mainMenu)" (mainMenu is the class which extends JPanel).
It suggests adding an argument to match 'add(Component, Object)'
I am at a loss in trying to fix this especially because later in my code, I use the same add argument to add an object whose class extends a JButton. Any help is greatly appreciated.
I have tried creating a regular JPanel and adding that which worked.
(JFrame class)
public class gardenRunner extends JFrame {
public static void run(String[] args)
{
new gardenRunner()
}
public void gardenRunner()
{
mainMenu m = new mainMenu();
add(m); <-- gives error
}
(JPanel class)
public class mainMenu extends JPanel {
public mainMenu()
{
super();
setSize(60, 60);
}
I would expect this to add a JPanel to my JFrame but this results in an error.

Thanks for the help, turns out Eclipse was acting a little buggy and this worked when I deleted my JPanel class and made a new one. Thanks again.

Related

Is there any way to access FXML variables in classes other than Controller Class?

I'm curious that is there any way to call #FXML variables in not only Controller Class but also in another classes. Well actually i'm dealing with SVGPath nodes and trying to implement various kind graphs. However i dont wanna write the whole code in only Controller Class. I will appreciate if you can help and also give clear answers. So thanks anyway :)
EDIT: let me introduce a simple example about my issue.
Controller class code section;
public class RiskControllerClass implements Initializable {
#FXML private SVGPath NA_1; // Alaska
#FXML private SVGPath NA_2; // NorthWest_Ter
.
.
}
Territory class which refers to a vertex in a graph
public class Territory {
public Territory(SVGPath nodeSVG, int territoryID, int playerID){
this.playerID = playerID;
this.territoryID = territoryID;
this.nodeSVG = nodeSVG;
this.label = nodeSVG.getId();
this.adjacencyList = new LinkedList<>();
this.edgeSet = new LinkedList<>();
}
.
.
}
so i want to implement my graph another class than Controller class something like GameBoard
public class GameBoard {
// Want to call #FXML instance variables here
}
There is no other way than to access your controller and call methods from it. There is no magical way an #FXML annotation makes private variables globally available. #FXML is only used to mark certain fields for the FXMLLoader so he can access them via reflection in the instantiation process of your FXML - nothing else.
Refere to this questions on how to access the controller:
Accessing FXML controller class
JavaFX: How to get stage from controller during initialization?

Not able to use Custom XIB outlets with UICollectionViewCell

When accessing to outlets from my CustomClass : UICollectionViewCell, they are appearing as not initialized and can not set a proper value.
Every example I've seen it uses a plain Class (no XIB) to set the UI.
[Register("CustomCommentCell")]
public partial class CustomCommentCell : UICollectionViewCell
{
public static readonly NSString Identifier = new NSString("CustomCommentCell");
public CustomCommentCell () : base()
{
}
public CustomCommentCell (IntPtr handle) : base (handle)
{
}
public void updateData()
{
this.lblComment.Text = "Test";
}
}
On the other hand, I have registered the Class:
this.tableComments.RegisterClassForCell (typeof(CustomCommentCell),commentCellId);
and have the GetCell properly set.
However, when trying to set the outlets to a specific value, it indicates it is null. (this.lblcomment = null) while it should have been a UILabel initialized.
Any clues?
to create the Custom CollectionViewCell using XIB. do the following
1) create C# class which inherits from UIcollectionViewCell
[Register("MyCustomCell")]
public class MyCustomCell : UICollectionViewCell
{
public static readonly NSString Key = new NSString ("MyCustomCell");
[Export ("initWithFrame:")]
public MyCustomCell(CoreGraphics.CGRect frame) : base (frame)
{
}
public override UIView ContentView {
get {
var arr= NSBundle.MainBundle.LoadNib ("MyCustomCell", this, null);
UIView view =arr.GetItem<UIView> (0);
view.Frame = base.ContentView.Frame;
base.ContentView.AddSubview (view);
return base.ContentView;
}
}
}
2) Add a IphoneView XIB file has the Same Name as that of Class created in step 1
3) Open XIB in XCODE and do the Following Changes
3.1)Select the FileOwner set the Class same name as Step 1
3.2)Select The View Set the Class name UIView
4) Design Your XIB Accordingly
I can't follow quite the problem you are seeing. What is a "Custom XIB outlet"? Why is this question tagged "custom-controls"? Is there some example code or pictures you can show to help explain the problem?
The approach I use for UICollectionViewCell's is the same as I use for UITableViewCell - see the tutorial - http://slodge.blogspot.co.uk/2013/01/uitableviewcell-using-xib-editor.html
Update: From the code you've posted as a comment (not sure if it's complete or not), I think it would be useful for you to follow through that tutorial. There are a few steps to complete including registering the custom class name and including using RegisterNibForCellReuse - one of those will probably fix this for you.

PowerMocking static does not return expected object

I have a problem mocking Calendar.getInstance(). As you now this method returns a Calendar - the object I am mocking.
Right now my code looks like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Calendar.getInstance() gets called various times in surveillance.checkDatabase() and every time it is a new object and not the expected mock of Calendar.
Can anyone see what I am doing wrong?
It seems that you need to add the target test class in the PrepareForTest tag:
#PrepareForTest({ Calendar.class, Surveillance.class })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Calendar.class, Surveillance.class })
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Even Tom Tresansky's example above will need it if we move the Surveillance class to somewhere outside MockCalendarTest class.
I'm not as familiar with the when(object.call()).andReturn(response); but I'm assuming it works the same way as expect.(object.call()).andReturn(response);. If that is the case, then it looks like all you are missing a replay of the class PowerMock.replay(Calendar.class) and you are trying to do a full static mock instead of a partial static mock. This should resolve your issue.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
PowerMock.mockStaticPartial(Calendar.class, "getInstance"); //Mock Static Partial
expect(Calendar.getInstance()).andReturn(calendar);
PowerMock.replay(Calendar.class); // note the replay of the Class!
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
//Whatever tests you need to do here
}
}
It seems like you're doing everything right. For instance, this test below passes, proving that the Calendar returned by Calendar#getInstance() is in fact the one you set up with the static mocking.
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class MockCalendarTest {
#Test
public void testFailingDatabase() {
mockStatic(Calendar.class);
final Calendar testCalendar = new GregorianCalendar();
testCalendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(testCalendar);
final Surveillance surveillance = new Surveillance();
final Calendar resultCalendar = surveillance.checkDatabase();
assertTrue(testCalendar == resultCalendar);
}
public static class Surveillance {
public Calendar checkDatabase() {
return Calendar.getInstance();
}
}
}
Perhaps post the relevant parts of the Surveillance class so we can see how it's trying to get a new Calendar and assess why it's failing.

Very basic Spinner issue with Android AIDE

Hi I'm completely new to android programming and use AIDE via tablet.
I'm trying to create a very basic program with a Spinner box that gives output on the selection Ive made via an TextView or System.Out.printIn. (Perhaps the next step up from Hello world - if you will)
For some reason that I cannot fathom,the compiler refuses to recognise the OnClickListener and gives the error message 'Unknown method OnClickListener in Android.Widget.Spinner'
When I have already checked this in the imports.
As a matter of interest I have changed the name of the Spinner and the error seems to dissapear, the problem then is the Spinner name. I have tried several variations on this, and have came to the conclusion that the best option for me is to create a variable just after Main Acivity, and before the layout is declared.
I have also disabled one of the overrides in order to resolve my problem
has anyone got an idea what the problem could be?
package com.BGilbert.AUC;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.View.OnClickListener;
import android.widget.Spinner.*;
import android.view.*;
public class MainActivity extends Activity {;
String Fbstring;
OnClickListener Myonclick;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
final Spinner Fbspinner=(Spinner)findViewById(R.id.Spinner);
// The problem is with this line. OnClickListener just wont be
// recognised
Fbspinner.OnClickListener(Myonclick);
}
// Override previously disabled
#Override
public void Onselect(AdapterView<?> parent,View V, int pos, long id) {
Fbstring = parent.getItemAtPosition(pos).toString();
System.out.println(Fbstring);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
You can't set an onClickListener on a spinner, only on it's views which is too advanced for you at the moment. Instead, use an onItemSelectedListener.
public class MainActivity extends Activity extends Activity implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
...
...
}
You should read the documentation first http://developer.android.com/guide/topics/ui/controls/spinner.html
Also try to use standard naming conventions:
http://www.oracle.com/technetwork/java/codeconv-138413.html
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367
Finally, you have many problems in this code, e.g.
public class MainActivity extends Activity {;
Note the semicolon at the end.
Get your code compiling first, then come back with your next question.
Good luck

How do I get input from a user using j2me canvases? is this even possible?

I am currently trying to learn J2ME and build a connect four game (some of you might know this as 'four in a row'). I've More or less got all of the aspects of my game working, apart from one thing that is driving me mad! This is of course getting the text from the user!
For the two player mode of the game I want to be able to allow each player to enter their name. I am struggling to find a working example of text input that doesn't use the main Midlet.
For example the examples on java2x.com just use a single midlet (no classes or canvases or anything).
As it stands my application's main midlet start method simply opens a main menu class:
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
public void startApp() {
MainMenu mm = new MainMenu();
showScreen(mm);
}
public static void showScreen(Displayable screen) {
Display.getDisplay(instance).setCurrent(screen);
}
public void pauseApp() {
}
public static void quitApp() {
instance.notifyDestroyed();
}
public void destroyApp(boolean unconditional) {
}
}
The main menu class is as follows:
package view;
import javax.microedition.lcdui.*;
import lang.*;
import model.*;
import midlet.Main;
public class MainMenu extends List implements CommandListener {
private Command ok = new Command(StringDefs.currDefs.getString("TEXT_OK"), Command.OK, 1);
public MainMenu() {
super(StringDefs.currDefs.getString("TEXT_TITLE"), List.IMPLICIT);
// we we add in the menu items
append(StringDefs.currDefs.getString("TEXT_PLAY1"), null);
append(StringDefs.currDefs.getString("TEXT_PLAY2"), null);
append(StringDefs.currDefs.getString("TEXT_HIGHSCORETABLE"), null);
append(StringDefs.currDefs.getString("TEXT_HELP"), null);
append(StringDefs.currDefs.getString("TEXT_QUIT"), null);
this.addCommand(ok);
this.setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == ok) {
int selectedItem = this.getSelectedIndex();
if (selectedItem != -1) {
switch (selectedItem) {
case 0:
GameBoard gameBoard = new model.GameBoard();
GameCanvasOnePlayer board = new GameCanvasOnePlayer(gameBoard);
Main.showScreen(board);
break;
case 1:
GameBoard gameBoardTwo = new model.GameBoard();
GameCanvasTwoPlayer GameCanvasTwoPlayer = new GameCanvasTwoPlayer(gameBoardTwo);
Main.showScreen(GameCanvasTwoPlayer);
break;
case 2:
HighScores hc = new HighScores();
midlet.Main.showScreen(hc);
break;
case 3:
Help he = new Help();
midlet.Main.showScreen(he);
break;
case 4:
QuitConfirmation qc = new QuitConfirmation();
midlet.Main.showScreen(qc);
break
}
}
}
}
}
When a two player game is selected (case 1 in the above switch) from this menu I would like two text boxes to appear so that I can get both player names and store them.
What would be the best way of going about this? is this even possible with canvases? And do you know where I can find a relevant example or at least something which may help?
You can either:
1. Make the user enter his input in an ugly Textbox (which takes the whole screen)
2. Use the textbox control I've written from scratch a long time ago which is available here
and looks something like this (3 Textfields shown):
I've got a solution! well sort of.
I can create a form without using the main midlet:
The following main class is part of a source package called midlet (much like in my project):
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
private static UsernameForm unameForm=new UsernameForm();
private static MIDlet instance;
public void startApp() {
instance=this;
showScreen(unameForm); // show user name form
}
public static String getUsername1() {
return(unameForm.getUsername1());
}
public static String getUsername2() {
return(unameForm.getUsername2());
}
public void pauseApp() {
}
public static void showScreen(Displayable d) {
Display.getDisplay(instance).setCurrent(d); // show next screen
}
public void destroyApp(boolean unconditional) {
}
}
The next bit of code is the username form class that is part of a source package called view:
package view;
import javax.microedition.lcdui.*;
public class UsernameForm extends Form implements CommandListener {
private String username1="";
private String username2="";
private TextField tfUsername1=new javax.microedition.lcdui.TextField("User 1","User1",40,TextField.ANY);
private TextField tfUsername2=new javax.microedition.lcdui.TextField("User 2","User2",40,TextField.ANY);
private Command cmdOK=new Command("OK",Command.OK,1);
public UsernameForm() {
super("User details");
append(tfUsername1);
append(tfUsername2);
addCommand(cmdOK);
setCommandListener(this);
}
public void commandAction(Command cmd,Displayable d) {
if (cmd==cmdOK) {
this.setUsername1(tfUsername1.getString());
this.setUsername2(tfUsername2.getString());
// TO DO, GO TO NEXT SCREEN
}
}
/**
* #return the username1
*/
public String getUsername1() {
return username1;
}
/**
* #param username1 the username1 to set
*/
public void setUsername1(String username1) {
this.username1 = username1;
}
/**
* #return the username2
*/
public String getUsername2() {
return username2;
}
/**
* #param username2 the username2 to set
*/
public void setUsername2(String username2) {
this.username2 = username2;
}
}
So it looks like there's no easy way of doing it using canvases, I think I am better of using 'ugly forms' instead as they should work whatever the device.
That's a really sticky situation. Basically you will need to use J2ME's input text widget (which by the way looks horrible). If you don't, you'll end up having to implement all the logic behind the different types of phone keyboards and you won't have access to the dictionary... Your canvas will basically only be capturing keystrokes, not text input...
Sorry.
Here you need to, implement custom Items, all you need to do is to extend the part of the canvas where to want the user/player to enter his/her name to the CustomItems, and implement the customItems predefined abstract methods, and write method for Key Strokes and that's available in the nokia forum. They have explained it pretty good. Check out the Nokia forum.

Resources