Issue
My goal is simple - save the current HTML file in the NetBeans editor with one additional line at the top and bottom of the file, and with the extension of ".h".
This is my first attempt at a NetBeans module, but following some tutorials and research, I got as far as adding an entry to the popup menu when you right-click on an HTML file in the editor. It currently just shows a "Hello World" message:
The code to do that is here:
package ksmiller99.savehtmlasarduinoresource;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Edit",
id = "ksmiller99.savehtmlasarduinoresource.SaveHtmlAsArduinoResource"
)
@ActionRegistration(
displayName = "#CTL_SaveHtmlAsArduinoResource"
)
@ActionReference(path = "Editors/text/html/Popup")
@Messages("CTL_SaveHtmlAsArduinoResource=Save as Arduino Resource")
public final class SaveHtmlAsArduinoResource implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
//todo add a line to top and bottom of current file and save with .h extension
JOptionPane.showMessageDialog(null, "Hello Save As World");
}
}
How can I access the contents of the current editor? Would a different approach make more sense?
I'm using NetBeans 12.0, JDK 13, Windows 10.
Solution
Use the New Action wizard to create the source code for a Conditionally Enabled
action, enabled when User Selects One Node
.
In the 2nd wizard panel select File Type Context Menu
and choose text/html
as content type. If you want your action to appear only in the context menu you can disable Global Menu Item
.
You should end up with code like this:
@ActionID(
category = "File",
id = "org.test.TestHtmlAction"
)
@ActionRegistration(
displayName = "#CTL_TestHtmlAction"
)
@ActionReference(path = "Loaders/text/html/Actions", position = 0)
@Messages("CTL_TestHtmlAction=TestHtmlAction")
public final class TestHtmlAction implements ActionListener
{
private final DataObject context;
private static final Logger LOGGER = Logger.getLogger(TestHtmlAction.class.getName());
public TestHtmlAction(DataObject context)
{
this.context = context;
}
@Override
public void actionPerformed(ActionEvent ev)
{
FileObject file = context.getPrimaryFile();
LOGGER.info("context=" + context.getName() + " file.getPath()=" + file.getPath());
}
}
The wizard creates a context aware action, which is enabled only when user selects a single HTML file node. The DataObject
parameter gives you the context of the selected node, so you can retrieve the file path etc.
Answered By - jjazzboss
Answer Checked By - Terry (JavaFixing Volunteer)