How to refresh XML in Jtree - java

I read here , but if the xml file changes the jtree does not reload /refreshes
how to create a function for refresh / reload Jtree
I try to write code :
refreshAction = new AbstractAction("Refresh", IconFactory.getIcon("delete", IconFactory.IconSize.SIZE_16X16)) {
public void actionPerformed(ActionEvent e) {
XMLTree xmlClass = null;
((DefaultTreeModel) xmlClass.getModel()).reload();
System.out.println("Refresh");
}};
but i got the error : java.lang.NullPointerException

I added a new Action to popup in getJPopupForExplorerTree(). You'll probably want to re-factor xmlFile out of the XMLTree constructor; I've hard coded it for expedience below:
popup.add(new AbstractAction("Reload") {
public void actionPerformed(ActionEvent e) {
System.out.println("Reload");
try {
root = getRoot("xml.xml");
setModel(new XMLTreeModel(root));
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
});

this is most complex code, probably
read tutorial about JTables DefaultTableModel (good described concept and logics for DefaultXxxModel is similair / the same)
read tutorial about JTree
read tutorial about Concurency in Swing,
especially description about SwingWorker
in your case better (sorry for that) would be create an new instance for DefaultTreeModel, fills data by using SwingWorker, add new model to the visible JTree,
by replacing model you'll lost all changes in the current JTree

I dont know the spesific code but you can try this
refreshAction = new AbstractAction("Refresh", IconFactory.getIcon("delete", IconFactory.IconSize.SIZE_16X16)) {
public void actionPerformed(ActionEvent e) {
DefaultTreeModel myTreeModel = (DefaultTreeModel) xmlClass.getModel();
myTreeModel.reload();
revalidate();
repaint();
}};

Related

Wicket - Set Model from another panel

I am quite new to Wicket. I am adding a model to a sub-panel(ChartPanel) from a main panel (MainPanel) on a button click.
MainPanel.java
On button click, I am re-adding the chartPanel after I change its model. Following is the code I am using in the buttonClick of the MainPanel. Here the onRenderAnnotations event is generated on some click in the UI.
#OnEvent
public void onRenderAnnotations(RenderAnnotationsEvent aEvent)
{
LOG.trace("clicked on the annotation");
renderChart( aEvent.getRequestHandler());
}
private void renderChart(IPartialPageRequestHandler aRequestHandler)
{
MultiValuedMap<String, Double> recommenderScoreMap = getLatestScores(aRequestHandler);
Map<String,String> curveData = new HashMap<String,String>();
LearningCurve learningCurve = new LearningCurve();
for (String recommenderName : recommenderScoreMap.keySet()) {
String data = recommenderScoreMap.get(recommenderName).stream().map(Object::toString)
.collect(Collectors.joining(", "));
curveData.put(recommenderName,data);
learningCurve.setCurveData(curveData);
learningCurve.setMaximumPointsToPlot(MAX_POINTS_TO_PLOT);
}
chartPanel.setDefaultModel(Model.of(learningCurve));
// to avoid the error, A partial update of the page is being rendered
try {
aRequestHandler.add(chartPanel);
}
catch (IllegalStateException e) {
LOG.warn("Not updating the chart. " + e.toString());
setResponsePage(getPage());
}
}
ChartPanel.java
After this in the chartPanel, I want to use the updated model to add component inside the chartpanel. What would be the best way to do that?
I want to do something like this in the class ChartPanel:
#Override
protected void onRender()
{
super.onModelChanged();
LearningCurve newLearningCurve = getModel().getObject();
requestTarget = ???
String js = createJavascript(newLearningCurve);
requestTarget.prependJavascript(js);
}
My question is, in the above code how to get the request target since it is not an ajax request neither do I get it in the arguments. Should I use some other function where I also get a requestTarget. But I want it to be called every time the model of ChartPanel is updated from anywhere.
Pardon my ignorance. I have been trying for a few days but I am still stuck. I tried to explain it enough but if any information is missing, please comment and I will add it right away.
Thanks.
You should override renderHead() instead:
#Override
public void renderHead(IHeaderResponse response)
{
super.renderHead(response);
response.render(OnLoadHeaderItem.forScript(
createJavascript(newLearningCurve)));
}
This way your chart will be shown correctly regardless whether it was added due to an AjaxRequest or simply when the page is rerendered.

How to add help file to frame?

I'm making plugin for eclipse which opens frame with some table's when plugin command is activated. Now I want to add help file to plugin's frame, so that when clicked on help file's link in frame, file opens (executes). File is suppose to be part of plugin. My problems are:
Don't know how to make link and add it to frame.
Don't know how to locate that file in plugin from run time application.
JLabel lblFileLink = new JLabel("Help");
lblFileLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblFileLink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
/* Add code for opening file from plugin.*/
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
Found this code somewhere, now I need to implement link, any thoughts?
If i understand you question correct, something like this should work:
JLabel lblFileLink = new JLabel("Help");
lblFileLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblFileLink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
java.awt.Desktop.getDesktop().edit(INSERTYOURFILEHERE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
This will open the standard text editor and show your file. Just replace INSERTYOURFILEHERE with your own text file.
Edit: If you want to open it in Eclipse maybe look at this
Edit2: The gist of the link above:
File fileToOpen = new File("externalfile.xml");
if (fileToOpen.exists() && fileToOpen.isFile()) {
IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditorOnFileStore( page, fileStore );
} catch ( PartInitException e ) {
//Put your exception handler here if you wish to
}
} else {
//Do something if the file does not exist
}

JAVA javaFX menuBar, multiple items, one method (scene Builder)

I have a window built with scene builder with a menuBar.
In the menuBar there are a couple of Menuitems that only open other windows.
So I want to write only one function that can be used by each one of those menuItems, and open the appropriate window.
I tried to give an id for each menuItem, and with this function
public void openWindow(ActionEvent event){
System.out.println( event);
}
I can see that id (example : customer menuItem) ,
javafx.event.ActionEvent[source=MenuItem[id=customers, styleClass=[menu-item]]]
But I dont know how to get it to use it to open the customer window.
In order to get id from ActionEvent you should cast the source of it to MenuItem:
public void openWindow(ActionEvent event){
MenuItem source = (MenuItem) event.getSource();
System.out.println(source.getId());
}
note, that if you are not sure that the source of event is of type MenuItem you can check it like so:
if (event.getSource() instanceof MenuItem) {
MenuItem source = (MenuItem) event.getSource();
System.out.println(source.getId());
}
One option is to get the source of the event (the MenuItem) and retrieve some appropriate data from it (e.g. the id or the userData), as shown in other answers. This will work, but it feels a little fragile as you are relying on string binding and having to perform casts on the types all over the place.
I prefer in this situation just to define a separate method for handling each menu item. Obviously, you can still refactor common functionality into a separate method, in the usual way.
public class MyController {
#FXML
private void openCustomersWindow() {
openWindow("/path/to/customers.fxml");
}
#FXML
private void openOrdersWindow() {
openWindow("/path/to/orders.fxml");
}
// ...
private void openWindow(String resource) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource(resource));
Scene scene = new Scene(loader.load());
Stage newWindow = new Stage();
newWindow.setScene(scene);
newWindow.show();
} catch (Exception exc) {
// handle errors....
}
}
}
and then just use onAction="#openCustomersWindow" for one menu item and onAction="#openOrdersWindow" for another, etc.
Clearly, there is a little repeated code here, but it's not bad (certainly no worse than the amount of repetition in the FXML). If you had enough MenuItems that this were problematic, you would probably want to consider defining them in Java code instead of FXML anyway.
If everything has an ID you can try this.
#FXML void openWindow(ActionEvent event){
try
{
MenuItem tempMenuItem = (MenuItem)event.getSource();
System.out.println(tempMenuItem.getId());
switch(tempMenuItem.getId())
{
case "yourFirstID":
//open your first window here
break;
case "yourSecondID":
//open your second window here
break;
}
}
catch (IOException ex)
{
//catch errors here
}
}

Java how do I save a background color once my application has been launched again

I'm trying to create a button in game where the background color will go from light_gray to dark_gray. However when the application relaunches I have to re select the button to get the color back to dark_gray.
How would I have it so that it saves the color when the application is relaunched?
My code is very simple and is just an action listener on the button which then changes the bg color of selected items.
Ok, I have now had the chance to allow it to create the properties file but one doesn't know how one could store the data. I've seen people have stuff such as 'properties.setProperty("Favorite sport", "Football");'
But how could one have this so that it stores the bg color?
windowDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
try {
Properties properties = new Properties();
properties.setProperty();
File file = new File("DarkTheme.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Dark theme background colour");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
The java.util.prefs Preferences API is well suited for storing persistent preference data for user applications running on the desktop.
Here's an example how you can use it to store and retrieve persistent background color settings:
import java.awt.Color;
import java.util.prefs.Preferences;
public class MyPrefs {
private static Preferences preferences =
Preferences.userRoot().node("myappname.ColorPreferences");
public static void storeBackground(Color background) {
preferences.putInt("background", background.getRGB());
}
public static Color retrieveBackground() {
// Second argument is the default when the setting has not been stored yet
int color = preferences.getInt("background", Color.WHITE.getRGB());
return new Color(color);
}
}
To call it, use something like:
public static void main(String[] args) {
System.out.println("Background: " + retrieveBackground());
storeBackground(Color.RED);
}
You can store the color as an int value in the properties file, as follows:
windowDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
getProperties().setProperty("color", Integer.toString(getColor().getRGB()));
}
});
Have the properties as a member of the window this button is in, or even better, in some general location of the application (the class with the main() perhaps ?), and access it with getProperties().
When you need to use the color, parse the string:
Color color = new Color(Integer.parseInt(getProperties().getProperty("color")));
Don't save the properties file on each button click, instead, do so when the application is about to exit:
mainWindow.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
mainWindow.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
File file = new File("DarkTheme.properties");
FileOutputStream fileOut = new FileOutputStream(file);
getProperties().store(fileOut, "Dark theme background colour");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
mainWindow.dispose();
}
}
});
The change done in memory will be disposed once the application is terminated. If you want to persist some data (in this case, the background color), then you need to store is somewhere, e.g. file, database, etc.
For a simple application, storing your data in a file will be practical.
To do this, you will need to:
- when application starts, read the file, and apply the color specified in the file
- while the application is running and user changes the color, save the color to the same file
To deal with file, you will need to use File, FileReader, and FileWriter classes (all are in java.io package).

How to create a graph window in java

I'm using this code
private void botaoGrafADMouseClicked(java.awt.event.MouseEvent evt) {
try {
boolean[] b=new boolean[8];
if (Caixa9.isSelected()) b[0]=true; else b[0]=false;
if (Caixa11.isSelected()) b[1]=true; else b[1]=false;
if (Caixa10.isSelected()) b[2]=true; else b[2]=false;
if (Caixa12.isSelected()) b[3]=true; else b[3]=false;
b[4]=false;b[5]=false;b[6]=false;b[7]=false;
final LineChartDemo1 demo = new LineChartDemo1("Leitura A/D",b,"outad.txt",4);
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Comunicacao.class.getName()).log(Level.SEVERE, null, ex);
}
}
to call an graph interface. But, when I do this, every time I call the graph, it generates on new window and, if I close on of these windows, the whole program is closed.
I'd want to know what am I doing wrong. How Can I avoid this (I would post a printscreen, but, as new user, I can't, it is on http://i.stack.imgur.com/4JLxQ.png I think
Edit: Image
JFrame has a default close operation (i.e. what happens when you close the window using your window manager) of EXIT_ON_CLOSE. Use JFrame.setDefaultCloseOperation to set a different value.
I don't know what the class LineChartDemo1 is, but you could probably set it as the content of a JDialog and call setDefaultCloseOperation (JDialog.DISPOSE_ON_CLOSE) on each dialog. This way, when the user closes the dialog, only that window will close, the others will remain open.
I created a new netbeans JFrame and made reference to it like this:
InterfaceGrafico minhaInterface = new InterfaceGrafico("Leitura I/O",b,"outio.txt",8);
where the arguments where the same to generate the graph. In this "InterfaceGrafico" class:
public InterfaceGrafico(final String title,boolean[] b, String nomeArquivo, int col) {
try {
initComponents();
final LineChartDemo1 demo = new LineChartDemo1("Leitura I/O", b, "outio.txt", 8);
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(InterfaceGrafico.class.getName()).log(Level.SEVERE, null, ex);
}
}
That means, I just shifted the code to another JFrame. I also commented the public void run method . Now I can close each graph generated without closing the whole application and the other generated graphs. In the "LineChart1" class, I added this
public void windowClosing(final WindowEvent evt){
if(evt.getWindow() == this){
dispose();
}
}

Categories

Resources