How to create Jframe?

How to create a basic programme that shows JFrame?
Please guide me.

Similarly,
public class ThePanel extends JPanel implements <insert list of listeners here>
}There are any number of things wrong with having a frame/panel subclass defined this way.
1. Often coders with any number of disparate buttons make their
frame or panel listener to them all:
public class ThePanel extends JPanel implements ActionListenerThen the actionPerformed method is a laundry list of if/then/elseifs. Ugh.
That's the perfect situation for specific action objects listening to specific controls.
2. Exposing implementation details: the fact that the panel is listening
to list selection is not part of the API for the panel, it's an implementation
detail, yet that's not what this reads as:
public class ThePanel extends JPanel implements ListSelectionListenerWhat's to stop other code from doing the following?
unrelatedList.addListSelectionListener(thePanel); //woops, thePanel wasn't meant to listen to *that* list.It's surprising what cruft people won't tolerate in other areas of code are
happy to commit in Swing code.
Message was edited by:
DrLaszloJamf

Similar Messages

  • How to create a template like JFrame Form in netbeans?

    Hi! I'm working with netbeans 5.5.1 jdk 6 and i'm trying to make my own JFrame form template to avoid writing a lot of code.
    I look in the Template manager and add my template but when i add it to the template list it appears like ".java" extension, no matter if i choose the .FORM file. This bring me the problem that i can't use the netbeans GUI editor on this template and is my goal :S
    It may be a simple question but i haven't found anything to solve it,
    If anyone knows how to create and use the templeate as i need i would appreciate the help!
    Thanks a lot!

    I'm sure that someone at the NetBeans website mailing list knows how to do that. Do note that these are Java forums, not NB support.

  • How to create the digital clock in java swing application ?

    I want to create the running digital clock in my java swing application. Can someone throw some light on this how to do this ? Or If someone has done it then can someone pl. paste the code ?
    Thanks.

    hi prah_Rich,
    I have created a digital clock you can use. You will most likely have to change some things to use it in another app although that shouldn't be too hard. A least it can give you some ideas on how to create one of your own. There are three classes.One that creates the numbers. a gui class and frame class.
    cheers:)
    Hex45
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.geom.*;
    public class DigitalClock extends Panel{
              BasicStroke stroke = new BasicStroke(4,BasicStroke.CAP_ROUND,
                                               BasicStroke.JOIN_BEVEL);
              String hour1, hour2;
              String minute1, minute2;
              String second1, second2;
              String mill1, mill2, mill3;
              int hr1, hr2;
              int min1, min2;
              int sec1, sec2;
              int mll1, mll2,mll3;       
        public void update(Graphics g){
             paint(g);
         public void paint(Graphics g){
              Graphics2D g2D = (Graphics2D)g;
              DigitalNumber num = new DigitalNumber(10,10,20,Color.cyan,Color.black);     
              GregorianCalendar c = new GregorianCalendar();
              String hour = String.valueOf(c.get(Calendar.HOUR));
              String minute = String.valueOf(c.get(Calendar.MINUTE));
              String second = String.valueOf(c.get(Calendar.SECOND));
              String milliSecond = String.valueOf(c.get(Calendar.MILLISECOND));
              if(hour.length()==2){
                   hour1 = hour.substring(0,1);
                   hour2 = hour.substring(1,2);
              }else{
                   hour1 = "0";
                   hour2 = hour.substring(0,1);
              if(minute.length()==2){
                   minute1 = minute.substring(0,1);
                   minute2 = minute.substring(1,2);
              }else{
                   minute1 = "0";
                   minute2 = minute.substring(0,1);
              if(second.length()==2){
                   second1 = second.substring(0,1);
                   second2 = second.substring(1,2);
              }else{
                   second1 = "0";
                   second2 = second.substring(0,1);
              if(milliSecond.length()==3){
                   mill1 = milliSecond.substring(0,1);
                   mill2 = milliSecond.substring(1,2);
                   mill3 = milliSecond.substring(2,3);
              }else if(milliSecond.length()==2){
                   mill1 = "0";
                   mill2 = milliSecond.substring(0,1);
                   mill3 = milliSecond.substring(1,2);
              }else{
                   mill1 = "0";
                   mill2 = "0";
                   mill3 = milliSecond.substring(0,1);
              hr1  = Integer.parseInt(hour1);     
              hr2  = Integer.parseInt(hour2);
              min1 = Integer.parseInt(minute1);
              min2 = Integer.parseInt(minute2);
              sec1 = Integer.parseInt(second1);
              sec2 = Integer.parseInt(second2);
              mll1 = Integer.parseInt(mill1);
              mll2 = Integer.parseInt(mill2);
              g2D.setStroke(stroke);
              g2D.setPaint(Color.cyan);
              num.setSpacing(true,8);
              num.setSpacing(true,8);
              if(hr1==0&hr2==0){
                   num.drawNumber(1,g2D);
                   num.setLocation(40,10);
                   num.drawNumber(2,g2D);
              else{
                   if(!(hr1 == 0)){     
                        num.drawNumber(hr1,g2D);
                   num.setLocation(40,10);
                   num.drawNumber(hr2,g2D);
              num.setLocation(70,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(100,10);
              num.drawNumber(min1,g2D);
              num.setLocation(130,10);
              num.drawNumber(min2,g2D);
              num.setLocation(160,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(190,10);
              num.drawNumber(sec1,g2D);
              num.setLocation(220,10);
              num.drawNumber(sec2,g2D);
              /*num.setLocation(250,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(280,10);
              num.drawNumber(mll1,g2D);
              num.setLocation(310,10);
              num.drawNumber(mll2,g2D);
              g2D.setPaint(Color.cyan);
              if((c.get(Calendar.AM_PM))==Calendar.AM){               
                   g2D.drawString("AM",260,20);
              }else{
                   g2D.drawString("PM",260,20);
         String dayOfweek = "";     
         switch(c.get(Calendar.DAY_OF_WEEK)){
              case(Calendar.SUNDAY):
                   dayOfweek = "Sunday, ";
                   break;
              case(Calendar.MONDAY):
                   dayOfweek = "Monday, ";
                   break;
              case(Calendar.TUESDAY):
                   dayOfweek = "Tuesday, ";
                   break;
              case(Calendar.WEDNESDAY):
                   dayOfweek = "Wednesday, ";
                   break;
              case(Calendar.THURSDAY):
                   dayOfweek = "Thursday, ";
                   break;
              case(Calendar.FRIDAY):
                   dayOfweek = "Friday, ";
                   break;
              case(Calendar.SATURDAY):
                   dayOfweek = "Saturday, ";
                   break;
         String month = "";     
         switch(c.get(Calendar.MONTH)){
              case(Calendar.JANUARY):
                   month = "January ";
                   break;
              case(Calendar.FEBRUARY):
                   month = "February ";
                   break;
              case(Calendar.MARCH):
                   month = "March ";
                   break;
              case(Calendar.APRIL):
                   month = "April ";
                   break;
              case(Calendar.MAY):
                   month = "May ";
                   break;
              case(Calendar.JUNE):
                   month = "June ";
                   break;
              case(Calendar.JULY):
                   month = "July ";
                   break;
              case(Calendar.AUGUST):
                   month = "August ";
                   break;
              case(Calendar.SEPTEMBER):
                   month = "September ";
                   break;
              case(Calendar.OCTOBER):
                   month = "October ";
                   break;
              case(Calendar.NOVEMBER):
                   month = "November ";
                   break;
              case(Calendar.DECEMBER):
                   month = "December ";
                   break;
         int day = c.get(Calendar.DAY_OF_MONTH);
         int year = c.get(Calendar.YEAR);
         Font font = new Font("serif",Font.PLAIN,24);
         g2D.setFont(font);
         g2D.drawString(dayOfweek+month+day+", "+year,10,80);
         public static void main(String args[]){
              AppFrame aframe = new AppFrame("Digital Clock");
              Container cpane = aframe.getContentPane();
              final DigitalClock dc = new DigitalClock();
              dc.setBackground(Color.black);
              cpane.add(dc,BorderLayout.CENTER);
              aframe.setSize(310,120);
              aframe.setVisible(true);
              class Task extends TimerTask {
                 public void run() {
                      dc.repaint();
              java.util.Timer timer = new java.util.Timer();
             timer.schedule(new Task(),0L,250L);
    class DigitalNumber {
         private float x=0;
         private float y=0;
         private float size=5;
         private int number;
         private Shape s;
         private float space = 0;
         public static final int DOTS = 10;
         private Color on,off;
         DigitalNumber(){          
              this(0f,0f,5f,Color.cyan,Color.black);          
         DigitalNumber(float x,float y, float size,Color on,Color off){
              this.x = x;
              this.y = y;
              this.size = size;
              this.on = on;
              this.off = off;
         public void drawNumber(int number,Graphics2D g){
              int flag = 0;
              switch(number){
                   case(0):          
                        flag = 125;
                        break;
                   case(1):
                        flag = 96;
                        break;
                   case(2):
                        flag = 55;
                        break;
                   case(3):
                        flag = 103;
                        break;
                   case(4):
                        flag = 106;
                        break;
                   case(5):
                        flag = 79;
                        break;
                   case(6):
                        flag = 94;
                        break;
                   case(7):
                        flag = 97;
                        break;
                   case(8):
                        flag = 127;
                        break;
                   case(9):
                        flag = 107;
                        break;
                   case(DOTS):
                        GeneralPath path = new GeneralPath();
                        path.moveTo(x+(size/2),y+(size/2)-1);
                        path.lineTo(x+(size/2),y+(size/2)+1);
                        path.moveTo(x+(size/2),y+(size/2)+size-1);
                        path.lineTo(x+(size/2),y+(size/2)+size+1);
                        g.setPaint(on);
                        g.draw(path);     
                        return;
              //Top          
              if((flag & 1) == 1){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Top = new GeneralPath();
              Top.moveTo(x + space, y);
              Top.lineTo(x + size - space, y);
              g.draw(Top);
              //Middle
              if((flag & 2) == 2){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Middle = new GeneralPath();
              Middle.moveTo(x + space, y + size); 
              Middle.lineTo(x + size - space,y + size);     
              g.draw(Middle);
              //Bottom
              if((flag & 4) == 4){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Bottom = new GeneralPath();
              Bottom.moveTo(x + space, y + (size * 2));  
              Bottom.lineTo(x + size - space, y + (size * 2));
              g.draw(Bottom);
              //TopLeft
              if((flag & 8) == 8){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath TopLeft = new GeneralPath();     
              TopLeft.moveTo(x, y + space);
              TopLeft.lineTo(x, y + size - space);          
              g.draw(TopLeft);
              //BottomLeft
              if((flag & 16) == 16){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath BottomLeft = new GeneralPath();     
              BottomLeft.moveTo(x, y + size + space);
              BottomLeft.lineTo(x, y + (size * 2) - space);
              g.draw(BottomLeft);
              //TopRight
              if((flag & 32) == 32){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath TopRight = new GeneralPath();     
              TopRight.moveTo(x + size, y + space);
              TopRight.lineTo(x + size, y + size - space);
              g.draw(TopRight);
              //BottomRight
              if((flag & 64) == 64){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath BottomRight = new GeneralPath();     
              BottomRight.moveTo(x + size, y + size + space);
              BottomRight.lineTo(x + size, y + (size * 2) - space);
              g.draw(BottomRight);
         public void setSpacing(boolean spacingOn){
              if(spacingOn == false){
                   space = 0;
              else{
                   this.setSpacing(spacingOn,5f);
         public void setSpacing(boolean spacingOn,float gap){
              if(gap<2){
                   gap = 2;
              if(spacingOn == true){
                   space = size/gap;
         public void setLocation(float x,float y){
              this.x = x;
              this.y = y;
         public void setSize(float size){
              this.size = size;
    class AppFrame extends JFrame{
         AppFrame(){
              this("Demo Frame");
         AppFrame(String title){
              super(title);
              setSize(500,500);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • How to create .JAR file in JSE 8?

    I don't know how to create a .JAR file from my project. I found a .JAR file in .../dist under my project folder, but I could not run it.

    This Swing app has 2 class files, requires Swing Library to be imported (of course), and requires no other files. It seems like the program does not import Swing Lib. so that it can display the JFrame inside.
    1. I have JRE installed separately so I can run Jar files directly by double-clicking. I also tried to run within command prompt, and had the same result. No error or exception warning found.
    2. As I said, the program requires no other files.
    3. I repeat that it works fine within JSE as well as JBuilder. the Jar created by JBuilder (same code) works fine, too.
    4. This Jar file is the only one Jar that I found in my project folder, and has the same name with the project. (But anyway, there's no folder contains 2 files with the same name, so this verification is not necessary).

  • How to create a pie diagram and display it in html code

    hii frds,
    happy 2 meet u all.
    I want to know how to create a pie diagram that should not be devleloped by using applet, and use it in the html code to display a pie diagram in browser.
    ex code:
    package temp;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    public class Dummy1 extends Panel {
    BufferedImage image;
         int a1,a2,l,t,w,h;
    public Dummy1()
              try
    a1=90;
              a2=210;
              l=10;
              t=10;
              w=200;
              h=200;
    } catch (Exception ie) { System.out.println("Error:"+ie.getMessage());  }
    public void paint(Graphics g) {
    // g.drawImage( image, 0, 0, null);
    g.setColor(Color.green);
              g.fillArc(l,t,w,h,0,a1);
    g.setColor(Color.red);
              g.fillArc(l,t,w,h,a1,(a2-a1));
         g.setColor(Color.blue);
              g.fillArc(l,t,w,h,a2,(360-a2));
              System.out.println("in paint");
              image=(Image)g.getGraphics();
    public JFrame getMyFrame()
    JFrame frame=null;
              try
    frame = new JFrame("Display image");
    Panel panel = new Dummy1();
    frame.getContentPane().add(panel);
    frame.setSize(500, 500);
    // frame.setVisible(true);
    // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              }catch(Exception e) { e.printStackTrace(); }
              return frame;
    static public void main(String args[]) throws
    Exception {
    JFrame frame = new JFrame("Display image");
    Panel panel = new Dummy1();
    frame.getContentPane().add(panel);
    frame.setSize(500, 500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    - > with out using <applet> in html can't we display the awt grahics in browser.
    plz clarify my doubts.
    thank you.
    regards
    moons..

    If you are using MSSQL SERVER then try creating a stored procedure like this
    create proc Name
    select * from Table
    by executing this in sql query analyzer will create a stored procedure that returns all the data from Table
    here is the syntax to create SP
    Syntax
    CREATE PROC [ EDURE ] procedure_name [ ; number ]
        [ { @parameter data_type }
            [ VARYING ] [ = default ] [ OUTPUT ]
        ] [ ,...n ]
    [ WITH
        { RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ]
    [ FOR REPLICATION ]
    AS sql_statement [ ...n ]
    Now Create new report and create new connection to your database and select stored procedure and add it to the report that shows all the columns and you can place the required fields in the report and refresh the report.
    Regards,
    Raghavendra
    Edited by: Raghavendra Gadhamsetty on Jun 11, 2009 1:45 AM

  • How to make JFrame become the topmost window?

    I have server that is supposed to show a TOPMOST JFrame window each time it gets a "Show Window" command from client. I use JFrame to create and show the window in the server code:               
    JFrame mainWin = new JFrame();
    mainWin.setResizable( false );
    Container mainContainer = mainWin.getContentPane();
    mainContainer.setLayout( null );
    // add components to mainContainer
    mainWin.setVisible( true );
    mainWin.show();
    mainWin.toFront();
    If I run the server under windows platform, the first created JFrame window is always hiding behind under other application windows. However, the JFrame windows other than the 1st one are always at top.
    The BAD thing is, if I run the server under Macintosh platform, the JFrame windows are always hiding behind the other application windows.
    Does anyone know how to fix the problem? i.e., making the JFrame window appear on top of other windows under any platforms?
    Thanks.
    ZZ
    p.s. I am using JDK version is 1.3.0.

    there is some weirdness with java I've noticed under windows during development. When you start the app from a console window or script, if you change focus to another window before the first java window shows up, it will show up behind the window you changed focus to. If you leave it alone until the window shows, it will be on top. A work around is after you call show(), call toFront().

  • How to create a window with its own window border other than the local system window border?

    How to create a window with its own window border other than the local system window border?
    For example, a border: a black line with a width 1 and then a transparent line with a width 5. Further inner, it is the content pane.
    In JavaSE, there seems to have the paintComponent() method for the JFrame to realize the effect.

    Not sure why your code is doing that. I usually use an ObjectProperty<Point2D> to hold the initial coordinates of the mouse press, and set it to null on a mouse release. That seems to avoid the dragging being confused by mouse interaction with other nodes.
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.collections.FXCollections;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.Point2D;
    import javafx.geometry.Pos;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.ChoiceBox;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.AnchorPane;
    import javafx.scene.layout.StackPane;
    import javafx.scene.layout.VBox;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    import javafx.stage.StageStyle;
    import javafx.stage.Window;
    public class CustomBorderExample extends Application {
      @Override
      public void start(Stage primaryStage) {
      AnchorPane root = new AnchorPane();
      root.setStyle("-fx-border-color: black; -fx-border-width: 1px; ");
      enableDragging(root);
      StackPane mainContainer = new StackPane();
        AnchorPane.setTopAnchor(mainContainer, 5.0);
        AnchorPane.setLeftAnchor(mainContainer, 5.0);
        AnchorPane.setRightAnchor(mainContainer, 5.0);
        AnchorPane.setBottomAnchor(mainContainer, 5.0);
      mainContainer.setStyle("-fx-background-color: aliceblue;");
      root.getChildren().add(mainContainer);
      primaryStage.initStyle(StageStyle.TRANSPARENT);
      final ChoiceBox<String> choiceBox = new ChoiceBox<>(FXCollections.observableArrayList("Item 1", "Item 2", "Item 3"));
      final Button closeButton = new Button("Close");
      VBox vbox = new VBox(10);
      vbox.setAlignment(Pos.CENTER);
      vbox.getChildren().addAll(choiceBox, closeButton);
      mainContainer.getChildren().add(vbox);
        closeButton.setOnAction(new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            Platform.exit();
      primaryStage.setScene(new Scene(root,  300, 200, Color.TRANSPARENT));
      primaryStage.show();
      private void enableDragging(final Node n) {
       final ObjectProperty<Point2D> mouseAnchor = new SimpleObjectProperty<>(null);
       n.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent event) {
            mouseAnchor.set(new Point2D(event.getX(), event.getY()));
       n.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent event) {
            mouseAnchor.set(null);
       n.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent event) {
            Point2D anchor = mouseAnchor.get();
            Scene scene = n.getScene();
            Window window = null ;
            if (scene != null) {
              window = scene.getWindow();
            if (anchor != null && window != null) {
              double deltaX = event.getX()-anchor.getX();
              double deltaY = event.getY()-anchor.getY();
              window.setX(window.getX()+deltaX);
              window.setY(window.getY()+deltaY);
      public static void main(String[] args) {
      launch(args);

  • How to create a frame in a applet?

    Dear All,
    How to create a frame in a applet?
    Thanks in advance
    Kityy

    You can't add a Frame/JFrame to an Applet/JApplet.
    An Applet/JApplet has its origins in the class Panel/JPanel.
    So, if you make your Applet to an application you
    can easily do that by putting your Applet "above" a Frame.
    Maybe you can archieve your goals with some Panels?!

  • How to Create XML Schema From JTree ?

    Please help me... Thank you.
    This is Code
    Tree.java ----- Run This File
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    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.tree.DefaultMutableTreeNode;
    public class Tree extends JPanel implements ActionListener {
        private int newNodeSuffix = 1;
        private static String ADD_COMMAND = "add";
        private static String REMOVE_COMMAND = "remove";
        private static String CLEAR_COMMAND = "clear";
        private static String OK_COMMAND = "ok";
        private DynamicTree treePanel;
        public Tree() {
            super(new BorderLayout());
            //Create the components.
            treePanel = new DynamicTree();
            //populateTree(treePanel);
            JButton addButton = new JButton("Add");
            addButton.setActionCommand(ADD_COMMAND);
            addButton.addActionListener(this);
            JButton removeButton = new JButton("Remove");
            removeButton.setActionCommand(REMOVE_COMMAND);
            removeButton.addActionListener(this);
            JButton clearButton = new JButton("Clear");
            clearButton.setActionCommand(CLEAR_COMMAND);
            clearButton.addActionListener(this);
            JButton okButton = new JButton("OK");
            okButton.setActionCommand(OK_COMMAND);
            okButton.addActionListener(this);
            //Lay everything out.
            treePanel.setPreferredSize(new Dimension(300, 150));
            add(treePanel, BorderLayout.CENTER);
            JPanel panel = new JPanel(new GridLayout(0,1));
            panel.add(addButton);
            panel.add(removeButton);
            panel.add(clearButton);
            panel.add(okButton);
            add(panel, BorderLayout.LINE_END);
        /*public void populateTree(DynamicTree treePanel) {
            String p1Name = new String("Parent 1");
            //String p2Name = new String("Parent 2");
            String c1Name = new String("Child 1");
            //String c2Name = new String("Child 2");
            DefaultMutableTreeNode p1;
            p1 = treePanel.addObject(null, p1Name);
            //p2 = treePanel.addObject(null, p2Name);
            treePanel.addObject(p1, c1Name);
            //treePanel.addObject(p1, c2Name);
            //treePanel.addObject(p2, c1Name);
            //treePanel.addObject(p2, c2Name);
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if (ADD_COMMAND.equals(command)) {
                //Add button clicked.
                treePanel.addObject("New Node " + newNodeSuffix++);
            } else if (REMOVE_COMMAND.equals(command)) {
                //Remove button clicked.
                treePanel.removeCurrentNode();
            } else if (CLEAR_COMMAND.equals(command)) {
                //Clear button clicked.
                treePanel.clear();
            } else if (OK_COMMAND.equals(command)) {
                 //Ok button clicked.
                 treePanel.ok();
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("Craete XML Tree");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            Tree newContentPane = new Tree();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        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() {
                public void run() {
                    createAndShowGUI();
    }DynamicTree.java
    import javax.swing.JOptionPane;
    import java.awt.GridLayout;
    import java.awt.Toolkit;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    public class DynamicTree extends JPanel {
        protected DefaultMutableTreeNode rootNode;
        protected DefaultTreeModel treeModel;
        protected JTree tree;
        private Toolkit toolkit = Toolkit.getDefaultToolkit();
        public DynamicTree() {
            super(new GridLayout(1,0));
            rootNode = new DefaultMutableTreeNode("Root Node");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setEditable(true);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
            JScrollPane scrollPane = new JScrollPane(tree);
            add(scrollPane);
        /** Remove all nodes except the root node. */
        public void clear() {
            rootNode.removeAllChildren();
            treeModel.reload();
        public void ok() {
             int n = JOptionPane.showConfirmDialog(null, "Do you want to create XML Schema?", "", JOptionPane.YES_NO_OPTION);
        /** Remove the currently selected node. */
        public void removeCurrentNode() {
            TreePath currentSelection = tree.getSelectionPath();
            if (currentSelection != null) {
                DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                             (currentSelection.getLastPathComponent());
                MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
                if (parent != null) {
                    treeModel.removeNodeFromParent(currentNode);
                    return;
            // Either there was no selection, or the root was selected.
            toolkit.beep();
        /** Add child to the currently selected node. */
        public DefaultMutableTreeNode addObject(Object child) {
            DefaultMutableTreeNode parentNode = null;
            TreePath parentPath = tree.getSelectionPath();
            if (parentPath == null) {
                parentNode = rootNode;
            } else {
                parentNode = (DefaultMutableTreeNode)
                             (parentPath.getLastPathComponent());
            return addObject(parentNode, child, true);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child) {
            return addObject(parent, child, false);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child,
                                                boolean shouldBeVisible) {
            DefaultMutableTreeNode childNode =
                    new DefaultMutableTreeNode(child);
            if (parent == null) {
                parent = rootNode;
            treeModel.insertNodeInto(childNode, parent,
                                     parent.getChildCount());
            //Make sure the user can see the lovely new node.
            if (shouldBeVisible) {
                tree.scrollPathToVisible(new TreePath(childNode.getPath()));
            return childNode;
        class MyTreeModelListener implements TreeModelListener {
            public void treeNodesChanged(TreeModelEvent e) {
                DefaultMutableTreeNode node;
                node = (DefaultMutableTreeNode)
                         (e.getTreePath().getLastPathComponent());
                 * If the event lists children, then the changed
                 * node is the child of the node we've already
                 * gotten.  Otherwise, the changed node and the
                 * specified node are the same.
                try {
                    int index = e.getChildIndices()[0];
                    node = (DefaultMutableTreeNode)
                           (node.getChildAt(index));
                } catch (NullPointerException exc) {}
                System.out.println("The user has finished editing the node.");
                System.out.println("New value: " + node.getUserObject());
            public void treeNodesInserted(TreeModelEvent e) {
            public void treeNodesRemoved(TreeModelEvent e) {
            public void treeStructureChanged(TreeModelEvent e) {
    }

    XML shema is basically an XML file. So u need to know how to create an XML,
    provided u know how the shema file should be.
    Creating an XML :
    http://forum.java.sun.com/thread.jspa?threadID=5181031&messageID=9705786#9705786

  • How to create a dynamic table were the JTable columns keep varying

    How to create a dynamic table were the JTable columns keep varying based on the input to the jtable

    Oooh, I lied. DefaultTableModel has an API for adding and
    removing columns. I didn't know that. You should have read
    the API.
    As for preferring to extend AbstractTableModel rather than
    DefaultTableModel, I think it's more correct. DefaultTableModel
    is a simple implementation of Abstract for basic cases. It isn't
    intended to be extended. I figure most people extending
    DefaultTableModel are also extending JFrame, JPanel, and Thread
    instead of encapsulating the first two and implementing
    Runnable for the third.

  • How to create rollover text on an image

    I'm a non-coder I'm using Dreamweaver CS4 to create a personal website.  I know next to nothing about CSS, but I think I understand how to create a style and apply it to elements. 
    My website has several image galleries, and what I'd like to be able to do is create a rollover text box of some kind that floats up in a fixed position when mouseover on an image.  What I'm looking to do is basically what this website does on their top header image:
    AstroBin | AstroBin
    I've experimented some with spry tooltips but I want the text box to be in the same position and not wherever the mouse is pointing at the time.  I have done hours of searching and I cannot come up with a solution to this (at least not one that I understand) and it's quite possible that I don't even know the terms to search for. 
    What tools or terms am I describing here?  What should I be searching for? 
    Can anyone point me to a good tutorial to do what I'm asking?  Please give me the dummy version!
    Thanks in advance.

    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class fireleaf extends JFrame {
      public fireleaf() {
        JLabel label = new ImageLabel();
        JPanel panel = new JPanel();
        panel.setBackground(Color.pink);
        panel.add(label);
        getContentPane().add(panel, "Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,200);
        setLocation(300,200);
        setVisible(true);
      private class ImageLabel extends JLabel {
      // image from:
      // http://java.sun.com/docs/books/tutorial/uiswing/painting/imageSequence.html
        public ImageLabel() {
          Toolkit toolkit = Toolkit.getDefaultToolkit();
          Image image = toolkit.getImage("images\\T4.gif");
          ImageIcon icon = new ImageIcon(image);
          setIcon(icon);
          setOpaque(true);
        public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D)g;
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                              RenderingHints.VALUE_ANTIALIAS_ON);
          g2.drawString("hello", 10, 10);
      public static void main(String[] args) {
        new fireleaf();
    }

  • How to create tab indexing for jtextBox

    Dear Forum
    i am user of jDeveloper.
    And working on JClient/Swing application.
    In "Jframe.java" i add various cotrols such as jTextbox,jCombobox ,jlabel etc.
    So how to create tab indexing for these controls.
    Girdher

    Dear Forum
    i am user of jDeveloper.
    And working on JClient/Swing application.
    In "Jframe.java" i add various cotrols such as jTextbox,jCombobox ,jlabel etc.
    So how to create tab indexing for these controls.
    Girdher

  • How to create this type of Form?

    Hello ,
    I'm new to java so I would like a hint from experts on how to create such a form :
    A form that displays Customer's Codes and their name from Oracle database , so that they appear in the form as a list of 2 columns , what kind of compnents I should use to display this kind of data ? JTextField ? I dont think so .... . And also I would like to highlight each other line so that the list looks good , then at the top of the list I want a filter so that the data is filtered each time I enter a character . The last thing is how to make the data displayed have the ability to be dragged to another form in the application so that it fills the corresponding fields relative to the data dragged ?
    Too much ha? . Please just provide hints/ideas about each point as I know it can be time consuming to give details about all this.
    Thanks in advance...

    Thank you , I tried with this code to achieve what I wanted but I get no result .
    Can you please tell me whats wrong with this code ?
    package desktopapplication1;
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    public class MainOMSWindow extends JPanel{
        public MainOMSWindow ()
            super(new GridLayout(1,0));
    JTable customerListTable = new JTable();
    customerListTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
    customerListTable.setFillsViewportHeight(true);//to make the table uses the entire height of the container
        JScrollPane pane = new JScrollPane(customerListTable);
        add(pane);
        populateTable(customerListTable);
        private static Connection getConnection()
        Connection con = null;
         try
            String driverName = "oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName);   //registering JDBC Driver
            String serverName = "localhost";
            String portNumber = "1521";
            String sid = "mydb";
            //jdbc:oracle:thin:@localhost:1521:ahmaddb
            String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
            String user = "fundinfo";
            String pw = "tadapps";
            con = DriverManager.getConnection(url, user, pw);
         catch (ClassNotFoundException e) {
                                        System.out.println(e.getMessage());
                                        System.out.println(e.getStackTrace());
                                        System.out.println(e.getCause());
                                        System.out.println(e.getException());
                                        System.exit(0);
         catch (SQLException e) {
                                  System.out.println(e.getMessage());
                                  System.exit(0);
        return con;
        private static ResultSet useConnAndGetData()
            Connection con = getConnection();
        try
             Statement stmt = con.createStatement();
             String select = "select title,year,price from movie order by year";
             ResultSet rows = stmt.executeQuery(select);
             return rows;
        catch(SQLException e) {
                 System.out.println(e.getMessage());
            return null;
        private static void populateTable(JTable table)
            try{
        ResultSet rs = useConnAndGetData();
        while(rs.next())
    public void setValueAt(object value, int row, int column)
    •Value: The new value to be placed in the cell
    •row: The row in the JTable to be changed
    •column: The column in the JTable to be changed
    * rows and columns start at the number "0", not "1".
    * Notice that the first column in a result set is column "1".
         int row = 0;
         table.setValueAt(rs.getString("title"),row,0);
         table.setValueAt(rs.getInt("year"),row,1);
         table.setValueAt(rs.getDouble("price"),row,2);
         row++;
            catch(SQLException e)
             System.out.println(e.getMessage());
            private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("OMS");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            MainOMSWindow newContentPane = new MainOMSWindow();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main (String [] args){
        createAndShowGUI();
    }The programe throws this :
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
            at java.util.Vector.elementAt(Vector.java:427)
            at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
            at javax.swing.JTable.convertColumnIndexToModel(JTable.java:2553)
            at javax.swing.JTable.setValueAt(JTable.java:2719)
            at desktopapplication1.MainOMSWindow.populateTable(MainOMSWindow.java:99)
            at desktopapplication1.MainOMSWindow.<init>(MainOMSWindow.java:24)
            at desktopapplication1.MainOMSWindow.createAndShowGUI(MainOMSWindow.java:119)
            at desktopapplication1.MainOMSWindow.main(MainOMSWindow.java:130)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 1 second)

  • How to create menu in game?

    Hello,
    I am a newbie in java. I have to create a game in a window. My program should show menu inside the window when it starts (new game, options, etc). After choosing new game menu should disappeared and there should appear a game. I don't know how to do it. I know how to create window or buttons but I don't know what should I do to get effect as I described above.
    I want to have a game which looks like [http://www.java.com/en/games/desktop/astrocrusher.jsp ] or [http://www.crystalsquid.com/games/mt/monkey_play.php] but it can't be an applet. I hope it is clear what I need.
    Could you help me?

    a quick throw-together with a terrible amount of redundancy
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class FunWithLayouts2
        private CardLayout cardlayout = new CardLayout();
        private JPanel mainPanel = new JPanel(cardlayout);
        private MenuPanel menuPanel = new MenuPanel(cardlayout, mainPanel);
        private OptionsPanel optionsPanel = new OptionsPanel(cardlayout, mainPanel);
        private GamePanel gamePanel = new GamePanel(cardlayout, mainPanel);
        public FunWithLayouts2()
            mainPanel.add(menuPanel, menuPanel.getName());
            mainPanel.add(optionsPanel, optionsPanel.getName());
            mainPanel.add(gamePanel, gamePanel.getName());
        public JPanel getMainPanel()
            return mainPanel;
        private static void createAndShowGUI()
            JFrame frame = new JFrame("FunWithLayouts2 Application");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new FunWithLayouts2().getMainPanel());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    class MenuPanel extends JPanel
        private CardLayout cardlayout;
        private JPanel mainPanel;
        public MenuPanel(CardLayout cardlayout, JPanel mainPanel)
            setName("MenuPanel");
            setLayout(new BorderLayout());
            JPanel labelPanel = new JPanel();
            JLabel nameLbl = new JLabel(getName());
            labelPanel.add(nameLbl);
            add(labelPanel, BorderLayout.NORTH);
            JPanel btnPanel = new JPanel();
            JButton optionBtn = new JButton("Options");
            optionBtn.addActionListener(new BtnListener("OptionsPanel"));
            btnPanel.add(optionBtn);
            JButton gameBtn = new JButton("Game");
            gameBtn.addActionListener(new BtnListener("GamePanel"));
            btnPanel.add(gameBtn);
            add(btnPanel, BorderLayout.SOUTH);
            this.cardlayout = cardlayout;
            this.mainPanel = mainPanel;
        private class BtnListener implements ActionListener
            String panelStr = "";
            public BtnListener(String ps)
                panelStr = ps;
            public void actionPerformed(ActionEvent e)
                cardlayout.show(mainPanel, panelStr);
    class OptionsPanel extends JPanel
        private CardLayout cardlayout;
        private JPanel mainPanel;
        public OptionsPanel(CardLayout cardlayout, JPanel mainPanel)
            setName("OptionsPanel");
            setLayout(new BorderLayout());
            JPanel labelPanel = new JPanel();
            JLabel nameLbl = new JLabel(getName());
            labelPanel.add(nameLbl);
            add(labelPanel, BorderLayout.NORTH);
            JPanel btnPanel = new JPanel();
            JButton menuBtn = new JButton("Menu");
            menuBtn.addActionListener(new BtnListener("MenuPanel"));
            btnPanel.add(menuBtn);
            JButton gameBtn = new JButton("Game");
            gameBtn.addActionListener(new BtnListener("GamePanel"));
            btnPanel.add(gameBtn);
            add(btnPanel, BorderLayout.SOUTH);
            this.cardlayout = cardlayout;
            this.mainPanel = mainPanel;
        private class BtnListener implements ActionListener
            String panelStr = "";
            public BtnListener(String ps)
                panelStr = ps;
            public void actionPerformed(ActionEvent e)
                cardlayout.show(mainPanel, panelStr);
    class GamePanel extends JPanel
        private CardLayout cardlayout;
        private JPanel mainPanel;
        public GamePanel(CardLayout cardlayout, JPanel mainPanel)
            setName("GamePanel");
            setLayout(new BorderLayout());
            JPanel labelPanel = new JPanel();
            JLabel nameLbl = new JLabel(getName());
            labelPanel.add(nameLbl);
            add(labelPanel, BorderLayout.NORTH);
            JPanel btnPanel = new JPanel();
            JButton optionBtn = new JButton("Options");
            optionBtn.addActionListener(new BtnListener("OptionsPanel"));
            btnPanel.add(optionBtn);
            JButton menuBtn = new JButton("Menu");
            menuBtn.addActionListener(new BtnListener("MenuPanel"));
            btnPanel.add(menuBtn);
            add(btnPanel, BorderLayout.SOUTH);
            this.cardlayout = cardlayout;
            this.mainPanel = mainPanel;
        private class BtnListener implements ActionListener
            String panelStr = "";
            public BtnListener(String ps)
                panelStr = ps;
            public void actionPerformed(ActionEvent e)
                cardlayout.show(mainPanel, panelStr);
    }

  • [Help] Learn How To Create InputDialog

    I still learn how to create a component.
    I want to create a simple input dialog which modeled after JOptionPane.showInputDialog, but i can't get the value, it's always show null. Anybody know where i doing wrong?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class kotakPesan extends JFrame implements ActionListener {
         String jdlPesan;
         String isiPesan;
         JPanel p = new JPanel();
         JButton bOk = new JButton("Ok");
         JTextField tIsi = new JTextField();
         JLabel lIsi = new JLabel();
         String A;
         public String inputPesan (String Judul, String Isi) {
              this.jdlPesan = Judul;
              this.isiPesan = Isi;
              tampilInputPesan();
              return A;          
         public void tampilInputPesan () {
              setTitle(jdlPesan);
              lIsi.setText(isiPesan);
              p.setLayout(new GridLayout(3, 1));
              p.add(lIsi);
              p.add(tIsi);
              p.add(bOk);
              getContentPane().add(p);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
              setVisible(true);
              bOk.addActionListener(this);
         public void actionPerformed (ActionEvent aE) {
              A = tIsi.getText();
    }Main Method:
    public class Sim {
         public static void main (String[] args) {
              kotakPesan p = new kotakPesan();
              String A = p.inputPesan("Masuk", "Angka");
              System.out.println(A);
    }

    I'm also learning java and I'm not quite sure what are you trying to do. Are you trying to read your pre-defined input in the text field?
    I've created a simple window with a text field, a button and the program will produce a sample output. I hope it will help you a bit.
    import javax.swing.*;
    import java.awt.event.*;
    public class TestWindow extends JFrame
         //Window attributes - references
         private JPanel panel;
         private JLabel inputLabel, outputLabel, resultLabel;
         private JTextField inputField;
         private JButton clickButton;
         //Window size - in pixels
         private final int WINDOW_WIDTH = 300;
         private final int WINDOW_HEIGHT = 450;
         //Constructor
         public TestWindow ()
              setTitle ("This is a simple window.");
              setSize (WINDOW_WIDTH, WINDOW_HEIGHT);
              setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
              createPanel ();
              add (panel);
              setVisible (true);
         private void createPanel ()
              inputLabel = new JLabel ("Enter an integer of your choice: ");
              outputLabel = new JLabel ("Your number is: ");
              resultLabel = new JLabel ("---------------");
              inputField = new JTextField (5);
              clickButton = new JButton (" dum dum dum ");
              clickButton.addActionListener (new TempListener ());
              panel = new JPanel();
              panel.add (inputLabel);
              panel.add (inputField);
              panel.add (outputLabel);
              panel.add (resultLabel);
              panel.add (clickButton);
         //Action listener for the button.
         private class TempListener implements ActionListener
              public void actionPerformed (ActionEvent event)
                   int textToInt;
                   String inputFieldTempOut = "";
                   String text = inputField.getText ();
                   textToInt = Integer.parseInt (text);
                   if (textToInt % 2 == 0)
                        if (textToInt == 0)
                             inputFieldTempOut = "Neither even nor odd.";
                        else
                             inputFieldTempOut = "An even number.";
                   else
                        inputFieldTempOut = "An odd number.";
                   resultLabel.setText (inputFieldTempOut);
    public class TestWindowDemo
       public static void main(String[] args)
          TestWindow tw = new TestWindow();
    }

Maybe you are looking for

  • How to insert new row in MIGO using badi.

    hi, Transaction code: MIGO. i'm using badi "MB_MIGO_BADI" and method "LINE_MODIFY", i want to insert N number of item lines when user entered any production order no. and press enter. Notes: production order has only one item line with qty N. regards

  • Script to choose which account mail is to be sent from in Mail?

    Does anyone have an AppleScript which will automatically set the default Mail account to an account chosen in script? I use FileMaker to send mail automatically, but have to use Eudora because it makes it easy to auto reset the default account from w

  • My phone is on bell how do i turn it to rogers.yahoo

    my phone is on bell how do i turn it to rogers.yahoo

  • Why should we go for ODI?

    Hi, I know the Informatica 9.1.0. Now , I am learning ODI so getting some questions. I am working with the Hyperion & ODI is used with the hyperion to fetch data from any source system. I have few questions in my mind related to ODI. why should I go

  • Export procedure for intrastat purposes

    Dear all, In Tcode Z*** is showing sales documents for which export procedure for intrastat purposes is no longer automatically determined in some case.Please  let me know the possible reasons. Regards, Praveen