Setting an icon for a jFrame in Netbeans swing gui builder - swing

I've been trying to set up a window in Netbean's GUI builder, without success. I've tried accessing the JFrame, from my main class as:
public void run(){
JFrame frame = new JFrame("Title of Frame");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("org/icon.png"));
}
Which creates a new frame apart from my main window with my icon.png. I'd like to know if there is some way to gain access to the JFrame that contains the rest of my UI elements, and set that icon.
I've also tried
new SearchAppUI().setIconImage(null);
which doesn't do anything of note.
Setting the icon directly:
JFrame.setIconImage("org/icon.png");
gives me the error, non-static method setIconImage(java.awt.Image) cannot be referenced from a static context.
Is there any way to set the main JFrame's icon from either Netbean's swing desinger preview, or from my run() method?

The OP is a bit dated but just for the record, try this:
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("org/icon.png")));

NVM, I found a solution on: http://www.youtube.com/watch?v=o_35iro4b7M
Describing how to set the icon and title of a jFrame. Basically, it requires
the libraries
import javax.swing.JFrame;
import java.awt.image.BufferedImage;
import java.io.File;
import java.awt.Image;
import javax.imageio.ImageIO;
I pretty much wanted to stick with using Netbean's guibuilder for now, at least for prototyping.

First of all. It's worth to read How to Make Frames.
You can use the following example.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class FrameWithIcon extends JFrame {
public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
FrameWithIcon myFrame = new FrameWithIcon();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setTitle("Frame with Icon");
myFrame.setLayout(new BorderLayout());
myFrame.setIconImage(
loadImageIcon("org/icon.png").getImage());
Dimension size = new Dimension(250, 100);
JPanel panel = new JPanel();
panel.setPreferredSize(size);
myFrame.add(panel, BorderLayout.LINE_START);
myFrame.setVisible(true);
myFrame.pack();
}
});
} catch (InterruptedException ex) {
} catch (InvocationTargetException ex) {
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
private static ImageIcon loadImageIcon(String path) {
URL imgURL = FrameWithIcon.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}

Related

How can I use DJNativeSwing JWebBrowser as the browser for the jupyter notebook?

I am using chrriis.dj.nativeswing.swtimpl.components.JWebBrowser in my swing application to open web page of a jupyter-notebook. Now my problem is when I click New->Python 3 button JWebBrowser to new a file, it always return the 404 page.
New a notebook in DJNativeSwing JWebBrowser
DJNativeSwing JWebBrowser got the 404 page
I think maybe it did not execute the javascript api in jupyter-notebook, can anyone help me make the DJNativeSwing JWebBrowser work under jupyter notebook?
The code I used:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowserWindow;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserNavigationEvent;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserWindowFactory;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserWindowWillOpenEvent;
/**
* #author Christopher Deckers
*/
public class NavigationControl extends JPanel {
protected static final String LS = System.getProperty("line.separator");
public NavigationControl() {
super(new BorderLayout());
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
final JWebBrowser webBrowser = new JWebBrowser();
webBrowser.setBarsVisible(false);
webBrowser.setStatusBarVisible(true);
webBrowser.navigate("https://try.jupyter.org/");
tabbedPane.addTab("Controled Browser", webBrowser);
add(tabbedPane, BorderLayout.CENTER);
}
/* Standard main method to try that test as a standalone application. */
public static void main(String[] args) {
UIUtils.setPreferredLookAndFeel();
NativeInterface.open();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("DJ Native Swing Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new NavigationControl(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
NativeInterface.runEventPump();
}
}
Thanks Thomas K. I changed the engine of jwebbrowser to Xulrunner-24.0.en-US and the problem disappeared.

JavaFX walk widget tree

Is there a simple (uniform) way to recursively descend a JavaFX widget tree starting from a defined node (possibly from the Scene itself)?
The following code:
static class Visitor {
public void visit(Node node){
...
}
}
protected void walkWidgets(Node n, Visitor cb) {
if (n instanceof Parent) {
Parent p = (Parent) n;
for (Node c : p.getChildrenUnmodifiable()) {
walkWidgets(c, cb);
}
}
cb.visit(n);
}
... does not work because the "children" of some containers (e.g.: SplitPane, BorderPane, etc.) are not listed in their children Property.
To overcome this I should specialize the code to allow for all the quirks of all different widgets. This is particularly annoying when You start using widget libs beyond the "standard" provision.
Am I missing something? (I surely hope so!)
This seems to work fine: it gets all the child nodes in the BorderPane, SplitPane and TabPane.
import java.util.function.Consumer;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class WalkComponentTree extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
root.setTop(new Label("Title"));
SplitPane splitPane = new SplitPane();
root.setCenter(splitPane);
ListView<String> list = new ListView<>();
list.getItems().addAll("One", "Two", "Three");
TabPane tabPane = new TabPane();
Tab tab1 = new Tab();
tab1.setContent(new TextArea());
Tab tab2 = new Tab();
tab2.setContent(new Label("Tab 2"));
tabPane.getTabs().addAll(tab1, tab2);
splitPane.getItems().addAll(tabPane, list);
Button button = new Button("Walk tree");
button.setOnAction(event -> walkTree(root, node ->
System.out.println(node.getClass())));
root.setBottom(button);
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private void walkTree(Node node, Consumer<Node> visitor) {
visitor.accept(node);
if (node instanceof Parent) {
((Parent) node).getChildrenUnmodifiable()
.forEach(n -> walkTree(n, visitor));
}
}
public static void main(String[] args) {
launch(args);
}
}
Note you can also use node.lookupAll("*");, though this is less robust as it only works once css has been applied to the node.
In my opinion you are correct to say that there is no "standard" way to walk through the JavaFX scene graph.
One reason is, that Tab is not derived from Node, so you will not get a List of Tabs from Parent.getChildrenUnmodifiable(). Another reason is, that ScrollPane and TitledPane do not publish their content node in Parent.getChildrenUnmodifiable(). Some other Panes like Accordion, SplitPane and Toolbar also don't publish their children with Parent.getChildrenUnmodifiable(). So you need to handle this yourself.
For more Information please see:
Walking the JavaFX Scene Graph

Updating Layout of Panel after changing label icon

I have created a project that will download the thumbnails of the images from a ftp server and display it in a panel using JLabel.
The images are being displayed but the layout of the panel only works if i call the panel once more (i.e using a button on the frame) then the layout corrects itself automatically. What am i doing wrong? Here is the code
EDIT- Updated the code with sscce
1. sscce.java
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* #author Rohn
*/
public class Sscce implements Interface{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setVisible(true);
//frame.add(sci.);
Container c=frame.getContentPane();
JButton button=new JButton("Recall ShowCategoryImagesFunction");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
sci.ShowCategoryImagesFunction("\\Nature\\Black And White"); //for testing purpose only
// if button is pressed then we get right layout and image load
}
});
c.setLayout(new FlowLayout());
c.add(button);
c.add(sci.ShowCategoryImagesFunction("\\Nature\\Black And White")); // default path for image load for first time
// problem in correctly loading images and text with layout
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
2. ShowCategoryImages.java
package sscce;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPFile;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ShowCategoryImages{
//FTPClient client=null;
JPanel panel=new JPanel();
JLabel label=new JLabel();
FTPClient client=new FTPConnection().FTPConnection();
FTPFile[] list;
File thumbnails;
File[] files;
ImageIcon icon;
public JPanel ShowCategoryImagesFunction(String path){
// delete all the components on reload
if(panel.getComponents().length>0){
System.out.println(panel.getComponents().length);
panel.removeAll();
panel.revalidate();
panel.repaint();
}
//panel.setLayout(new GridLayout(0,4,2,2));
//panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));
panel.setLayout(new FlowLayout());
panel.revalidate();
panel.repaint();
panel.updateUI();
try{
//images in /wallpapers/nature/black and white/thumb
client.changeDirectory("\\Wallpapers"+path+"\\thumb"); //path of thumbnails
//temporary folder for holding images
thumbnails=new File("Thumbnails");
list=client.list();
if(thumbnails.exists()){
files = thumbnails.listFiles();
if(files!=null) { //some JVMs return null for empty dirs
for(File f: files) {
f.delete();
}
}
}
else
thumbnails.mkdir();
for(int i=0;i<list.length;i++){
System.out.println("running");
icon=new ImageIcon(thumbnails.getAbsolutePath()+"\\"+list[i].getName());
icon.getImage().flush();
client.download(client.currentDirectory()+"\\"+list[i].getName(), new java.io.File(thumbnails.getAbsolutePath()+"\\"+list[i].getName()));
label=new JLabel(list[i].getName());
label.setIcon(icon);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
panel.add(label);
panel.revalidate();
panel.repaint();
label.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
JLabel la=(JLabel)e.getSource();
System.out.println(la.getIcon());
}
});
}
//client.disconnect(true);
}catch(Exception e){
System.out.println(e.getMessage());
}
return panel;
}
}
3. FTPConnection.java
import it.sauronsoftware.ftp4j.FTPClient;
public class FTPConnection {
//ftp connection on local host
public static FTPClient FTPConnection(){
String ftphost="127.0.0.1";
String ftpuser="newuser";
String ftppassword="wampp";
int ftpport=21;
FTPClient client=new FTPClient();
try{
if(client.isConnected()==true){
client.disconnect(true);
};
client.connect(ftphost, ftpport);
client.login(ftpuser, ftppassword);
}
catch(Exception e){
System.out.println(e.getMessage());
}
return client;
}
}
not entirely sure what you mean with not layout, but your code is missing a revalidate/repaint after adding the labels:
// adding all labels
forEach (thumb....) {
JLabel label = new JLabel(thumb);
panel.add(label);
}
panel.revalidate();
panel.repaint();

TreeModelListener not responding to changes in TreeModel which it subscribes to

I'm having some bother understanding why I cannot get a TreeModelChanged listener to respond to changes in the model which it subscribes to.
I have managed to reproduce the problem in a small example.
The SysOut message does not print to the console whenever a new node is added to the tree.
I intend to replace the SysOut message with some commands to redraw the tree. At the moment I am using a SysOut message just to prove that the listener is not being fired.
Am I missing something fundamental?
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class TreeTest {
private JTree t;
private DefaultTreeModel m ;
public static void main(String[] args) {
new TreeTest();
}
public TreeTest() {
//Draw Frame & Panel - set dimensions
JFrame f = new JFrame();
f.setSize(new Dimension(800,600));
JPanel p = new JPanel();
p.setSize(new Dimension(800,600));
//Create a Tree Model. Give it a String at the root.
m = new DefaultTreeModel(new DefaultMutableTreeNode("Root"));
//Create a tree and add the Model to it
t = new JTree();
t.setModel(m);
//Try a Tree Model Listener
m.addTreeModelListener(new TreeModelListener() {
private void doSomething() {
//Should fire whenever a node is added to the model
System.out.println("Responding to TreeModelListener");
}
#Override
public void treeStructureChanged(TreeModelEvent e) {
doSomething();
}
#Override
public void treeNodesRemoved(TreeModelEvent e) {
doSomething();
}
#Override
public void treeNodesInserted(TreeModelEvent e) {
doSomething();
}
#Override
public void treeNodesChanged(TreeModelEvent e) {
doSomething();
}
});
//Add listener to a button which adds nodes to the tree when clicked
JButton addNode = new JButton("Add node");
addNode.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node");
DefaultMutableTreeNode root = (DefaultMutableTreeNode) m.getRoot();
root.add(newNode);
}
});
JScrollPane s = new JScrollPane(t);
p.add(s);
p.add(addNode);
p.setVisible(true);
f.add(p);
f.setVisible(true);
}
}
that's because the model doesn't know about the addition, it happens under its feet. Use the methods on DefaultTreeModel to do the insertion:
model.insertNodeInto(newNode, root, root.getChildCount())
Edit
a TreeNode is just a (more or less) dumb data structure. As you can see in the api, it's not an Observable, so there is no way for the model which uses that data structure to detect if anything changed on the node. To make it aware of the change, you have to do one of two things
use the node manipulation methods of the model
update the node and notify the model manually (calling nodesWereInserted)
The first is the preferable way (keeps control where it belongs), the second might be needed in more complex contexts (though I would strongly recommend to never do it, that's why SwingX DefaultTreeTableModel doesn't have them exposed :)

trouble executing actionlistener in swing applet embedded in html

Following is the applet code below:
import javax.swing.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.UnknownHostException;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ui extends JApplet implements ActionListener{
public static JPanel panel2;
private JTextField subnetField =null;
public static JPanel panel3;
public static Font fc;
public static String[] subn;
public static String searchnet;
boolean flag=false;
public void init()
{
String hostname = null;
String hostaddress=null;
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
hostaddress=addr.getHostAddress();
// Get hostname
hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
subn= hostaddress.split("\\.");
System.out.println(subn[2]);
searchnet=subn[2];
//WindowDestroyer listener=new WindowDestroyer();
//addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new GridLayout(3,0));
JPanel panel1 =new JPanel();
panel2 =new JPanel();
panel1.setBackground(Color.WHITE);
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
JLabel lb2 = new JLabel("You are at: "+hostname+" "+hostaddress+" ");
lb2.setFont(new Font("sans-serif",Font.BOLD,15));
lb2.setForeground(Color.RED);
JPanel panel1_1 =new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
panel1_1.setBackground(Color.WHITE);
panel1_1.add(lb2, c);
//lb2.setAlignmentX(Component.CENTER_ALIGNMENT);
//panel1_1.add(lb2, BorderLayout.EAST);
panel1_1.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.add(panel1_1);
panel3=new JPanel();
panel3.setLayout(new GridLayout(2,0));
panel3.setBackground(Color.WHITE);
panel1.add(panel3);
UIManager.put("Button.background", Color.white);
UIManager.put("Button.foreground", Color.red);
fc = new Font("sans-serif",Font.BOLD,15);
UIManager.put("Button.font", fc);
JButton searchButton= new JButton("Search");
//Border b = new SoftBevelBorder(BevelBorder.LOWERED) ;
//searchButton.setBorder(b);
searchButton.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.add(searchButton);
searchButton.addActionListener(this);
contentPane.add(panel1);
panel2.setBackground(Color.WHITE);
contentPane.add(panel2);
//contentPane.add(searchButton);
//JButton closeButton=new JButton("Close");
//contentPane.add(closeButton);
//closeButton.addActionListener(this);
contentPane.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand ().equals ("Close"))
{
System.exit(0);
}
if (e.getActionCommand ().equals ("Search"))
{
panel2.setVisible(false);
panel2.removeAll();
panel2.revalidate();
panel3.setVisible(false);
panel3.removeAll();
panel3.revalidate();
if(flag){
searchnet=subnetField.getText();
}
result(panel2);//puts panel 2&panel 3 in the ui
panel2.setVisible(true);
panel3.setVisible(true);
}
}
public boolean complete;
public JPanel call(){
return null;
}
public void result(JPanel pn){
.
.
.
}
}
}
private void addColumnName(JPanel pn) {
// TODO Auto-generated method stub
}
public void addDataToTable(JPanel p, String element, int type){
......
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (Exception e) {
// TODO: error handling
}
} else {
// TODO: error handling
}
}
public static void main(String[] args){
ui start=new ui();
start.setVisible(true);
JFrame f = new JFrame("Find Device");
ui applet=new ui();
applet.init();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,450);
f.setVisible(true);
}
}
then the html file looks like this:
<html>
<applet code=ui.class
archive="webapplet.jar"
width=800 height=450>
</applet>
</body>
</html>
when i run the program via eclipse as an applet it runs fine, but when i put it in the html file, the init() seems to show up but the actionlistener on the button never seems to work
Any help would be really appreciated. Thanks!!
ps: will be happy to share any additional details if required
Emm... you mean the code never works as
System.exit(0);
?
If you mean "Close" button inactivity so it shouldn't close Internet Browser ... so that's OK :)
And this one as
InetAddress addr = InetAddress.getLocalHost();
Hmm... As for applet, I guess you should use getCodeBase() instead
Good luck :)