How to add another row to jTable - netbeans

Before I start, I've read through the current topics on how to do this and the solutions aren't working for me. I've tried table.addRow(...) and that doesn't work. I've tried to add an object but it just resets the table and makes one single row. Here's a basic netbeans pane code :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package components;
import java.awt.event.*;
/**
*
* #author Ethan
*/
public class AccountManager extends javax.swing.JFrame {
/**
* Creates new form AccountManager
*/
public AccountManager() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Account Manager");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"Admin", "Admin", new Integer(1), new Boolean(true)},
{"Username", "Password", new Integer(1), new Boolean(true)}
},
new String [] {
"Username", "Password", "Account Type", "Active"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Boolean.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jTable1.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(jTable1);
jButton1.setText("Add Account");
class addAccount implements ActionListener{
public void actionPerformed(ActionEvent e){
//Action listener for button 1 that adds the row
}
}
jButton1.addActionListener(new addAccount());
jButton2.setText("Delete Account");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(78, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Steel".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AccountManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AccountManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AccountManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AccountManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AccountManager().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
So does anyone know how to add a row with netbean's jTable? I would greatly appreciate help on the topic, thanks!
Also, if deleting a row isn't like adding a row in the code, I would appreciate some pointers on how to do that, also.

One of your problems is that you are hard coding you entries for you table, you will need some form of database for storing the data. You cannot add entries to your table through a method that will try add coding for specifics.
Best choice is use a embedded database such as SQLite or server database such as MySQL.
There is many different ways to execute such using a database. The best way to add, edit or delete entries to and from a table is through connection and integration with a database. It is simple, easy to use and most effective or efficient method.
coding for connection to a MySQL database:
//used to add the entry to database table
String query = "insert into tableName (col1, col2, col3,col4) values ('data','data','data','data')";
Class.forName("com.mysql.jdbc.Driver");
//connection
Connection conn = (Connection)
//root and username and password for access to the database
DriverManager.getConnection("jdbc:mysql://localhost:3306/NameOfDatabase","root","password");
//create the statement that will be used
Statement stmt=conn.createStatement();
//executes the query statement
stmt.executeUpdate(query);
Must make sure you import you mysql library as well and imports where ever is needed during your code integration throughout.
When you done with adding an entry just refresh your table by calling it up again. Easy way but not the most effective but will help you just out for this section.
Hope this helps

Related

How to override installed mappings of Behavior?

In java-9 Skins made it into public scope, while Behaviors are left in the dark - nevertheless changed considerably, in now using InputMap for all input bindings.
CellBehaviorBase installs mouse bindings like:
InputMap.MouseMapping pressedMapping, releasedMapping;
addDefaultMapping(
pressedMapping = new InputMap.MouseMapping(MouseEvent.MOUSE_PRESSED, this::mousePressed),
releasedMapping = new InputMap.MouseMapping(MouseEvent.MOUSE_RELEASED, this::mouseReleased),
new InputMap.MouseMapping(MouseEvent.MOUSE_DRAGGED, this::mouseDragged)
);
A concrete XXSkin now installs the behavior privately:
final private BehaviorBase behavior;
public TableCellSkin(TableCell control) {
super(control);
behavior = new TableCellBehavior(control);
....
}
The requirement is replace the mousePressed behavior (in jdk9 context). The idea is to grab super's field reflectively, dispose all its mappings and install the custom behavior. For some reason that I don't understand, the old bindings are still active (though the old mappings are empty!) and are invoked before the new bindings.
Below is a runnable example to play with: the mapping to mousePressed is simply implemented to do nothing, particularly to not invoke super. To see the old bindings at work, I set a conditional debug breakpoint at CellBehaviorBase.mousePressed like (in Eclipse):
System.out.println("mousePressed super");
new RuntimeException("whoIsCalling: " + getNode().getClass()).printStackTrace();
return false;
Run a debug and click into any cell, then the output is:
mousePressed super
java.lang.RuntimeException: whoIsCalling: class de.swingempire.fx.scene.control.cell.TableCellBehaviorReplace$PlainCustomTableCell
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(CellBehaviorBase.java:169)
at com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
//... lots more of event dispatching
// until finally the output in my custom cell behavior
Feb. 02, 2016 3:14:02 NACHM. de.swingempire.fx.scene.control.cell.TableCellBehaviorReplace$PlainCustomTableCellBehavior mousePressed
INFORMATION: short-circuit super: Bulgarisch
I would expect to only see the very last part, that is the printout by my custom behavior. It feels like I'm somehow fundamentally off - but can't nail it. Ideas?
The runnable code (sorry for its length, most is boiler-plate, though):
public class TableCellBehaviorReplace extends Application {
private final ObservableList<Locale> locales =
FXCollections.observableArrayList(Locale.getAvailableLocales());
private Parent getContent() {
TableView<Locale> table = createLocaleTable();
BorderPane content = new BorderPane(table);
return content;
}
private TableView<Locale> createLocaleTable() {
TableView<Locale> table = new TableView<>(locales);
TableColumn<Locale, String> name = new TableColumn<>("Name");
name.setCellValueFactory(new PropertyValueFactory<>("displayName"));
name.setCellFactory(p -> new PlainCustomTableCell<>());
TableColumn<Locale, String> lang = new TableColumn<>("Language");
lang.setCellValueFactory(new PropertyValueFactory<>("displayLanguage"));
lang.setCellFactory(p -> new PlainCustomTableCell<>());
table.getColumns().addAll(name, lang);
return table;
}
/**
* Custom skin that installs custom Behavior. Note: this is dirty!
* Access super's behavior, dispose to get rid off its handlers, install
* custom behavior.
*/
public static class PlainCustomTableCellSkin<S, T> extends TableCellSkin<S, T> {
private BehaviorBase<?> replacedBehavior;
public PlainCustomTableCellSkin(TableCell<S, T> control) {
super(control);
replaceBehavior();
}
private void replaceBehavior() {
BehaviorBase<?> old = (BehaviorBase<?>) invokeGetField(TableCellSkin.class, this, "behavior");
old.dispose();
// at this point, InputMap mappings are empty:
// System.out.println("old mappings: " + old.getInputMap().getMappings().size());
replacedBehavior = new PlainCustomTableCellBehavior<>(getSkinnable());
}
#Override
public void dispose() {
replacedBehavior.dispose();
super.dispose();
}
}
/**
* Custom behavior that's meant to override basic handlers. Here: short-circuit
* mousePressed.
*/
public static class PlainCustomTableCellBehavior<S, T> extends TableCellBehavior<S, T> {
public PlainCustomTableCellBehavior(TableCell<S, T> control) {
super(control);
}
#Override
public void mousePressed(MouseEvent e) {
if (true) {
LOG.info("short-circuit super: " + getNode().getItem());
return;
}
super.mousePressed(e);
}
}
/**
* C&P of default tableCell in TableColumn. Extended to install custom
* skin.
*/
public static class PlainCustomTableCell<S, T> extends TableCell<S, T> {
public PlainCustomTableCell() {
}
#Override protected void updateItem(T item, boolean empty) {
if (item == getItem()) return;
super.updateItem(item, empty);
if (item == null) {
super.setText(null);
super.setGraphic(null);
} else if (item instanceof Node) {
super.setText(null);
super.setGraphic((Node)item);
} else {
super.setText(item.toString());
super.setGraphic(null);
}
}
#Override
protected Skin<?> createDefaultSkin() {
return new PlainCustomTableCellSkin<>(this);
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(getContent(), 400, 200));
primaryStage.setTitle(FXUtils.version());
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
/**
* Reflectively access super field.
*/
public static Object invokeGetField(Class source, Object target, String name) {
try {
Field field = source.getDeclaredField(name);
field.setAccessible(true);
return field.get(target);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unused")
private static final Logger LOG = Logger
.getLogger(TableCellBehaviorReplace.class.getName());
}
Edit
The suggestion inherit from the abstract skin XXSkinBase instead of the concrete XXSkin (then you are free to install whatever behavior you want, dude :-) is very reasonable and should be the first option. In the particular case of XX being TableCell, that's currently not possible, as the base class contains abstract package-private methods. Also, there are XX that don't have an abstract base (like f.i. ListCell).
Might be a bug in InputMap:
Digging into the sources I found some internal book-keeping (eventTypeMappings) parallel to mappings (these are the handlers). InputMap is listening to changes in mappings and updates the internal book-keeping on changes
mappings.addListener((ListChangeListener<Mapping<?>>) c -> {
while (c.next()) {
// TODO handle mapping removal
if (c.wasRemoved()) {
for (Mapping<?> mapping : c.getRemoved()) {
removeMapping(mapping);
}
}
// removeMapping
private void removeMapping(Mapping<?> mapping) {
// TODO
}
Meaning that the internal structure is never cleaned, particularly not when the mappings are removed in behavior.dispose(). When looking up eventHandlers - by inputMap.handle(e), see debug stacktrace shown in the question - the old handler is found in the internal book-keeping structure.
Joys of early experiments ... ;-)
At the end, a (very dirty, very hacky!) solution is to take over InputMap's job and force a cleanup of the internals:
private void replaceBehavior() {
BehaviorBase<?> old = (BehaviorBase<?>) invokeGetField(TableCellSkin.class, this, "behavior");
old.dispose();
cleanupInputMap(old.getInputMap());
// at this point, InputMap mappings are empty:
// System.out.println("old mappings: " + old.getInputMap().getMappings().size());
replacedBehavior = new PlainCustomTableCellBehavior<>(getSkinnable());
}
/**
* This is a hack around InputMap not cleaning up internals on removing mappings.
* We remove MousePressed/MouseReleased/MouseDragged mappings from the internal map.
* Beware: obviously this is dirty!
*
* #param inputMap
*/
private void cleanupInputMap(InputMap<?> inputMap) {
Map eventTypeMappings = (Map) invokeGetField(InputMap.class, inputMap, "eventTypeMappings");
eventTypeMappings.remove(MouseEvent.MOUSE_PRESSED);
eventTypeMappings.remove(MouseEvent.MOUSE_RELEASED);
eventTypeMappings.remove(MouseEvent.MOUSE_DRAGGED);
}
BTW: just in case anybody is wondering wtf - without, my hack around the missing commitOnFocusLost when editing a cell stopped working in java-9.
Try in PlainCustomTableCellSkin to inherit from the abstract class TableCellSkinBase rather than from TableCellSkin.
Then you can call the super constructor, which takes an TableCellBehaviorBase object as additional param.
Then you can save your time replacing it, by initializing it directly with the right one.
Just for more claryfication:
TableCellSkin extends TableCellSkinBase
TableCellBehavior extends TableCellBehaviorBase
One more thing. You need to also call super.init(tableCell) in your constructor.
Take the TableCellSkin class as reference.

delete Treenode not removed

I am developing in Visual Studio 2012 web interface. When I remove a parent node it removes correctly, but when I try to remove a child node the node stays and does not seem to get removed. Both methods shows the same result.
Tree1.Nodes.Remove(e.Node);
This is a postback method removing the node with e as FineUI.TreeCommandEventArgs.
Tree1.Nodes.Remove(Tree1.SelectedNode);
This is another method to remove the node. There is no update or refresh method to refresh the tree. Both of which cannot delete a child node.
Another question would be that I want to update the database based on the SelectedNode, the SelectedNodeID contains a string with the ID value, but it exist in a form like fnode1 where I only want the integer value at the end. I want to know how to get just the integer value so I can delete the selected node from the database.
what u need to do is you need to take DefaultNode from Tree and then u have to Remove it. see this.
DefaultMutableTreeNode defaultMutableTreeNode = new DefaultMutableTreeNode(node_vervesystems);
model.removeNodeFromParent(defaultMutableTreeNode);
that will Work.
Here the Example for the same.
import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author kishan
*/
public class JTreeRemoveNode extends JFrame{
public JTreeRemoveNode() throws HeadlessException {
initializeUI();
}
private void initializeUI() {
setSize(200, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Address Book");
String[] names = new String[] {"Alice", "Bob", "Carol", "Mallory"};
for (String name : names) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(name);
root.add(node);
}
final JTree tree = new JTree(root);
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(200, 400));
JButton removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
TreePath[] paths = tree.getSelectionPaths();
for (TreePath path : paths) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if (node.getParent() != null) {
model.removeNodeFromParent(node);
}
}
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(tree, BorderLayout.CENTER);
getContentPane().add(removeButton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JTreeRemoveNode().setVisible(true);
}
});
}
}
hope that will help.

Generating check boxes dynamically, Netbeans

I am developing a desktop application in which I want Admin have option to delete users, for which I planned that whenever Admin clicks on 'delete users' button a new tab will open in which check boxes with the name of all existing users in my database should appear(so that he can delete multiple users simultaneously); so basically I need to generate dynamic check boxes as per my database.
I am using Netbeans 7.0.1, jdk 1.6, sqlite3.
After searching on google I got two links which match to my problem:
http://www.coderanch.com/t/345949/GUI/java/create-dynamic-checkboxes#2805277
Creating dcheckbox dynamically in Java-NetBeans
I have tried to follow the code from above first link but it does not working for me properly. What I does is just created new JFrame in netbeans and called a method inside constructor which create checkboxes as per needed, method's code is as below:
public class Work extends javax.swing.JFrame {
/** Creates new form Work */
public Work() {
initComponents();
checks = new java.util.ArrayList<>();
createCheckboxes();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void createCheckboxes(){
panel = new javax.swing.JPanel();
this.add(panel);
for(int i = 0; i<4; i++){
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
panel.add(box);
checks.add(box);
panel.revalidate();
panel.repaint();
}
panel.setVisible(true);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
private java.util.ArrayList <javax.swing.JCheckBox> checks;
private javax.swing.JPanel panel;
}
The output is just a blank frame. Please help me to know where I am wrong!!
And yes this code is not connected to database yet, once it will work then I can modify it to work with database.
Also is their any other betterway to accomplish my task or am on right path?`
I think it might help if u call the following function whenever to wanna create a new checkbox..
public class CheckBox extends JFrame{
//private static final long serialVersionUID = 1L;
public CheckBox() {
// set flow layout for the frame
this.getContentPane().setLayout(new FlowLayout(FlowLayout.TRAILING, 50, 20)); //(default) centered alignment and a default 5-unit horizontal and vertical gap.
JCheckBox checkBox1 = new JCheckBox("Checkbox 1");
checkBox1.setSelected(true);
JCheckBox checkBox2 = new JCheckBox("Checkbox 2", true);
JCheckBox checkBox3 = new JCheckBox("Checkbox 3");
// add checkboxes to frame
add(checkBox1);
add(checkBox2);
add(checkBox3);
}
private static void createAndShowGUI() {
//Create and set up the window.
//JFrame frame = new CreateCheckedUncheckedJCheckBox();
CheckBox cb = new CheckBox();
//Display the window.
cb.pack();
cb.setVisible(true);
cb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You add the new checkboxes as if your frame was using some simple layout such as FlowLayout, but it is not - it is using GroupLayout - see the generated initComponents() method.
If you want to handle ALL components in the frame dynamically, you can do this (it is better to create an empty class file and then paste the code below; do not ask NB to create a JFrame as it would again create a form to be designed in the visual designer; if you still do it then r-click it and change the layout to something simpler):
public class Work extends javax.swing.JFrame {
private java.util.List <javax.swing.JCheckBox> checks = new java.util.ArrayList<>();;
public Work() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new java.awt.FlowLayout()); // simply put the components next to each other
createCheckboxes();
}
private void createCheckboxes(){
for(int i=0; i<4; i++) {
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
add(box);
checks.add(box);
}
pack(); // this will tell the JFrame's panel to layout all the components
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
}
Or you can design part of your frame with the visual designer and then add the checkboxes. In that case add an empty panel in the designer, set the panel's layout to something like flow or grid layout and then add the checkboxes to that panel from your code in the same way as above.
You validate needs to be called only if the panel/frame is already visible. Calling pack works even then, but might change the size of the frame. Also validating can be done after all components were added not after adding each one.
To add check boxes or any other component dynamically in Netbeans JFrame one need to manage Layout Managers, by default netbeans frames use Free Design Layout, follow steps below:
Create blank JFrame -->Add Jpanel to it-->right click to the panel, select setLayout and change it to GridLayout.
Now we are free to add ant components on this panel.
Also don't forgate to add revalidate() and repaint() methods.
This worked for me.

Netbeans ExplorerTopComponent Node losing focus when showing dialog

I have a netbeans RCP application that shows a set of nodes in the explorertopcomponent. When selected, I display details on the editortopcomponent and it works well. When I show a dialog using JOptionPage on the editor, the selected node in the tree is deselected, and eventually my editortopcomponent also loses the selected node details. Is there a way to save the selected node in the tree from being deselected if a dialog opens?
Thanks.
it is simple.
In your explorertopcomponent you have LookupListner, that "is waiting" on event "someYourNodeClass" (for example Album)appears in the lookup. You must removeLookupListener, when your explorertopcomponent is not visible or yust do nothing.
/**
* your explorertopcomponent
*/
#ConvertAsProperties(
dtd = "-//com.galileo.netbeans.module//Y//EN",
autostore = false)
#TopComponent.Description(
preferredID = "YTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
#TopComponent.Registration(mode = "explorer", openAtStartup = false)
#ActionID(category = "Window", id = "com.galileo.netbeans.module.YTopComponent")
#ActionReference(path = "Menu/Window" /*, position = 333 */)
#TopComponent.OpenActionRegistration(
displayName = "#CTL_YAction",
preferredID = "YTopComponent")
#Messages({
"CTL_YAction=Y",
"CTL_YTopComponent=Y Window",
"HINT_YTopComponent=This is a Y window"
})
public final class YTopComponent extends TopComponent implements LookupListener {
private Lookup.Result<Album> result;
public YTopComponent() {
initComponents();
setName(Bundle.CTL_YTopComponent());
setToolTipText(Bundle.HINT_YTopComponent());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
#Override
public void componentOpened() {
result = Utilities.actionsGlobalContext().lookupResult(Album.class);
result.addLookupListener(this);
}
#Override
public void componentClosed() {
result.removeLookupListener(this);
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// TODO store your settings
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
public void resultChanged(LookupEvent le) {
Collection<? extends Album> allInstances = result.allInstances();
TopComponent findTopComponent = WindowManager.getDefault().findTopComponent("YourNodeExplorerWindow");
if (findTopComponent == null) {
return;
}
if (!findTopComponent.isShowing()) {
return;
}
if (!allInstances.isEmpty()) {
showDetail(allInstances.iterator().next());
}
}
}
Jirka

JLayeredPane in netbeans

I am trying to put two components Jeditorpane and Jtextarea in Jlayeredpane. I am using Netbeans. I added jeditorpane and jtextarea in jlayeredpane and two buttons. When i click on button1 then it should show message "Hello world doing nice".
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextArea1.setText("");
jTextArea1.setOpaque(true);
jLayeredPane1.moveToFront(jEditorPane1);
jEditorPane1.setText("Hello world doing nice");
}
and when click on button2 then it should show message "Hello world not doing good".
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jEditorPane1.setText("");
jEditorPane1.setOpaque(true);
jLayeredPane1.moveToFront(jTextArea1);
jTextArea1.setText("Hello world not doing good");
}
But when i click on button1 then it shows message "Hello world doing nice" but when i click on button2 then it does not shows message "Hello world not doing good" as it should move the component to front. Could some one please tell me how to solve this. Here is source code which is partially generated by netbeans and partially written by me.
Thank you.
public class test extends javax.swing.JFrame {
/** Creates new form test */
public test() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLayeredPane1 = new javax.swing.JLayeredPane();
jScrollPane1 = new javax.swing.JScrollPane();
jEditorPane1 = new javax.swing.JEditorPane();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLayeredPane1.add(jTextArea1);// i added this code using custom code property
jLayeredPane1.add(jEditorPane1); //i added this code using custom code property
jEditorPane1.setText("");//i added this code using custom code property
jScrollPane1.setViewportView(jEditorPane1);
jScrollPane1.setBounds(0, 0, 480, 200);
jLayeredPane1.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jTextArea1.setText("");//i added this code using custom code property of netbeans
jScrollPane2.setViewportView(jTextArea1);
jScrollPane2.setBounds(0, 0, 480, 200);
jLayeredPane1.add(jScrollPane2, javax.swing.JLayeredPane.DEFAULT_LAYER);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 505, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(143, 143, 143)
.addComponent(jButton2)))
.addContainerGap(68, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(43, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextArea1.setText("");
jTextArea1.setOpaque(true);
jLayeredPane1.moveToFront(jEditorPane1);
jEditorPane1.setText("Hello world doing nice");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jEditorPane1.setText("");
jEditorPane1.setOpaque(true);
jLayeredPane1.moveToFront(jTextArea1);
jTextArea1.setText("Hello world not doing good");
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JEditorPane jEditorPane1;
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
You should probably be using CardLayout instead.