I have a code which when run generates a table in swing form which contains a set of checkboxes which can be selected or unselected
When I click on the Check All tab I am able to select/unselect all the other below check boxes but when i select one of the below checkboxes individually I get this error :
> Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JTable
at com.tps.charts.CheckBoxHeader.handleClickEvent(JTableHeaderCheckBox.java:152)
at com.tps.charts.CheckBoxHeader.mouseClicked(JTableHeaderCheckBox.java:168)
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source) mousePressed......
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableHeaderCheckBox {
private Object colNames[] = {"", "String", "String"};
private Object[][] data = {};
private DefaultTableModel dtm;
private JTable table;
private TableColumn tc;
public void buildGUI() {
dtm = new DefaultTableModel(data, colNames);
table = new JTable(dtm);
for (int x = 0; x < 5; x++) {
dtm.addRow(new Object[]{false, "Row " + (x + 1) + " Col 2", "Row " + (x + 1) + " Col 3"});
}
JScrollPane sp = new JScrollPane(table);
tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
JFrame f = new JFrame();
f.getContentPane().add(sp);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
private class MyItemListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent e) {
System.out.println("ItemStateChanged");
Object source = e.getSource();
if (source instanceof AbstractButton == false) {
return;
}
boolean checked = e.getStateChange() == ItemEvent.SELECTED;
for (int x = 0, y = table.getRowCount(); x < y; x++) {
table.setValueAt(checked, x, 0);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JTableHeaderCheckBox().buildGUI();
}
});
}
}
class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {
private static final long serialVersionUID = 1L;
private CheckBoxHeader rendererComponent;
private int column;
private boolean mousePressed = false;
public CheckBoxHeader(ItemListener itemListener) {
rendererComponent = this;
rendererComponent.addItemListener(itemListener);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (table != null) {
JTableHeader header = table.getTableHeader();
table.addMouseListener(rendererComponent);
if (header != null) {
rendererComponent.setForeground(header.getForeground());
rendererComponent.setBackground(header.getBackground());
rendererComponent.setFont(header.getFont());
header.addMouseListener(rendererComponent);
}
}
setColumn(column);
rendererComponent.setText("Check All");
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return rendererComponent;
}
protected void setColumn(int column) {
this.column = column;
}
public int getColumn() {
return column;
}
protected void handleClickEvent(MouseEvent e) {
if (mousePressed) {
mousePressed = false;
JTableHeader header = (JTableHeader) (e.getSource());
JTable tableView = header.getTable();
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
column = tableView.convertColumnIndexToModel(viewColumn);
if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
System.out.println(" doClick()......");
doClick();
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(" mouseClicked()......");
handleClickEvent(e);
/* problem occurs from this line */
((JTableHeader) e.getSource()).repaint();
}
#Override
public void mousePressed(MouseEvent e) {
//System.out.println("mousePressed(MouseEvent e).......");
mousePressed = true;
}
#Override
public void mouseReleased(MouseEvent e) {
//System.out.println(" mouseReleased()......");
}
#Override
public void mouseEntered(MouseEvent e) {
//System.out.println(" mouseEntered()......");
}
#Override
public void mouseExited(MouseEvent e) {
//System.out.println("mouseExited()......");
}
}
with Exception
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
javax.swing.JTable cannot be cast to javax.swing.table.JTableHeader
On line 152: JTableHeader header = (JTableHeader)(e.getSource()); you are assuming the event is on the table header. You need to check event source's class to see if it's on the header or an individual checkbox.
You are casting the source of the event to a JTableHeader:
JTableHeader header = (JTableHeader) (e.getSource());
and the source is a JTable when you click at a cell. I would have two different listeners for the header and the cell selection or you can do a hack by checking event.getSource() instanceof ... in your mouse-click-listener.
Related
I have a problem here with my javafx application jar, generated by Eclipse mars. Actually everything is running pretty well if I am running inside eclipse. However when I use the command line and try to run the jar of my application which was previously created by eclipse, using the command:
java -jar TalanTestingWithXPathFX.jar
I got a lot of errors in my terminal. The error are the following:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Location is not set.
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at talan.test.webApp.MainApp.initRootLayout(Unknown Source)
at talan.test.webApp.MainApp.start(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162 (Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
... 1 more
Exception running application talan.test.webApp.MainApp
This is some code from the main class
public class MainApp extends Application {
#FXML
private static Stage primaryStage;
#FXML
private AnchorPane rootLayout;
public Project mainProject;
public static rootLayOutController rootController;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setResizable(true);
this.primaryStage.setTitle("AutoGenDriver");
initRootLayout();
//showSubWindow();
}
/**
* Initializes the root layout.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("./view/rootLayOut.fxml"));
rootLayout = loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
//
primaryStage.setScene(scene);
rootController=loader.getController();
// Give the controller access to the main app.
rootLayOutController controller = loader.getController();
controller.setMainApp(this);
primaryStage.show();
} catch (IOException e) {
System.out.println("Loading error");
}
}
public void setProject(Project p){
this.mainProject = p;
}
/**
* Called when the user clicks New Project.
*/
#FXML
public static Project showNewProjectDialog() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/newProjectDialog.fxml"));
AnchorPane page = loader.load();
// Create the dialog Stage.
Stage dialogStage = new Stage();
dialogStage.setTitle("Add new Test Project");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(page);
dialogStage.setScene(scene);
// Set the project into the controller.
newProjectDialogController controller = loader.getController();
controller.setDialogStage(dialogStage);
// controller.setProject(project);
// Show the dialog and wait until the user closes it
dialogStage.showAndWait();
return controller.getProject();
} catch (IOException e) {
System.out.println("Loading error");
return null;
}
}
public static void setPrimaryStage(Stage primaryStage) {
MainApp.primaryStage = primaryStage;
}
/**
* Returns the main stage.
* #return
*/
public static Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
this is some code from the rootLayOutController class
public void setRootTreeView(String nameProject) {
Image image=new Image(new File("C:\\Users\\DELL 3521\\workspaceMars\\TalanTestingFX\\Images\\dossier.png").toURI().toString(),20,20,true,true);
ImageView imv= new ImageView();
imv.setImage(image);
TreeItem<String> rootNode = new TreeItem<String>(tempProject.getName(),imv);
rootNode.setExpanded(true);
testProject.add(rootNode);
t.setRoot(rootNode);
}
/**
* add sub Elements to the TreeView
*
* #param mainApp
*/
public void addItemToTreeView(String item) {
testProject.get(0).getChildren().add(new TreeItem<String>(item));
}
public static Template getTemplate() {
return template;
}
public static void setTemplate(Template template) {
rootLayOutController.template = template;
}
public AnchorPane getContent() {
return content;
}
public void setContent(AnchorPane content) {
this.content = content;
}
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded.
*/
#FXML
private void initialize() {
handleTreeViewSelectElement();
newSuiteItem.setDisable(true);
openPageItem.setDisable(true);
cnxItem.setDisable(true);
openPageItem.setDisable(true);
scItem.setDisable(true);
acItem.setDisable(true);
dactItem.setDisable(true);
}
I'm using Swing, Java Messaging Service and GlassFish4.1 server to build a chat box from a Jpanel so I can add it to my Jframe application; but I seem to have a problem establishing a connection.
During runtime the program stops at the line:
TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup("BJconn");
I previously got this client-code to work on an Enterprise application, but now I'm attempting to add it to a regular Java project I'm rather stuck.
Really appreciate any help on this, I'm very new to JMS so please keep answers as Lamen as possible. Thanks!
import java.awt.event.KeyEvent;
import javax.jms.*;
import javax.naming.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class ChatPanel extends javax.swing.JPanel implements Runnable{
private Thread t = null;
private TopicConnection tpConnection = null;
private TopicPublisher tpPublisher = null;
private TopicSession tpSession = null;
private TopicSubscriber tpSubscriber = null;
private final String name;
/**
* Creates new form chatFrame
* #param nickName
*/
public ChatPanel(String nickName)
{
initComponents();
DefaultCaret caret = (DefaultCaret) gameInfoTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
name = nickName;
connect();
}
/**
* This method is called from within the constructor to initialise 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">
// </editor-fold>
public JTextArea getTextArea()
{
return gameInfoTextArea;
}
public void setText(String textString)
{
String s = gameInfoTextArea.getText() + "\n" + textString;
gameInfoTextArea.setText(s);
}
private void connect()
{
try
{
Context ctx = new InitialContext();
TopicConnectionFactory tcf = (TopicConnectionFactory)
ctx.lookup("BJconn");
tpConnection = tcf.createTopicConnection();
tpConnection.setClientID(name);
tpSession = tpConnection.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup("BJDest");
tpPublisher = tpSession.createPublisher(topic);
tpSubscriber = tpSession.createDurableSubscriber(topic, name);
tpConnection.start();
t = new Thread(this);
t.start();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Chat cannot connect");
System.out.println(e.getMessage());
}
}
/*private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
try
{
tpConnection.close();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage() );
}
} */
private void sendMessage()
{
try
{
TextMessage tx = tpSession.createTextMessage();
tx.setText(name + ": " + this.chatField.getText());
tpPublisher.send(tx);
this.chatField.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Cannot send message");
}
}
#Override
public void run()
{
try
{
while (true)
{
TextMessage tx = (TextMessage) tpSubscriber.receive();
if (tx != null)
{
String content = "";
content += this.gameInfoTextArea.getText() + "\n" + tx.getText();
this.gameInfoTextArea.setText(content);
Thread.sleep(100);
}
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
/**
* This method is called from within the constructor to initialise 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() {
chatField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
gameInfoTextArea = new javax.swing.JTextArea();
setBackground(new java.awt.Color(0, 102, 0));
chatField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chatFieldActionPerformed(evt);
}
});
chatField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
chatFieldKeyReleased(evt);
}
});
gameInfoTextArea.setEditable(false);
gameInfoTextArea.setColumns(20);
gameInfoTextArea.setRows(5);
jScrollPane1.setViewportView(gameInfoTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chatField)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chatField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>
private void chatFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void chatFieldKeyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER)
{
sendMessage();
}
}
// Variables declaration - do not modify
private javax.swing.JTextField chatField;
private javax.swing.JTextArea gameInfoTextArea;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
public class Activator implements BundleActivator {
TestFrame testFrame = new TestFrame();
public static JPanel graphPanel;
public void start(BundleContext context) throws Exception {
graphPanel = cartesianGraphs.getGraphPanel();
testFrame.getPanel1().add(graphPanel);
testFrame.setVisible(true);
}
}
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private library kutuphane = null;
private JPanel contentPane;
private JTabbedPane tabbedPane;
private JPanel panel1;
private JButton btn;
public TestFrame() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
contentPane.add(getTabbedPane(), BorderLayout.CENTER);
contentPane.add(getBtn(), BorderLayout.NORTH);
}
public JPanel getPanel1() {
if (panel1 == null) {
panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
}
return panel1;
}
private JButton getBtn() {
if (btn == null) {
btn = new JButton("Remove All and Add");
btnTabSil.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
TestFrame.this.getPanel1().removeAll();
Activator.graphPanel.revalidate();
// where it throws the exception is below
TestFrame.this.getPanel1().add(Activator.graphPanel);
TestFrame.this.revalidate();
TestFrame.this.repaint();
TestFrame.this.setVisible(true);
}
});
}
return btn;
}
}
In the activator class above I add (JPanel )graphpanel into (JPannel) testFrame.getPanel1() Then with a button in the testFrame class I used removeAll() method and add the static graphPannel again but I got the error below.
When I debug it I see that GLcanvas looses the peer. I couldnt find a solution.
Exception in thread "Thread-3" java.lang.RuntimeException:
javax.media.opengl.GLException: Unable to create temp OpenGL context
for device context 0xffffffffde01148b at
jogamp.common.awt.AWTEDTExecutor.invoke(AWTEDTExecutor.java:58) at
jogamp.opengl.awt.AWTThreadingPlugin.invokeOnOpenGLThread(AWTThreadingPlugin.java:103)
at
jogamp.opengl.ThreadingImpl.invokeOnOpenGLThread(ThreadingImpl.java:205)
at
javax.media.opengl.Threading.invokeOnOpenGLThread(Threading.java:172)
at javax.media.opengl.Threading.invoke(Threading.java:191) at
javax.media.opengl.awt.GLCanvas.display(GLCanvas.java:449) at
grafik.view.grafik.Gcontroller.draw(Gcontroller.java:169) at
grafik.model.data.Dcontroller.drawAll(Dcontroller.java:272) at
grafik.view.Wcontroller.GdataClean(Wcontroller.java:261) at
grafik.view.WThread.run(WThread.java:57) Caused by:
javax.media.opengl.GLException: Unable to create temp OpenGL context
for device context 0xffffffffde01148b at
jogamp.opengl.windows.wgl.WindowsWGLContext.createImpl(WindowsWGLContext.java:306)
at
jogamp.opengl.GLContextImpl.makeCurrentWithinLock(GLContextImpl.java:572)
at jogamp.opengl.GLContextImpl.makeCurrent(GLContextImpl.java:485)
at
jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:645)
at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:594)
at javax.media.opengl.awt.GLCanvas$8.run(GLCanvas.java:996) at
java.awt.event.InvocationEvent.dispatch(Unknown Source) at
java.awt.EventQueue.dispatchEventImpl(Unknown Source) at
java.awt.EventQueue.access$300(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source)
Please switch to JOGL 2.3.1. Then, replace "javax.media" by "com.jogamp" to avoid any compile error.
When you remove the AWT GLCanvas from its parent container, it loses its peer and its OpenGL context is destroyed. This is something that you can't avoid when using this kind of canvas. Switch to NEWT if this isn't the desired behavior.
The creation of another context might fail in some particular cases on some hardware. If you still get the same stack trace with the latest version of JOGL, please fill a bug report: http://jogamp.org/wiki/index.php/Jogl_FAQ#Bugreports_.26_Testing
Take the Example 13-3 "Implementing a Cell Factory" from
http://docs.oracle.com/javafx/2/ui_controls/tree-view.htm
and add the lines
box.addEventHandler(EventType.ROOT, new EventHandler<Event>() {
#Override
public void handle(Event event) {
System.out.println("event "+event);
}
});
in the start method then the following exceptions will be thrown when double clicking
an employee node:
java.lang.ClassCastException: javafx.scene.layout.VBox cannot be cast to javafx.scene.control.TreeView
at javafx.scene.control.TreeView$EditEvent.getSource(TreeView.java:988)
at javafx.scene.control.TreeView$EditEvent.getSource(TreeView.java:965)
at com.sun.javafx.event.EventHandlerManager.fixEventSource(EventHandlerManager.java:225)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:216)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:28)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Node.fireEvent(Node.java:6863)
at javafx.scene.control.TreeCell.startEdit(TreeCell.java:315)
at test.TreeViewSample$TextFieldTreeCellImpl.startEdit(TreeViewSample.java:100)
at javafx.scene.control.TreeCell.updateEditing(TreeCell.java:435)
at javafx.scene.control.TreeCell.access$500(TreeCell.java:67)
at javafx.scene.control.TreeCell$6.invalidated(TreeCell.java:151)
at javafx.beans.WeakInvalidationListener.invalidated(WeakInvalidationListener.java:80)
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:359)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)
at javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyObjectWrapper.java:195)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:161)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:130)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:163)
at javafx.scene.control.TreeView.setEditingItem(TreeView.java:573)
at javafx.scene.control.TreeView.edit(TreeView.java:771)
at com.sun.javafx.scene.control.behavior.TreeCellBehavior.simpleSelect(TreeCellBehavior.java:257)
at com.sun.javafx.scene.control.behavior.TreeCellBehavior.doSelect(TreeCellBehavior.java:213)
at com.sun.javafx.scene.control.behavior.TreeCellBehavior.mouseReleased(TreeCellBehavior.java:132)
at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:336)
at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:329)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:64)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3328)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3168)
at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3123)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1563)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2265)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:250)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:173)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:292)
at com.sun.glass.ui.View.handleMouseEvent(View.java:528)
at com.sun.glass.ui.View.notifyMouse(View.java:922)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
at java.lang.Thread.run(Unknown Source)
Is this a bug or did I something wrong?
Full example code (you will need to include the files "root.png" and "department.png" in the same directory):
package test;
import java.util.*;
import javafx.application.*;
import javafx.beans.property.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.stage.*;
import javafx.util.*;
public class TreeViewSample extends Application {
private final Node rootIcon =
new ImageView(new Image(getClass().getResourceAsStream("root.png")));
private final Image depIcon =
new Image(getClass().getResourceAsStream("department.png"));
List<Employee> employees = Arrays.<Employee>asList(
new Employee("Ethan Williams", "Sales Department"),
new Employee("Emma Jones", "Sales Department"),
new Employee("Michael Brown", "Sales Department"),
new Employee("Anna Black", "Sales Department"),
new Employee("Rodger York", "Sales Department"),
new Employee("Susan Collins", "Sales Department"),
new Employee("Mike Graham", "IT Support"),
new Employee("Judy Mayer", "IT Support"),
new Employee("Gregory Smith", "IT Support"),
new Employee("Jacob Smith", "Accounts Department"),
new Employee("Isabella Johnson", "Accounts Department"));
TreeItem<String> rootNode =
new TreeItem<String>("MyCompany Human Resources", rootIcon);
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) {
rootNode.setExpanded(true);
for (Employee employee : employees) {
TreeItem<String> empLeaf = new TreeItem<String>(employee.getName(), new ImageView(depIcon));
boolean found = false;
for (TreeItem<String> depNode : rootNode.getChildren()) {
if (depNode.getValue().contentEquals(employee.getDepartment())){
depNode.getChildren().add(empLeaf);
found = true;
break;
}
}
if (!found) {
TreeItem<String> depNode = new TreeItem<String>(
employee.getDepartment(),
new ImageView(depIcon)
);
rootNode.getChildren().add(depNode);
depNode.getChildren().add(empLeaf);
}
}
stage.setTitle("Tree View Sample");
VBox box = new VBox();
final Scene scene = new Scene(box, 400, 300);
scene.setFill(Color.LIGHTGRAY);
TreeView<String> treeView = new TreeView<String>(rootNode);
treeView.setEditable(true);
treeView.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
#Override
public TreeCell<String> call(TreeView<String> p) {
return new TextFieldTreeCellImpl();
}
});
box.getChildren().add(treeView);
stage.setScene(scene);
stage.show();
box.addEventHandler(EventType.ROOT, new EventHandler<Event>() {
#Override
public void handle(Event event) {
System.out.println("event "+event);
}
});
}
private final class TextFieldTreeCellImpl extends TreeCell<String> {
private TextField textField;
public TextFieldTreeCellImpl() {
}
#Override
public void startEdit() {
super.startEdit();
if (textField == null) {
createTextField();
}
setText(null);
setGraphic(textField);
textField.selectAll();
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(getTreeItem().getGraphic());
System.out.println(" item canceled "+getItem());
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(getTreeItem().getGraphic());
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
public static class Employee {
private final SimpleStringProperty name;
private final SimpleStringProperty department;
private Employee(String name, String department) {
this.name = new SimpleStringProperty(name);
this.department = new SimpleStringProperty(department);
}
public String getName() {
return name.get();
}
public void setName(String fName) {
name.set(fName);
}
public String getDepartment() {
return department.get();
}
public void setDepartment(String fName) {
department.set(fName);
}
}
}
Indeed there is a little problem with their code.
You can avoid this exception by removing these lines :
box.addEventHandler(EventType.ROOT, new EventHandler<Event>() {
#Override
public void handle(Event event) {
System.out.println("event "+event);
}
});
This is the source of the problem. The Vbox catches every event thrown (because you told it to do so with EventType.ROOT). And I suspect it to catch an event thrown by the TreeCell or the TreeView when you double click.
It would work better with this because it will only catch input events from the user:
box.addEventHandler(InputEvent.ANY , new EventHandler<InputEvent>()
Despite reading the tutorial here, I cant seem to understand how to make FEST work with my application.
I have a Swing application in a big class witht a main method, and a couple of SwingWorker classes. I want to test my application as if I'm running it via the main method. The tutorial only seemed to give instructions on how to test a single component.
Miniature version of my ApplicationWindow.class that contains the main method:
private JFrame frmArtisol;
private JButton btnBrowseDB;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ApplicationWindow window = new ApplicationWindow();
window.frmArtisol.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ApplicationWindow() {
initialize();
}
And my testclass throwing an error.
public class ApplicationWindowTest {
private FrameFixture window;
#Before
public void setup() throws InitializationError{
ApplicationWindow applicationWindow = new ApplicationWindow();
JFrame frame = applicationWindow.getFrmArtisol();
frame = GuiActionRunner.execute(new GuiQuery<JFrame>() {
#Override
protected JFrame executeInEDT() throws Throwable {
return new JFrame();
}
});
window = new FrameFixture(frame);
window.show();
}
#Test
public void test(){
window.button("btnBrowseDB").click();
}
#After
public void after(){
window.cleanUp();
}
}
The error thrown when running this test:
org.fest.swing.exception.ComponentLookupException: Unable to find component using matcher org.fest.swing.core.NameMatcher[name='btnBrowseDB', type=javax.swing.JButton, requireShowing=true].
Component hierarchy:
javax.swing.JFrame[name='frame0', title='', enabled=true, visible=true, showing=true]
javax.swing.JRootPane[]
javax.swing.JPanel[name='null.glassPane']
javax.swing.JLayeredPane[]
javax.swing.JPanel[name='null.contentPane']
at org.fest.swing.core.BasicComponentFinder.componentNotFound(BasicComponentFinder.java:271)
at org.fest.swing.core.BasicComponentFinder.find(BasicComponentFinder.java:260)
at org.fest.swing.core.BasicComponentFinder.find(BasicComponentFinder.java:254)
at org.fest.swing.core.BasicComponentFinder.findByName(BasicComponentFinder.java:191)
at org.fest.swing.fixture.ContainerFixture.findByName(ContainerFixture.java:527)
at org.fest.swing.fixture.ContainerFixture.button(ContainerFixture.java:124)
at ApplicationWindowTest.test(ApplicationWindowTest.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
It seems as if the runner doesn't find my component, and this leads me to believe that I have misunderstood how to test this kind of thing. Any help pointing me in the right direction is greatly appreciated.
You may have already solved this, but I just came across your question while looking for help with a related problem.
The problem is that your setup() method creates an ApplicationWindow but then overwrites the variable frame with a reference to a completely new and unrelated JFrame object. What you want to do is create the ApplicationWindow in the executeInEDT() method like this:
#Before
public void setup() throws InitializationError{
JFrame frame = GuiActionRunner.execute(new GuiQuery<JFrame>() {
#Override
protected JFrame executeInEDT() throws Throwable {
return new ApplicationWindow().getFrmArtisol();
}
});
window = new FrameFixture(frame);
window.show();
}