How do I 'initialize' my graphics? - graphics

My friend has make me a simple JFrame, and I am meant to work on it and develop it. I have encountered a problem within the first 30 mins of having it: it's not drawing the graphics!!
Here is the code that draws the graphics, and the code from the class that brings up the JFrame.
Thanks in advance.
GameCanvas.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package danielballtest;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.LinkedList;
/**
*
* #author Kris
*/
public class GameCanvas extends Canvas{
Player p;
LinkedList<Stalker> s = new LinkedList<>();
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
p.paintItAll(g2d);
for(int i = 0; i < s.size(); i++) {
s.get(i).paintItAll(g2d);
}
}
public GameCanvas() {
initComponents();
repaint();
}
public void initComponents() {
p = new Player(new Point(50,50));
s.add(new Stalker(new Point(50,100)));
}
public Point getPlayerPos() {
return p.getPos();
}
}
MainWindow.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package danielballtest;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
*
* #author Kris
*/
public class MainWindow extends JFrame{
static Toolkit tk = Toolkit.getDefaultToolkit();
static int xSize = ((int) tk.getScreenSize().getWidth());
static int ySize = ((int) tk.getScreenSize().getHeight());
/**
* #param args the command line arguments
*/
public MainWindow() {
super("STALKER!!!!!!!!!!");
GameCanvas canvas = new GameCanvas();
add(canvas, BorderLayout.CENTER);
setSize(xSize, ySize);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
canvas.createBufferStrategy(2);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainWindow();
}
});
}
}

You are using the old AWT Canvas class as the base component. This class follows the AWT painting mechanism, where there is no paintComponent method and you were supposed to override paint to do custom graphics.
Change the base class to JComponent and you can use the newer painting mechanism:
...
import javax.swing.JComponent;
public class GameCanvas extends JComponent {
This article compares how painting works in AWT and Swing if you want to know more about them.

Related

Can I replace ActionBarActivity with AppCompatActivity in a Tabbed Activity in Android Studio?

The following Tabbed Activity is created by Android Studio 1.2.2 Wizard, it works well in API 9, but someboyd told me that ActionBarActivity is deprecated,
so I hope to replace public class MainActivity extends ActionBarActivity implements ActionBar.TabListener with public class MainActivity extends AppCompatActivity implements ActionBar.TabListener , and stay all other code the same, is it OK?
Thanks!
package com.example.cuiwei.myapplication;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
You can safely replace ActionBarActivity with AppCompatActivity.
As you can see in v7-appcompat source code from version v22.1.0 ActionBarActivity simply extends AppCompatActivity:
/**
* #deprecated Use {#link android.support.v7.app.AppCompatActivity} instead.
*/
#Deprecated
public class ActionBarActivity extends AppCompatActivity {
}

Adding a TilePane instantiated in .java files to FXML

I'm trying to add a TilePane with ImageView children to a scene in JavaFX. Currently, my FXML is loading an empty TilePane.
The current FXML line that i have making the TilePane is
<TilePane id="MapPane" fx:id="mapPane" layoutX="3.0" layoutY="0.0" prefColumns="9" prefHeight="560.0" prefTileHeight="112.0" prefTileWidth="112.0" prefWidth="1277.0" visible="true"\>
where mapPane is the name of the variable in my .java file
controller:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package screens.gameScreen;
import screens.*;
import mule.*;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.*;
import java.awt.MouseInfo;
import java.awt.Point;
import com.sun.glass.ui.Robot;
/**
* FXML Controller class
*
* #author Stephen
*/
public class GameScreenController implements Initializable, ControlledScreen {
Robot robot = com.sun.glass.ui.Application.GetApplication().createRobot();
ScreenManager screenManager;
TileEngine tileEngine = new TileEngine();
#FXML
TilePane mapPane = tileEngine.createRandomMap(true);;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#Override
public void setScreenParent(ScreenManager screen) {
screenManager = screen;
}
#FXML
private void goToMain(ActionEvent event) {
screenManager.setScreen(mule.MULE.mainMenuScreenID);
}
}
you can use SceneBuilder for create FXML. This can easily solve your problem.

How do I implement JavaFX in existing WindowBuilder project ?

I am trying to get my head around the JavaFX stuff...
My program is a WindowBuilder based Gui, and I want a JavaFX graph, and a JavaFX live video-feed displayed in my app.
How do I implement it in my code? I have tried this, but I couldn't get it runnning.
The data feed isnt the problem. I just need to view it inside my JFrame as small squares...
Confused now :(
Here is my code: (I am sorry that it is a tad long, but I blame the examplecode from JavaFX :p
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Canvas;
import java.awt.SystemColor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import javax.swing.UIManager.*;
/**
* #author
*
*/
public class MyClientApp extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
protected static final String BufferedWriter = null;
JFrame frame;
private JTextField textFieldUsername;
/**
* Create the application.
*/
public MyClientApp(BufferedWriter serverDataOut, BufferedReader serverDataIn) {
initialize();
}
/**
* Initialize the contents of the frame.
*
* #param serverDataOut
*
*/
private void initialize() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// Nimbus Theme not avaliable
}
frame = new JFrame();
frame.setResizable(false);
frame.setTitle("*********** My Program ***********");
frame.setBounds(320, 130, 730, 570);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
Canvas canvasTemp = new Canvas();
canvasTemp.setBackground(SystemColor.window);
canvasTemp.setBounds(6, 277, 380, 255);
frame.getContentPane().add(canvasTemp);
Canvas canvasLevel = new Canvas();
canvasLevel.setBackground(SystemColor.window);
canvasLevel.setBounds(6, 10, 380, 255);
frame.getContentPane().add(canvasLevel);
}
public JFrame frame() {
return frame;
}
}
And here is the main file to get it running for you guys... :
Client.java
import java.io.IOException;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
MyClientApp window = new MyClientApp(null, null);
window.frame.setVisible(true);
}
}
The code I want to implement is:
AdvancedLineChartSample.java (from JavaFX)
/**
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*/
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.util.Duration;
/**
* An advanced line chart with a variety of actions and settable properties.
*
* #see javafx.scene.chart.LineChart
* #see javafx.scene.chart.Chart
* #see javafx.scene.chart.NumberAxis
* #see javafx.scene.chart.XYChart
*/
public class AdvancedLineChartSample extends Application {
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
root.getChildren().add(createChart());
}
protected LineChart<Number, Number> createChart() {
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
final LineChart<Number,Number> lc = new LineChart<Number,Number>(xAxis,yAxis);
// setup chart
lc.setTitle("Temp Chart");
xAxis.setLabel("tid");
yAxis.setLabel("temp");
// add starting data
XYChart.Series<Number,Number> series = new XYChart.Series<Number,Number>();
series.setName("Dataset 1");
series.getData().add(new XYChart.Data<Number,Number>(20d, 50d));
series.getData().add(new XYChart.Data<Number,Number>(40d, 80d));
series.getData().add(new XYChart.Data<Number,Number>(50d, 90d));
series.getData().add(new XYChart.Data<Number,Number>(70d, 30d));
series.getData().add(new XYChart.Data<Number,Number>(170d, 122d));
lc.getData().add(series);
return lc;
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
public static void main(String[] args) { launch(args);
}
}
and the StreamingMediaPlayer.java (from JavaFX):
/**
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*/
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.util.Duration;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.animation.ParallelTransition;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
/**
* A media player with controls for play, pause, stop, seek, and volume. This media player is playing media via HTTP Live Streaming, also known as HLS.
*
* #see javafx.scene.media.MediaPlayer
* #see javafx.scene.media.Media
*/
public class StreamingMediaPlayer extends Application {
private static final String MEDIA_URL = "http://download.oracle.com/otndocs/products/javafx/JavaRap/prog_index.m3u8";
private MediaPlayer mediaPlayer;
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
mediaPlayer = new MediaPlayer(new Media(MEDIA_URL));
mediaPlayer.setAutoPlay(true);
PlayerPane playerPane = new PlayerPane(mediaPlayer);
playerPane.setMinSize(480, 360);
playerPane.setPrefSize(480, 360);
playerPane.setMaxSize(480, 360);
// getStylesheets().add("ensemble/samples/media/OverlayMediaPlayer.css");
root.getChildren().add(playerPane);
}
public void play() {
Status status = mediaPlayer.getStatus();
if (status == Status.UNKNOWN || status == Status.HALTED) {
return;
}
if (status == Status.PAUSED || status == Status.STOPPED || status == Status.READY) {
mediaPlayer.play();
}
}
#Override public void stop() {
mediaPlayer.stop();
}
static class PlayerPane extends BorderPane {
private MediaPlayer mp;
private MediaView mediaView;
private final boolean repeat = false;
private boolean stopRequested = false;
private boolean atEndOfMedia = false;
private Duration duration;
private Slider timeSlider;
private Label playTime;
private Slider volumeSlider;
private HBox mediaTopBar;
private HBox mediaBottomBar;
private ParallelTransition transition = null;
#Override protected void layoutChildren() {
if (mediaView != null && getBottom() != null) {
mediaView.setFitWidth(getWidth());
mediaView.setFitHeight(getHeight() - getBottom().prefHeight(-1));
}
super.layoutChildren();
if (mediaView != null) {
mediaView.setTranslateX((((Pane)getCenter()).getWidth() - mediaView.prefWidth(-1)) / 2);
mediaView.setTranslateY((((Pane)getCenter()).getHeight() - mediaView.prefHeight(-1)) / 2);
}
}
#Override protected double computeMinWidth(double height) {
return mediaBottomBar.prefWidth(-1);
}
#Override protected double computeMinHeight(double width) {
return 200;
}
#Override protected double computePrefWidth(double height) {
return Math.max(mp.getMedia().getWidth(), mediaBottomBar.prefWidth(height));
}
#Override protected double computePrefHeight(double width) {
return mp.getMedia().getHeight() + mediaBottomBar.prefHeight(width);
}
#Override protected double computeMaxWidth(double height) { return Double.MAX_VALUE; }
#Override protected double computeMaxHeight(double width) { return Double.MAX_VALUE; }
public PlayerPane(final MediaPlayer mp) {
this.mp = mp;
setId("player-pane");
mediaView = new MediaView(mp);
Pane mvPane = new Pane() { };
mvPane.setId("media-pane");
mvPane.getChildren().add(mediaView);
setCenter(mvPane);
mediaTopBar = HBoxBuilder.create()
.padding(new Insets(5, 10, 5, 10))
.alignment(Pos.CENTER)
.opacity(1)
.build();
BorderPane.setAlignment(mediaTopBar, Pos.CENTER);
mediaBottomBar = HBoxBuilder.create()
.padding(new Insets(5, 10, 5, 10))
.alignment(Pos.CENTER)
.opacity(1)
.build();
BorderPane.setAlignment(mediaBottomBar, Pos.CENTER);
mp.currentTimeProperty().addListener(new ChangeListener<Duration>() {
#Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
updateValues();
}
});
mp.setOnPlaying(new Runnable() {
public void run() {
if (stopRequested) {
mp.pause();
stopRequested = false;
}
}
});
mp.setOnReady(new Runnable() {
public void run() {
duration = mp.getMedia().getDuration();
updateValues();
}
});
mp.setOnEndOfMedia(new Runnable() {
public void run() {
if (!repeat) {
stopRequested = true;
atEndOfMedia = true;
}
}
});
mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
// Time label
Label timeLabel = LabelBuilder.create()
.text("Time")
.minWidth(Control.USE_PREF_SIZE)
.textFill(Color.WHITE)
.build();
mediaTopBar.getChildren().add(timeLabel);
// Time slider
timeSlider = SliderBuilder.create()
.id("media-slider")
.minWidth(240)
.maxWidth(Double.MAX_VALUE)
.build();
timeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (timeSlider.isValueChanging()) {
// multiply duration by percentage calculated by slider position
if (duration != null) {
mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
}
updateValues();
}
}
});
HBox.setHgrow(timeSlider, Priority.ALWAYS);
mediaTopBar.getChildren().add(timeSlider);
// Play label
playTime = LabelBuilder.create()
.prefWidth(130)
.minWidth(50)
.textFill(Color.WHITE)
.build();
mediaTopBar.getChildren().add(playTime);
// Volume label
Label volumeLabel = LabelBuilder.create()
.text("Vol")
.textFill(Color.WHITE)
.minWidth(Control.USE_PREF_SIZE)
.build();
mediaTopBar.getChildren().add(volumeLabel);
// Volume slider
volumeSlider = SliderBuilder.create()
.id("media-slider")
.prefWidth(120)
.maxWidth(Region.USE_PREF_SIZE)
.minWidth(30)
.build();
volumeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
}
});
volumeSlider.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
if (volumeSlider.isValueChanging()) {
mp.setVolume(volumeSlider.getValue() / 100.0);
}
}
});
mediaTopBar.getChildren().add(volumeSlider);
setTop(mediaTopBar);
final EventHandler<ActionEvent> backAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.seek(Duration.ZERO);
}
};
final EventHandler<ActionEvent> stopAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.stop();
}
};
final EventHandler<ActionEvent> playAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.play();
}
};
final EventHandler<ActionEvent> pauseAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.pause();
}
};
final EventHandler<ActionEvent> forwardAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
Duration currentTime = mp.getCurrentTime();
mp.seek(Duration.seconds(currentTime.toSeconds() + 5.0));
}
};
mediaBottomBar = HBoxBuilder.create()
.id("bottom")
.spacing(0)
.alignment(Pos.CENTER)
.children(
ButtonBuilder.create()
.id("back-button")
.text("Back")
.onAction(backAction)
.build(),
ButtonBuilder.create()
.id("stop-button")
.text("Stop")
.onAction(stopAction)
.build(),
ButtonBuilder.create()
.id("play-button")
.text("Play")
.onAction(playAction)
.build(),
ButtonBuilder.create()
.id("pause-button")
.text("Pause")
.onAction(pauseAction)
.build(),
ButtonBuilder.create()
.id("forward-button")
.text("Forward")
.onAction(forwardAction)
.build()
)
.build();
setBottom(mediaBottomBar);
}
protected void updateValues() {
if (playTime != null && timeSlider != null && volumeSlider != null && duration != null) {
Platform.runLater(new Runnable() {
public void run() {
Duration currentTime = mp.getCurrentTime();
playTime.setText(formatTime(currentTime, duration));
timeSlider.setDisable(duration.isUnknown());
if (!timeSlider.isDisabled() && duration. greaterThan(Duration.ZERO) && !timeSlider.isValueChanging()) {
timeSlider.setValue(currentTime.divide(duration).toMillis() * 100.0);
}
if (!volumeSlider.isValueChanging()) {
volumeSlider.setValue((int) Math.round(mp.getVolume() * 100));
}
}
});
}
}
private static String formatTime(Duration elapsed, Duration duration) {
int intElapsed = (int)Math.floor(elapsed.toSeconds());
int elapsedHours = intElapsed / (60 * 60);
if (elapsedHours > 0) {
intElapsed -= elapsedHours * 60 * 60;
}
int elapsedMinutes = intElapsed / 60;
int elapsedSeconds = intElapsed - elapsedHours * 60 * 60 - elapsedMinutes * 60;
if (duration.greaterThan(Duration.ZERO)) {
int intDuration = (int)Math.floor(duration.toSeconds());
int durationHours = intDuration / (60 * 60);
if (durationHours > 0) {
intDuration -= durationHours * 60 * 60;
}
int durationMinutes = intDuration / 60;
int durationSeconds = intDuration - durationHours * 60 * 60 - durationMinutes * 60;
if (durationHours > 0) {
return String.format("%d:%02d:%02d",
elapsedHours, elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",
elapsedMinutes, elapsedSeconds);
}
} else {
if (elapsedHours > 0) {
return String.format("%d:%02d:%02d",
elapsedHours, elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",
elapsedMinutes, elapsedSeconds);
}
}
}
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
play();
}
public static void main(String[] args) { launch(args);
}
}
I'm sorry about the long code. Its just the samplecode from JavaFX. You find it here, and here.
That should be quite easy to solve. Let me explain it with the chart example that you've shown.
Add an instance of JFXPanel to your JFrame. In your examples, all components are added to a Stage, which is the JavaFX class to represent a window. So you don't need it here. Instead, you add the components that you want to use to the JFXPanel. See also here (function initAndShowGUI) how to do it.
In the init function of the example, a Scene is created as well as the chart itself. What you have to do to let the chart be shown is not much more than that - create a Scene, fill it with content and pass it to the JFXPanel that you already created.
With a minimum effort you can make your chart example run: Make sure that AdvancedLineChartSample.java is in your build path and that the function createChart is somehow accessible from your JFrame. Then add the chart to your code with something similar to the following snippet.
Group root=new Group();
Scene scene=new Scene(root);
myJFXPanel.setScene(scene);
root.getChildren().add(createChart());
This is just a very quick and dirty solution to run your example without any beautiful code and also I didn't test it. But hopefully it gives you a basic understanding of what's going on to encourage further experiments. By my own experience I can tell you that from this step on, there's a lot of fun to come with JavaFX 2.

javafx html editor

actually i'm looking for something very similar to this thread:
How to hide the controls of HTMLEditor?
so basically i try to add a custom button to the javafx html editor but with the difference that it's implemented through FXML.
So my question is:
Is there a "work-around" to add custom buttons to the html-editor when it's implemented through FXML?
Sample solution is :
htmlEditor.setVisible(false);
Platform.runLater(new Runnable() {
#Override
public void run() {
Node[] nodes = htmlEditor.lookupAll(".tool-bar").toArray(new Node[0]);
for (Node node : nodes) {
node.setVisible(false);
node.setManaged(false);
}
htmlEditor.setVisible(true);
}
});
I have modified the #jewelsea answer for javaFX9.
I have also added some customization to move toolbars. The main idea is to get all the components by css selector, then modify or hide them. Read the class HTMLEditorSkin to get the CSS classes names, like ".html-editor-align-center" for the align button.
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.ToolBar;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
public class HTMLEditorCustomizationSample2 extends Application {
// limits the fonts a user can select from in the html editor.
private static final ObservableList<String> limitedFonts = FXCollections.observableArrayList("Arial",
"Times New Roman", "Courier New", "Comic Sans MS");
private HTMLEditor htmlEditor;
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("unchecked")
#Override
public void start(Stage stage) {
htmlEditor = new HTMLEditor();
stage.setScene(new Scene(htmlEditor));
stage.show();
customizeEditor(htmlEditor);
}
private void customizeEditor(HTMLEditor htmlEditor) {
// hide controls we don't need.
Node seperator = htmlEditor.lookup(".separator");
seperator.setVisible(false);
seperator.setManaged(false);
hideByClass(htmlEditor, ".separator");
hideByClass(htmlEditor, ".html-editor-cut", ".html-editor-copy", ".html-editor-paste", ".html-editor-strike",
".html-editor-hr");
hideByClass(htmlEditor, ".html-editor-align-left"
, ".html-editor-align-center"
, ".html-editor-align-right"
, ".html-editor-align-justify", ".html-editor-outdent"
, ".html-editor-indent", ".html-editor-bullets"
, ".html-editor-numbers");
// Move the toolbars
Node top= htmlEditor.lookup(".top-toolbar");
GridPane.setConstraints(top,1,0,1,1);
Node bottom= htmlEditor.lookup(".bottom-toolbar");
GridPane.setConstraints(bottom,0,0,1,1);
Node web= htmlEditor.lookup("WebView");
GridPane.setConstraints(web,0,1,2,1);
// modify font selections.
int i = 0;
Set<Node> fonts = htmlEditor.lookupAll(".font-menu-button");
Iterator<Node> fontsIterator = fonts.iterator();
fontsIterator.next();
ComboBox<String> formatComboBox = (ComboBox<String>) fontsIterator.next();
formatComboBox.itemsProperty().addListener((obs, old, value) -> {
if (value.size() != limitedFonts.size()) {// should loop on array for equality
Platform.runLater(() -> {
value.clear();
// stop.set(true);
value.addAll(limitedFonts);
formatComboBox.setValue(limitedFonts.get(0));
});
}
});
// add a custom button to the top toolbar.
Node node = htmlEditor.lookup(".top-toolbar");
if (node instanceof ToolBar) {
ToolBar bar = (ToolBar) node;
ImageView graphic = new ImageView(
new Image("http://bluebuddies.com/gallery/title/jpg/Smurf_Fun_100x100.jpg", 16 , 16, true, true));
graphic.setEffect(new DropShadow());
Button smurfButton = new Button("", graphic);
bar.getItems().add(smurfButton);
smurfButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
htmlEditor.setHtmlText("<font face='Comic Sans MS' color='blue'>Smurfs are having fun :-)</font>");
}
});
}
}
private void hideByClass(HTMLEditor htmlEditor, String... selectors) {
for (String selector : selectors) {
Set<Node> nodes = htmlEditor.lookupAll(selector);
for (Node node : nodes) {
node.setVisible(false);
node.setManaged(false);
}
}
}
#Override
public void stop() throws Exception {
super.stop();
System.out.println(htmlEditor.getHtmlText());
}
}
Here is some sample code which customizes the HTMLEditor and adds a custom button to it. The sample code does not use fxml but really it's very similar if fxml is used. You could define the HTMLEditor in fxml and inject it into your Controller using the standard #FXML annotation. Once you have a reference to the editor, customize it in Java code using an appropriate variation of the sample code. For the added button, just create it in Java rather than fxml and it will be simpler.

Dialling a phone number by platformrequest

I have tried for two days to write a code that dial a phone number , but I failed
I have written a midlet and a form called main as a Displayable the form contains a textfield and
command .
When the application starts up the form should appears and calls the dialed number written in
textField when the command pressed.
the dialing process didn't work with me .
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Displayable.*;
import javax.microedition.lcdui.Form.*;
import javax.microedition.midlet.MIDlet;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class DiallNumber extends MIDlet implements CommandListener
{
String num;
private Form main;
private Command call,dial;
private TextField phoneField;
Display display;
public DiallNumber()
{
main = new Form("main");
phoneField = new TextField("label","",10,phoneField.PHONENUMBER);
call = new Command("call",call.OK,0);
main.append(phoneField);
main.addCommand(call);
num=this.phoneField.getString().trim();
main.setCommandListener(this);
}
/**}
* From MIDlet. Called when the MIDlet is started.
*/
public void startApp()
{
// The initial display is the first form
display = Display.getDisplay(this);
display.setCurrent(main);
}
public void call( String number) {
try {
platformRequest("tel:"+number);
} catch (ConnectionNotFoundException ex) {
// TODO: Exception handling
}
}
public void commandAction(Command c, Displayable d){
if(d==main)
{
if(c==call)
call(""+num);
}
}
public void pauseApp()
{
// No implementation required
}
/*
* /
*/
/**
* From MIDlet. Called to signal the MIDlet to terminate.
*
* #param unconditional
* whether the MIDlet has to be unconditionally terminated
*/
public void destroyApp(boolean unconditional)
{
// No implementation required
}
/**
* From CommandListener. Called by the system to indicate that a command has
* been invoked on a particular displayable.
*
* #param command
* the command that was invoked
* #param displayable
* the displayable where the command was invoked
*/
}
My log trace
Copying 1 file to C:\Users\ELHADI\Documents\NetBeansProjects\DiallNumber2\dist\nbrun5217990045006831680
Copying 1 file to C:\Users\ELHADI\Documents\NetBeansProjects\DiallNumber2\dist\nbrun5217990045006831680
Jad URL for OTA execution: http://localhost:8082/servlet/org.netbeans.modules.mobility.project.jam.JAMServlet/C%3A/Users/ELHADI/Documents/NetBeansProjects/DiallNumber2/dist//DiallNumber2.jad
Starting emulator in execution mode
Installing suite from: http://127.0.0.1:49320/DiallNumber2.jad
[WARN] [rms ] javacall_file_open: _wopen failed for: C:\Users\ELHADI\javame-sdk\3.0\work\0\appdb\_delete_notify.dat
I have solved the problem
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Displayable.*;
import javax.microedition.lcdui.Form.*;
import javax.microedition.midlet.MIDlet;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class DiallNumber extends MIDlet
{
private Display display;
private MIDlet midlet;
Form f = new form("f");
/**}
* From MIDlet. Called when the MIDlet is started.
*/
public void startApp()
{
display = Display.getDisplay(this);
display.setCurrent(f);
}
public void pauseApp()
{
// No implementation required
}
/*
* /
*/
/**
* From MIDlet. Called to signal the MIDlet to terminate.
*
* #param unconditional
* whether the MIDlet has to be unconditionally terminated
*/
public void destroyApp(boolean unconditional)
{
// No implementation required
}
class form extends Form implements CommandListener
{
private Command call;
private TextField phoneField;
private String n;
public form(String title )
{
super(title);
call =new Command("call",call.OK,0);
this.phoneField =new TextField("number","",20,phoneField.PHONENUMBER);
addCommand(call);
append(this.phoneField);
this.setCommandListener(this);
}
public void commandAction(Command c,Displayable d)
{
if(c==call)
{
try
{
n=phoneField.getString().trim();
platformRequest("tel:"+n);
}
catch(javax.microedition.io.ConnectionNotFoundException e)
{e.printStackTrace();}
}
}
}
}

Resources