I am following a series of tutorials on game development in Java by thenewboston on Youtube. I am at the point where I can make a fullscreen window, but the resolution refuses to resize to 800x600. I have tested vc, a GraphicsEnvironment.getDefaultScreenDevice object, and dm, a DisplayMode, and they don't seem to be the problem. I am running Snow Leopard. Any ideas?
if(dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
System.out.println("Display mode set");
}catch(Exception ex){System.out.println("Despite the vc saying it is display change supported and the DM is not null, something went wrong");}
}
}
Add this code to your Core.java (or GameClient.java) class. The issue may be that you are not passing the required DM[] args to your ScreenManager.java class.
private static final DisplayMode modes[] = { //common monitor DMs
new DisplayMode(1366,768,32, DisplayMode.REFRESH_RATE_UNKNOWN), //1366x768px w/32-bit depth
new DisplayMode(1366,768,24, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/24-bit depth
new DisplayMode(1366,768,16, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/16-bit depth
new DisplayMode(800,600,32, DisplayMode.REFRESH_RATE_UNKNOWN), //800x600px w/32-bit depth
new DisplayMode(800,600,24, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/24-bit depth
new DisplayMode(800,600,16, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/16-bit depth
new DisplayMode(640,480,32, DisplayMode.REFRESH_RATE_UNKNOWN), //640x480px w/32-bit depth
new DisplayMode(640,480,24, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/24-bit depth
new DisplayMode(640,480,16, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/16-bit depth
};
I'm assuming that the error is with your public void setFullScreen(DisplayMode dm) method. In that case, the full syntax for this method is:
/*****************************************************************************
* #description: Creates window for program to run in, using appropriate DM
* #param DisplayMode dm
*/
public void setFullScreen(DisplayMode dm){
JFrame f = new JFrame();
f.setUndecorated(true); //no titlebars/scroll bars etc.
f.setIgnoreRepaint(true);
f.setResizable(false); //user cannot resize window
vc.setFullScreenWindow(f);
if(dm!=null && vc.isDisplayChangeSupported()){ //if DM is changeable
try {
vc.setDisplayMode(dm);
} catch (Exception e){/*Catch 'em all*/}
}
f.createBufferStrategy(2); //set # of screen buffers to 2
}//setFullScreen()
Noticed this was a mild necro-post after posting. Aaahh...
Related
I'm a CodeNameOne beginner. I'm trying to make a local notification, it doesn't seem to work,I don't get anything displayed. here's the start function.
Is there anything missing? Should I add variables in the build settings?
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
hi.show();
LocalNotification n = new LocalNotification();
n.setId("demo-notification");
n.setAlertBody("It's time to take a break and look at me");
n.setAlertTitle("Break Time!");
//n.setAlertSound("/notification_sound_beep-01a.mp3");
// alert sound file name must begin with notification_sound
Display.getInstance().scheduleLocalNotification(
n,
System.currentTimeMillis() + 10 * 1000, // fire date/time
LocalNotification.REPEAT_MINUTE // Whether to repeat and what frequency
);
}
I am trying to show an object without tapping on the screen using ARCore. In the basic sample of ARCore Sceneform provided by Google, you need to tap on the screen after it detects the surface.
I want to implement that, AR shows the object without tapping on the screen.
Anchor newAnchor;
for (Plane plane : mSession.getAllTrackables(Plane.class)) {
if (plane.getType() == Plane.Type.HORIZONTAL_UPWARD_FACING
&& plane.getTrackingState() == TrackingState.TRACKING)
{
newAnchor = plane.createAnchor(plane.getCenterPose());
break;
}
}
I tried this for displaying without tapping on the screen.
if Anyone know how to do this please help me. Thanks in Advance
Although I suggest you place the object when a user taps & where s/he taps on the screen, what you're asking can be achieved like so. (this example is in Kotlin)
Before you begin placing an object, you need to create a ModelRenderable. Declare one #Nullable globally.
private var modelRenderable: ModelRenderable? = null
//Create the football renderable
ModelRenderable.builder()
//get the context of the ARFragment and pass the name of your .sfb file
.setSource(fragment.context, Uri.parse("FootBall.sfb"))
.build()
//I accepted the CompletableFuture using Async since I created my model on creation of the activity. You could simply use .thenAccept too.
//Use the returned modelRenderable and save it to a global variable of the same name
.thenAcceptAsync { modelRenderable -> this#MainActivity.modelRenderable = modelRenderable }
The major chunk of the programming has to be done on the frame's onUpdate method. So you attach a listener for frame updates like so
fragment.arSceneView.scene.addOnUpdateListener(this#MainActivity) //You can do this anywhere. I do it on activity creation post inflating the fragment
now you handle adding an object on the listener.
override fun onUpdate(frameTime: FrameTime?) {
//get the frame from the scene for shorthand
val frame = fragment.arSceneView.arFrame
if (frame != null) {
//get the trackables to ensure planes are detected
val var3 = frame.getUpdatedTrackables(Plane::class.java).iterator()
while(var3.hasNext()) {
val plane = var3.next() as Plane
//If a plane has been detected & is being tracked by ARCore
if (plane.trackingState == TrackingState.TRACKING) {
//Hide the plane discovery helper animation
fragment.planeDiscoveryController.hide()
//Get all added anchors to the frame
val iterableAnchor = frame.updatedAnchors.iterator()
//place the first object only if no previous anchors were added
if(!iterableAnchor.hasNext()) {
//Perform a hit test at the center of the screen to place an object without tapping
val hitTest = frame.hitTest(frame.screenCenter().x, frame.screenCenter().y)
//iterate through all hits
val hitTestIterator = hitTest.iterator()
while(hitTestIterator.hasNext()) {
val hitResult = hitTestIterator.next()
//Create an anchor at the plane hit
val modelAnchor = plane.createAnchor(hitResult.hitPose)
//Attach a node to this anchor with the scene as the parent
val anchorNode = AnchorNode(modelAnchor)
anchorNode.setParent(fragment.arSceneView.scene)
//create a new TranformableNode that will carry our object
val transformableNode = TransformableNode(fragment.transformationSystem)
transformableNode.setParent(anchorNode)
transformableNode.renderable = this#MainActivity.modelRenderable
//Alter the real world position to ensure object renders on the table top. Not somewhere inside.
transformableNode.worldPosition = Vector3(modelAnchor.pose.tx(),
modelAnchor.pose.compose(Pose.makeTranslation(0f, 0.05f, 0f)).ty(),
modelAnchor.pose.tz())
}
}
}
}
}
}
I used one extension method
//A method to find the screen center. This is used while placing objects in the scene
private fun Frame.screenCenter(): Vector3 {
val vw = findViewById<View>(android.R.id.content)
return Vector3(vw.width / 2f, vw.height / 2f, 0f)
}
This is the end result
If you don't want to use hit-testing or button's action methods for placing an object in a real environment, you can use, for instance, a camera's Pose for auto-placement (remember, you have to add an ARAnchor, its corresponding Node and a Renderable in front of the ARCamera i.e. along -Z direction):
if (this.anchorNode == null) {
Session session = arFragment.getArSceneView().getSession();
float[] position = { 0, 0, -0.75 }; // 75 cm away from camera
float[] rotation = { 0, 0, 0, 1 };
Anchor anchor = session.createAnchor(new Pose(position, rotation));
anchorNode = new AnchorNode(anchor);
anchorNode.setRenderable(yourModelRenderable);
anchorNode.setParent(arFragment.getArSceneView().getScene());
}
Hope this helps.
Here is the code snippet if you want to place only one object.. Thanks #clinkz
override fun onUpdate(frameTime: FrameTime?) {
arFragment?.let { fragment ->
fragment.arSceneView?.let { sceneView ->
sceneView.arFrame?.let { frame ->
if (!placed) {
val trackable = frame.getUpdatedTrackables(Plane::class.java).iterator()
if (trackable.hasNext()) {
val plane = trackable.next() as Plane
if (plane.trackingState == TrackingState.TRACKING) {
fragment.planeDiscoveryController?.hide()
val hitTest =
frame.hitTest(frame.screenCenter().x, frame.screenCenter().y)
val hitTestIterator = hitTest.iterator()
if (hitTestIterator.hasNext()) {
val hitResult = hitTestIterator.next()
val modelAnchor = plane.createAnchor(hitResult.hitPose)
val anchorNode = AnchorNode(modelAnchor)
anchorNode.setParent(sceneView.scene)
val transformableNode =
TransformableNode(fragment.transformationSystem)
transformableNode.setParent(anchorNode)
transformableNode.renderable = this#ARActivity.modelRenderable
transformableNode.worldPosition = Vector3(
modelAnchor.pose.tx(),
modelAnchor.pose.compose(
Pose.makeTranslation(
0f,
0.05f,
0f
)
).ty(),
modelAnchor.pose.tz()
)
placed = true
}
}
}
}
}
}
}
}
private fun Frame.screenCenter(): Vector3 {
val vw = findViewById<View>(android.R.id.content)
return Vector3(vw.width / 2f, vw.height / 2f, 0f)
}
I am creating a GUI that will allow the user to input Lake information for the state of Florida and then has the ability to display that lake information. I want the display information to be in a JOptionPane.showMessageDialog that has the ability to scroll through the ArrayList of all the lake names. I am able to add the lakes into the ArrayList but they will not display in my JOptionPane and it is blank. I know it is reading something in the ArrayList since it is opening that window. Here is the code below in snippets as the whole thing would be cra.
public static ArrayList<Lakes> lake = new ArrayList<Lakes>();
private JTextArea textAreaDisplay;
private JScrollPane spDisplay;
// this is called in my initComponent method to create both
textAreaDisplay = new JTextArea();
for (Object obj : lake)
{
textAreaDisplay.append(obj.toString() + " ");
}
spDisplay = new JScrollPane(textAreaDisplay);
textAreaDisplay.setLineWrap(true);
textAreaDisplay.setWrapStyleWord(true);
spDisplay.setPreferredSize(new Dimension(500, 500));
// this is called in my createEvents method. After creating lakes in the database
// it will display the else statement but it is empty
btnDisplayLake.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
if (lake.size() == 0)
{
JOptionPane.showMessageDialog(null, "No Lakes in database!");
}
else
JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
}
catch (Exception e1)
{
}
}
});
Thank you for any help you can provide. I have been racking my brain for a few days on this. Been able to get other stuff accomplished but coming back to this issue.
Some obvious issues:
textAreaDisplay = new JTextArea();
A JTextArea should be created with code like:
textAreaDisplay = new JTextArea(5, 20);
By specifying the row/column the text area will be able to calculate its own preferred size. Scrollbars should appear when the preferred size of the text area is greater than the size of the scroll pane.
spDisplay.setPreferredSize(new Dimension(500, 500));
Don't use setPreferredSize(). The scroll area will calculate its preferred size based on the preferred size of the text area.
textAreaDisplay.append(obj.toString() + " ");
I would think you want each Lake to show on a different line, so I would append "\n" instead of the space.
I was setting textAreaDisplay before anything was entered into the ArrayList and it would not run again after anything was entered. I moved the for loop down and into the actionPerformed event and works well now.
btnDisplayLake.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
for (Object obj : lake)
{
textAreaDisplay.append(obj.toString() + "\n");
}
if (lake.size() == 0)
{
JOptionPane.showMessageDialog(null, "No Lakes in database!");
}
else
JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
}
catch (Exception e1)
{
I am having an issue with using a scrollpane in libgdx. It is going to be used for a chatwindow class. When you press enter the message will be added to the window and you will scroll to the latest posted message..However it doesn't. It misses one message and scrolls to the one before the latest message. Below I've posted the chatwindow class and the method that adds input to it. The textAreaholder is a table that holds everything. The chatField is where you input what you want to post to the chat. The chatarea is the textfield that then becomes added to the table. But as stated..it doesn't scroll properly, the error properly lies somewhere in the keyTyped method.
public ChatWindow(final Pipe<String> chatPipe) {
this.chatPipe = chatPipe;
messageFieldCounter = 0;
white = new BitmapFont(Gdx.files.internal("fonts/ChatWindowText.fnt"), false);
fontSize = white.getLineHeight();
white.scale(TEXT_SCALE);
final TextFilter filter = new TextFilter();
/* Making a textfield style */
textFieldStyle = new TextFieldStyle();
textFieldStyle.fontColor = Color.WHITE;
textFieldStyle.font = white;
textFieldStyle.focusedFontColor = Color.CYAN;
/*Area where all chat appears*/
textAreaHolder = new Table();
textAreaHolder.debug();
/*Applies the scrollpane to the chat area*/
scrollPane = new ScrollPane(textAreaHolder);
scrollPane.setForceScroll(false, true);
scrollPane.setFlickScroll(true);
scrollPane.setOverscroll(false, false);
/*Input chat*/
chatField = new TextField("", textFieldStyle);
chatField.setTextFieldFilter(filter);
/*Tries to make the textField react on enter?*/
chatField.setTextFieldListener(new TextFieldListener() {
#Override
public void keyTyped(final TextField textField, final char key) {
if (key == '\n' || key == '\r') {
if (messageFieldCounter <= 50) {
textAreaHolder.row();
StringBuilder message = new StringBuilder(); //Creates the message
message.append(chatField.getText()); //Appends the chatfield entry
TextArea chatArea = new TextArea(message.toString(), textFieldStyle); //Creates a chatArea with the message
chatArea.setHeight(fontSize + 1);
chatArea.setDisabled(true);
chatArea.setTextFieldFilter(filter);
textAreaHolder.add(chatArea).height(CHAT_INPUT_HEIGHT).width(CHAT_WIDTH);
scrollPane.scrollToCenter(0, 0, 0, 0);
//Scrolls to latest input
chatField.setText("");
//InputDecider.inputDecision(message.toString(), chatPipe); //TODO: Change the filter
//chatPipe.put(message.toString()); //TODO: testing
}
}
}
});
Problems could occur, because you're using scrollPane.scrollToCenter(float x, float y, float width, float height) with zero parameters:
scrollPane.scrollToCenter(0, 0, 0, 0);
scrollToCenter method requires that parameters to be correctly supplied. So, try to supply message bounds.
The second reason could be because you call scrollToCenter before table do layout itself. So, try overwrite table's layout method and call scrollToCenter after:
#Override
public void layout()
{
super.layout();
if (new_messages_added)
{
scrollPane.scrollToCenter(...)
}
}
My program will alert users when data (stock name & price) in the database matches with the data (stock name and price) from Yahoo Finance. With the help of HarryJoy i'm able to implement a pop up notification.
Problem is the pop up location on the screen is based on the database loop (int db). The frame will pop even if data doesn't match.
How can I set a counter or some method to pop up the frame only when database data = Yahoo Finance data? Also, my notification panels appears to be behind the main frame. How can make the panels appear on top of my main frame?
I hope I've given enough information, please ask if still unclear. Any guidance will be appreciated! Thanks!
In the database (using code sample only to display my explanation in order, source code below).
Object 1 = match
Object 2 = doesn't match (hence there's a gap)
Object 3 = match
Object 4 = match
Screenshot:
Code:
for (int db=0; db<= rowCount; db++)
{
Object popSymbol = table.getModel().getValueAt(db, 0);
String popupSymbol = popSymbol.toString();
Object popValue = table.getModel().getValueAt(db, 1);
String str = popValue.toString();
double popStockValue = Double.valueOf(str).doubleValue();
String stockNameDB = popupSymbol;
StockPara stock = YahooStock.getInstance().getStockPrice(stockNameDB);
double stockPriceDB = Math.round(stock.getPrice());
final JFrame popUpFrame;
final JPanel popupPanel;
if (stockPriceDB == popStockValue)
{
String header = "Stock: " + stock.getTicker() + " is now # " + stock.getPrice();
String message = "";
popUpFrame = new JFrame();
popUpFrame.setSize(320,90);
popUpFrame.setUndecorated(true);
popUpFrame.getContentPane().setLayout(null);
popupPanel = new JPanel();
popupPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
popupPanel.setBounds(0, 0, 320, 90);
getContentPane().add(popupPanel);
popupPanel.setBackground(new Color(255, 255, 224));
popupPanel.setLayout(null);
popUpFrame.add(popupPanel);
// Other labels, images, etc.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Insets toolHeight = Toolkit.getDefaultToolkit().getScreenInsets(popUpFrame.getGraphicsConfiguration());
popUpFrame.setLocation(screenSize.width - popUpFrame.getWidth(), screenSize.height - toolHeight.bottom - (popUpFrame.getHeight() * (db+1)));
}
}
To solve your issue quickly, simply create an additional counter (int counter = 0;). Then use that counter instead of db to position your popUpFrame and right after that increment counter.
int counter = 0; // Initiate outside de loop
...
for(int db=0; db<= rowCount; db++) {
...
if (stockPriceDB == popStockValue) {
...
popUpFrame.setLocation(screenSize.width - popUpFrame.getWidth(),
screenSize.height - toolHeight.bottom - (popUpFrame.getHeight() * (counter+1)));
counter++;
}
}
To bring your frame to the front use:
popUpFrame.toFront()
and to force it to be always on top (although I would really not recommend that because it is more annoying for the user than anything else):
popUpFrame.setAlwaysOnTop(true);
This is not necessarily supported by all platforms.
for on top issue, use
notificationPanel.requestFocus();