Split InternalFrames in a JFrame

Hi, everybody,
I want to place some internal frames in a JFrame, those internal frames can be iconified, maximizable,resizable and closable, and the most important, they can be splited in a JFrame, just like JSplitpane in a JFrame.
How to implement this? Write a class to implement DesktopManager?Could anyone help me?
Kevin

Thank you, Bsampieri, I think it's my fault to make it unclear.
What I want to do is shown below:
| | | | |
| iframe #1 | iframe #2 | | iframe #1 |
| ________|_________| -- close #2 --> |_________________|
| | | |
| iframe #3 | | iframe #3 |
|__________________| |_________________|
| | | | | #2 |
| iframe #1 | iframe #2 | | iframe #1 | |
| ________|_________| -- iconify #2 --> |_____________|___|
| | | |
| iframe #3 | | iframe #3 |
|__________________| |_________________|
| | | | | |
| iframe #1 | iframe #2 | | iframe #1 | iframe #2 |
| ________|_________| -- close #3 --> | | |
| | | | |
| iframe #3 | | | |
|__________________| |_________|________|
Kevin

Similar Messages

  • JSplitPane in JFrame class

    Hi all,
    Sorry about the newbie question. I'm trying to place a split pane into a JFrame, but I'm not entirely clear how to implement it. The code is below. Ideally, I'd have one ImageJPanel on the left-hand side, to be populated with a BufferedImage, and one on the right, to be populated with a graphical representation of some data from that image (specifically RGB and HSV histograms). However, I'm just having trouble displaying the JSplitPane, although, admittedly, I don't know much about it. Any advice is appreciated. Thanks!
    Joe
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import java.awt.image.*;
    public class ImFrame extends JFrame implements ActionListener {
        ImageJPanel imgPanel = new ImageJPanel();
        ImageJPanel leftPanel = new ImageJPanel();
        ImageJPanel rightPanel = new ImageJPanel();
        JScrollPane imageScrollPane = new JScrollPane();
        JScrollPane leftPane = new JScrollPane();
        JScrollPane rightPane = new JScrollPane();
        private JSplitPane split;
        public ImFrame(){
            super("Image Display Frame");
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
            JMenu fileMenu = new JMenu("File");
            fileMenu.add(makeMenuItem("Open"));
            fileMenu.add(makeMenuItem("Save Analysis Data"));
            fileMenu.add(makeMenuItem("Quit"));
            JMenu analyzeMenu = new JMenu("Analyze");
            analyzeMenu.add(makeMenuItem("Smooth"));
            analyzeMenu.add(makeMenuItem("Display RGB and HSV"));
            analyzeMenu.add(makeMenuItem("Display Second Image for Comparison"));
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(fileMenu);
            menuBar.add(analyzeMenu);
            setJMenuBar(menuBar);
            split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                    leftPanel, rightPanel);
            split.setDividerLocation(150);
            split.setSize(300, 300);
            split.setRightComponent(rightPane);
            split.setLeftComponent(leftPane);
            setContentPane(split);
            setSize(300, 300);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                .addComponent(imageScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(imageScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
            imageScrollPane.setViewportView(imgPanel);
            pack();
            //setVisible(true);
        public void actionPerformed(ActionEvent e){
            String command = e.getActionCommand();
            if(command.equals("Quit")) System.exit(0);
            else if (command.equals("Open")) loadFile();
        private void loadFile(){
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showOpenDialog(this);
            if (result == JFileChooser.CANCEL_OPTION) return;
            try{
                File file = chooser.getSelectedFile();
                System.out.println("Loading..." + file.getAbsolutePath());
                BufferedImage buffImage = ImageIO.read(file);
                if (buffImage != null) {
                leftPanel.setImage(buffImage);
                imageScrollPane.setViewportView(leftPanel);
                } else {
                    System.out.println("Problem loading image file.");
            } catch(Exception e){
                System.out.println("File error:" + e);
        private JMenuItem makeMenuItem(String name){
            JMenuItem m = new JMenuItem(name);
            m.addActionListener(this);
            return m;
        public static void main(String[] s){
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ImFrame().setVisible(true);
    }

    split.setDividerLocation(150); // only works once the GUI is visible
    split.setSize(300, 300);Don't use setSize() it has no effect when using a layout manager
    split.setRightComponent(rightPane);
    split.setLeftComponent(leftPane);You are adding an ImagePanel. Presumably ImagePanel extends JPanel. I don't know what you code is like but I'm guessing that you are doing custom painting. When you do custom painting the panel does not have a preferred size (unless you specifically set it). So when you do a pack(), the preferred size of each panel is (0, 0) and therefore the preferred size of the split pane is (0, 0) plus the divideer size, so you frame is really small.
    setContentPane(split);Just use getContentPane().add(split);
    setSize(300, 300);Has no effect since the pack method will recalculate the preferred size as described above.
    Here is a simple example:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SplitPaneBasic extends JFrame
         JSplitPane splitPane;
         public SplitPaneBasic()
              JPanel red = new JPanel();
              red.setBackground( Color.RED );
              red.setPreferredSize( new Dimension(100, 100) );
    //          red.setMinimumSize( new Dimension(0, 0) );
              JPanel blue = new JPanel();
              blue.setBackground( Color.BLUE );
              blue.setPreferredSize( new Dimension(100, 100) );
              splitPane = new JSplitPane();
              splitPane.setOneTouchExpandable(true);
              splitPane.setLeftComponent( red );
              splitPane.setRightComponent( blue );
    //          splitPane.setDividerLocation(1.0);
    //          splitPane.setResizeWeight(0.5);
              getContentPane().add(splitPane, BorderLayout.CENTER);
              splitPane.setDividerLocation(1.0);
         public static void main(String[] args)
              SplitPaneBasic frame = new SplitPaneBasic();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.splitPane.setDividerLocation(0.75);
              frame.setVisible(true);
    //          frame.splitPane.setDividerLocation(1.0);
    }

  • How to handle resize events of JSplitPane?

    Hi all,
    I have been looking up and down for how to be notified when a split pane is resized (or moved). That is, the bar is moved by the user. I tried adding a component listener, property change listener and action listener. None seem to get called on every movement of it. Anyone know what listener I need to add to the JSplitPane for this to work?
    Thanks.

    Just to make sure the code is available in a search of java.sun forums
    import javax.swing.*;
    * split.java
    * Created on September 5, 2002, 2:01 AM
    * @author  Symplox
    public class split extends javax.swing.JFrame {
        /** Creates new form split */
        public split() {
            initComponents();
         private void initComponents() {
            split = new JSplitPane();
            jPanel1 = new JPanel();
            jPanel2 = new JPanel();
                jPanel3 = new JPanel();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Split");
            setBackground(new java.awt.Color(204, 204, 255));
            setName("Split");
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
                JLabel l = new JLabel("Divider Location");
                text = new JTextField("175", 5);
            split.setBackground(new java.awt.Color(51, 255, 0));
            split.setDividerLocation(175);
            split.setForeground(new java.awt.Color(255, 51, 51));
            split.setContinuousLayout(true);
            split.setPreferredSize(new java.awt.Dimension(350, 200));
                split.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
                /** This Listener is something I think you can use
                *   The PropertyChangeEvent seems to only monitor the divider
                *   location
            split.addPropertyChangeListener("lastDividerLocation", new java.beans.PropertyChangeListener() {
                public void propertyChange(java.beans.PropertyChangeEvent evt) {
                    text.setText(evt.getNewValue().toString());
            jPanel1.setBackground(new java.awt.Color(255, 255, 0));
            split.setLeftComponent(jPanel1);
            jPanel2.setBackground(new java.awt.Color(0, 204, 0));
            split.setRightComponent(jPanel2);
                jPanel3.setPreferredSize(new java.awt.Dimension(350, 20));
                jPanel3.add(l);
                jPanel3.add(text);
            getContentPane().add(split, java.awt.BorderLayout.CENTER);
                getContentPane().add(jPanel3, java.awt.BorderLayout.NORTH);
            pack();
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new split().show();
        private JPanel jPanel1, jPanel2, jPanel3;
        private JSplitPane split;
          private JTextField text;
    }

  • Use jFrames as InternalFrames

    Hi, I have a problem with a jFrames.
    I have a library with some jFrames already defined and programmed, and I have an application project with a MainFrame.
    I need to load the library's jFrames inside the Main jFrame on the application project; something like the internalFrames do. I still can't do that.
    I want to ask if it is possible to show jFrames contained inside other jFrame, or if I can, somehow, cast or convert a jFrame to a internalFrame to do what I need. Or if I will have to recode the library's jFrames to internalFrames?
    thanks for the help you can give me.
    race

    Nope. You cannot cast a JFrame as JInternalFrame or vice versa, nor can you make it a child window in the context of an MDI interface. This is one reason why I recommend that most Swing interface elements be placed on a JFrame that way you can plunk them down in a JFrame, a JInternalFrame or a JDialog as the situation demands.
    BTW ... This actually belongs in the Swing forum ...
    Hope this helps,
    PS.

  • How to set Max size of InternalFrame should be size of JFrame?

    Hi,
    I added the toolbar on the BorderLayout North,
    JDesktopPane on the BorderLayout Center and the
    statusBar on the BorderLayout South.
    Whenever the toolbar gets clicked,the JInternalFrame is added into the JDesktopPane.
    I want like,
    If is click the maximize button of JInternalFrame, it has to maximize the size of the JFrame,and the JIF title has to added with the JFrame title,
    how to go ahead?In which Listener i have to try for maximize button for JInternalFrame?
    | Main - x |
    | TollBar |
    |----------------------- |
    || Child - x | |
    |----------------------- |
    | |
    | |
    I would like this...
    | Main - Child - x |
    | TollBar - x |
    | |
    | |
    | |
    | |
    | |
    I am waiting for suggestion from the experts.
    If any one have a idea,pls. guide me to go ahead.

    Its not supported.

  • Problem adding a component into a JFrame

    public DVD_VIDEO_CLUB() {
    mainFrame = new JFrame("DVD-VIDEO CLUB");
    mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
    aDesktopPane = new JDesktopPane();
    aDesktopPane.setBackground(Color.LIGHT_GRAY);
    aDesktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    mainFrame.setContentPane(aDesktopPane);
    mainFrame.getContentPane().add(internalPanels.MainInternalPanel());
    atoolkit = Toolkit.getDefaultToolkit();
    mainFrame.addKeyListener(new MainFrameKeyListener());
    mainFrame.addWindowListener(new FrameListener());
    mainFrame.setIconImage(createFeatures.getImage());
    mainFrame.setSize(atoolkit.getScreenSize());
    mainFrame.setJMenuBar(aMenubar.MakeMenuBar(new ItemActListener()));
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(3);
    }//end constructor
    The argument internalPanels.MainInternalPanel() is a class (internalPanels) which have various jpanels
    that i want to display under certain events.
    But i don't know why the command
    mainFrame.getContentPane().add(internalPanels.MainInternalPanel());
    doesn't work? I look into the java tutorial and i have read that in order to add a component you have to
    call the command
    jframe.getContentPane().add(component);
    any help is appreciated!

    my problem isn't how to add internalframes but how to add a jpanel.Did you set the size of the JPanel?
    import java.awt.*;
    import javax.swing.*;
    public class Example {
        public static void main(String[] args) {
            JFrame mainFrame = new JFrame("DVD-VIDEO CLUB");
            mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
            JDesktopPane aDesktopPane = new JDesktopPane();
            mainFrame.setContentPane(aDesktopPane);
            JPanel p = new JPanel();
            p.add(new JLabel("here is your panel"));
            p.setLocation(100, 200); //as you like
            p.setSize(p.getPreferredSize()); //this may be what you are missing
            p.setVisible(true);
            mainFrame.getContentPane().add(p);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainFrame.setVisible(true);
    also i have tried not write 3 but JFrame.EXIT_ON_CLOSE but i was getting an error exception continiously.Do you mean a syntax error? That constant was introduced in 1.3 -- what version are you using?

  • ActionListener not working with JFrame

    Hi,
    I've just rehashed an old bit of code to work with a new application but for some reason the JButton ActionListeners aren't working. However if I extend JDialog they work ok. The current code for JDialog is:-
    * File:     GUI.java
    * @author           ODL 3xx Distributed Systems - Team x
    * @description      This class provides a means for the user to
    *                    interact with file server.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class GUI extends JDialog implements ActionListener, ApplicationConstants {
        private JLabel label1, label2, label3, label4, label5;
        private JTextField field1, field2, field3, field4, field5;
        private JButton button1, button2, button3, button4, button5;
        private Container container;
        private Message sendFile;
        private String id;
        private String defaultText = "Enter file name here";
        private ClientForGUI client;
        private long timeStart, timeEnd;
        public GUI(JFrame frame) {
            super(frame, "File Server Actions", true);
            client = new ClientForGUI(this);
            try{
                   InetAddress addr = InetAddress.getLocalHost();
                   id = addr.getHostName() + Long.toString((new java.util.Date()).getTime());
                   if(client.connectToServer())
                   initGUI();
                   else{
                        JOptionPane.showMessageDialog(this, "Unable to connect to server", "Error", JOptionPane.WARNING_MESSAGE);
                        System.exit(0);
              catch(UnknownHostException uhe){
                   System.out.println("Unknown Host Exception");
            initGUI();
         * Create the GUI
        private void initGUI() {
            container = this.getContentPane();
            container.setLayout(null);
            label1 = new JLabel("Upload File");
            label2 = new JLabel("Rename File");
            label3 = new JLabel("Delete File");
            label4 = new JLabel("Create File");
            label5 = new JLabel("Download File");
            field1 = new JTextField();
            field2 = new JTextField();
            field3 = new JTextField();
            field4 = new JTextField();
            field5 = new JTextField();
            button1 = new JButton("Upload");
            button2 = new JButton("Rename");
            button3 = new JButton("Delete");
            button4 = new JButton("Create");
            button5 = new JButton("Download");
            label1.setBounds(10,10,80,20);
            label2.setBounds(10,40,80,20);
            label3.setBounds(10,70,80,20);
            label4.setBounds(10,100,80,20);
            label5.setBounds(10,130,80,20);
            field1.setBounds(100,40,200,20);
            field1.setText("Old name");
            field2.setBounds(310,40,200,20);
            field2.setText("New name");
            field3.setBounds(100,70,410,20);
            field3.setText(defaultText);
            field4.setBounds(100,100,410,20);
            field4.setText(defaultText);
            field5.setBounds(100,130,410,20);
            field5.setText(defaultText);
            button1.setBounds(100,10,100,20);
            button1.addActionListener(this);
            button2.setBounds(520,40,100,20);
            button2.addActionListener(this);
            button3.setBounds(520,70,100,20);
            button3.addActionListener(this);
            button4.setBounds(520,100,100,20);
            button4.addActionListener(this);
            button5.setBounds(520,130,100,20);
            button5.addActionListener(this);
            container.add(label1);
            container.add(button1);
            container.add(label2);
            container.add(field1);
            container.add(field2);
            container.add(button2);
            container.add(label3);
            container.add(field3);
            container.add(button3);
            container.add(label4);
            container.add(field4);
            container.add(button4);
            container.add(label5);
            container.add(field5);
            container.add(button5);
            setSize(640,200);
            setResizable(false);
            //Centre on the screen
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              int x = (int) ((d.getWidth() - getWidth()) / 2);
              int y = (int) ((d.getHeight() - getHeight()) / 2);
              setLocation(x,y);
            setVisible(true);
        private void sendMessageToServer(Message message){
             message.setId(id);
             timeStart = new java.util.Date().getTime();
             try{
                  client.sendMessageToServer(message);
             catch(IOException ioe){
                  System.out.println("Unable to send message to server");
          * Perform some action based on user interaction
          * @param ae - ActionEvent
        public void actionPerformed(ActionEvent e){
            Object o = e.getSource();
            String name;
            if(o == button1){
                 try{
                        JFileChooser fc = new JFileChooser();
                       fc.setVisible(true);
                      //return value is what the user presses in the open File dialog
                      int returnVal = fc.showOpenDialog(null);
                      //if they choose OK
                      if (returnVal == JFileChooser.APPROVE_OPTION) {
                             //file now references the selected
                             File file = fc.getSelectedFile();
                             //create a FileInputStream from file location
                             FileInputStream fis = new FileInputStream(file);
                             // Create the byte array to hold the data, the same size as the file
                             byte [] fileBytes = new byte[(int)file.length()];
                              // Read in the bytes from the file into the byte array
                              int offset = 0;
                              int numRead = 0;
                              while (offset < fileBytes.length &&
                             (numRead=fis.read(fileBytes, offset, fileBytes.length-offset)) >=
                             0) {
                                  offset += numRead;
                             // Ensure all the bytes have been read in
                             if (offset < fileBytes.length) {
                                  throw new IOException("Could not completely read file "+file.getName());
                             fis.close();
                             sendFile = new Message(SEND_FILE, fileBytes);
                             sendFile.setId(id);
                             sendFile.setFileName(file.getName());
                             byte [] myarray = ConvertData.messageToBytes(sendFile);
                             Message sendWarning = new Message(SEND_FILE_WARNING);
                               sendWarning.setFileName(file.getName());
                              sendWarning.setFileSize(myarray.length);
                              try{
                                    sendMessageToServer(sendWarning);
                               catch(Exception excep){
                                    System.out.println(excep);
                   catch(FileNotFoundException fnfe){
                        System.out.println("File Not Found Exception");
                   catch(java.io.IOException ioe){
                        System.out.println("IO Exception");
            else if(o == button2){
                   name = field1.getText();
                   String name2 = field2.getText();
                   Message renameMessage = new Message(RENAME_FILE);
                   renameMessage.setFileName(name);
                   renameMessage.setFileRename(name2);
                   sendMessageToServer(renameMessage);
                   field1.setText("Old name");
                   field2.setText("New name");
            else if(o == button3){
                   name = field3.getText();
                   Message deleteMessage = new Message(DELETE_FILE);
                   deleteMessage.setFileName(name);
                   sendMessageToServer(deleteMessage);
                   field3.setText(defaultText);
            else if(o == button4){
                   name = field4.getText();
                   Message createMessage = new Message(CREATE_FILE);
                   createMessage.setFileName(name);
                   sendMessageToServer(createMessage);     
                   field4.setText(defaultText);     
            else if(o == button5){
                   name = field5.getText();
                   Message downloadMessage = new Message(REQUEST_FILE);
                   downloadMessage.setFileName(name);
                   sendMessageToServer(downloadMessage);
                   field5.setText(defaultText);          
        public void processServerMessage(Message message){
             switch(message.getMessageHeader()){
                   case SEND_FILE_WARNING:
                   //change the download size to file size plus max message size
                   client.setDownload((int)message.getFileSize(),true);
                   //turn message back around with acknowledgement header
                   message.setMessageHeader(SEND_FILE_ACK);
                   //send the message
                   try{
                        sendMessageToServer(message);
                   catch(Exception e){
                        System.out.println(e);
                   break;
                   //server has acknowledged that the client wishes to send a message
                   //so send the message
                   case SEND_FILE_ACK:
                   //send the message
                   try{
                        sendMessageToServer(sendFile);
                   catch(Exception e){
                        System.out.println(e);
                   break;
                   //server is sending the file to the client.
                   case SEND_FILE:
                   //reset the download size to default
                   client.setDownload(DEFAULT_MESSAGE_SIZE,false);
                   //get the file name
                   File f = new File(message.getFileName());
                   //create the file chooser
                   JFileChooser fc = new JFileChooser();
                   //set selected file as thoe one downloaded
                   fc.setSelectedFile(f);
                   //get the button hit by the user
                 int returnVal = fc.showSaveDialog(null);
                 //if button is OK
                  if (returnVal == JFileChooser.APPROVE_OPTION){
                       File temp = fc.getCurrentDirectory();
                       String [] files = temp.list();
                       java.util.List alist = java.util.Arrays.asList(files);
                       f = fc.getSelectedFile();
                       if(alist.contains(message.getFileName())){
                            if(JOptionPane.showConfirmDialog(null,
                                       message.getFileName() + " already exists. Are you sure you want to overwrite this file?",
                                       "Instant Messenger: Quit Program",
                                       JOptionPane.YES_NO_OPTION,
                                       JOptionPane.QUESTION_MESSAGE,
                                       null) == JOptionPane.YES_OPTION) {
                                            //f = fc.getSelectedFile();
                                            System.out.println(f.toString());
                                           //this is where the file is copied
                                           try{
                                                FileOutputStream fs = new FileOutputStream(f);
                                                 fs.write(message.getFile());
                                                 fs.close();
                                           catch(IOException e){
                                                System.out.println(e);
                            else fc.hide();
                       else{
                            System.out.println("Here " + f.toString());
                            try{
                                 FileOutputStream fs = new FileOutputStream(f);
                                  fs.write(message.getFile());
                                  fs.close();
                            catch(IOException e){
                                 System.out.println(e);
                  else fc.hide();
                  break;
                  case INFORMATION:
                  timeEnd = new java.util.Date().getTime();
                  Long rtrip = timeEnd - timeStart;
                  String str = Long.toString(rtrip);
                  double d = Double.valueOf(str).doubleValue();
                  String fullMessage = message.getMessage();
                  fullMessage += " The total time taken for the last request was " +
                  rtrip + " milliseconds" + " or roughly " + d/1000 + " seconds";
                   JOptionPane.showMessageDialog(null,fullMessage,"Information",JOptionPane.INFORMATION_MESSAGE);
                   break;          
    class TestGUI{
        public static void main(String [] args){
             JFrame frame = new JFrame();
             GUI myGUI = new GUI(frame);
    }     If I change the GUI constructor to empty and extend JFrame instead of JDialog and change the call to super the ActionListener stops working. I've never known this problem before (i.e. I always use e.getSource()). I've even cast the object to a JButton to ensure that the right button is pressed and it is all ok.
    Is there something fundamentally wrong when I make those simple changes to JFrame?
    Regards,
    Chris

    I think rather the approach is your action handling in terms of the buttons. The giant actionPerformed method is difficult to read and maintain.
    I would recommend the following things:
    1. Split your ActionListener into multiple smaller listeners. There's not really even a reason for the GUI class to be an action listener. Instead of having GUI implement ActionListener and trying to keep all of the functionality in one place, use anonymous classes:
    button3.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent e)
            name = field3.getText();
            Message deleteMessage = new Message(DELETE_FILE);
            deleteMessage.setFileName(name);
            sendMessageToServer(deleteMessage);
            field3.setText(defaultText);
    button4.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent e)
            name = field4.getText();
            Message createMessage = new Message(CREATE_FILE);
            createMessage.setFileName(name);
            sendMessageToServer(createMessage);     
            field4.setText(defaultText);
    2. Only use the == operator on primitives. There are very few cases in which you can properly use the == operator on objects and, in every one of those cases I have experienced, the equals(Object) method produces the same result.
    3. Name your variables more descriptively. There is really very little reason for your buttons to be named button1, button2, and so on. Give them names that mean something. For example, button1 should be named something like uploadFileButton or buttonUpload. That will give us significant information about what it is expected to do, whereas button1 does not. You may be able to remember what button1 does, but you wrote the code. I keep having to refer back to the instantiation of the button to get a hint as to what it does and, in a few months' time, so will you. :) The same goes for your labels and fields, as well.
    I'm not sure why you aren't getting the behavior you want. However, have you checked to determine that the event source of the button click is actually the button when the whole thing is inside of a JFrame? I would expect it to be, but you never know. This is why I recommend using different ActionListeners for each button. That way, you can be sure of what caused the event.
    Just my 2c. Good luck to you. :)

  • Need help creating a Jframe

    Hi guys, need a little help here in creating a Jframe. Its not something I am knowledgeable at all with and I need this done for my Introductory Java class. I have the other parts of the program finished as best as I can get it. I will post the problem and my code so you guys can look at it and maybe help me out. All help is appreciated
    Problem:
    Congratulations, your fame as a Java programmer is spreading, and you have been hired by Intelecom Group to create a special application. Using multiple classes design an online address book to keep track of the names, addresses, phone numbers, and birthdays of family members, close friends, and certain business associates. Your program should be able to handle a maximum of 500 entries. This program should load the data from a file, called phoneData.txt.
    User Interface: Using JFrame, create a user interface of your design. Remember, unless notified otherwise, ALL input and output will be via this interface.
    Functionality: The program should be able to do the following:
    a) Search for all of the names and phone numbers by first letter of the last name, (this can be displayed using a message box)
    b) Search for a particular person by last name, displaying their phone number, address, and date of birth.
    c) Display the names of people whose birthday's are in a given month.
    d) Search for a person by their phone number, displaying their name, address, and their relationship (ie. Family, Friend, or Associate
    Code:
    package back_end;
    import java.util.*;
    public class Test_backend
    * @param args
    public static void main(String[] args)
    //Relation_type FRIEND;
    // TODO Auto-generated method stub
    Birthday b1 = new Birthday(9,2,1985);
    Birthday b2 = new Birthday(6,21,1985);
    Birthday b3 = new Birthday(1,2,1990);
    Birthday b4 = new Birthday(1,3,1950);
    Person p1 = new Person ("Sloan", "Mergler", "4 vanderbilt drive",
    "516-551-0829", b1, Relation_type.FRIEND );
    Person p2 = new Person ("Taylor", "Bowne", "21 greywood street",
    "516-944-6812", b2, Relation_type.FRIEND);
    // these are random numbers for birthdays
    Person p3 = new Person ("Daniel", "Py", "21 roger drive apt 2",
    "516-944-7530", b3, Relation_type.FAMILY_MEMBER);
    Person p4 = new Person ("Richard", "Py", "21 roger drive apt 1",
    "516-944-7530", b4, Relation_type.FAMILY_MEMBER);
    Address_book a1 = new Address_book();
    a1.add_to_book(p1);
    a1.add_to_book(p2);
    a1.add_to_book(p3);
    a1.add_to_book(p4);
    System.out.println("This is testing search_by_last_initial");
    Vector vt1a = a1.search_by_last_initial("M");
    Test_backend.printOutVector(vt1a);
    System.out.println("Sloan Mergler should be : ");
    Vector vt1b = a1.search_by_last_initial("P");
    Test_backend.printOutVector(vt1b);
    System.out.println("Daniel Py and Richard Py should be :");
    System.out.println("This is testing search_by_last_Name");
    Person lastname1 = a1.search_by_last_name("Mergler");
    System.out.println(lastname1.first_name + " " + lastname1.last_name +
    " should be Sloan Mergler " );
    Person lastname2 = a1.search_by_last_name("Bowne");
    System.out.println(lastname2.first_name + " " + lastname2.last_name +
    "should be Taylor Bowne" );
    System.out.println("This is testing search_by_birth_month");
    Vector vt3a = a1.search_by_birth_month(1);
    Test_backend.printOutVector(vt3a);
    System.out.println("should be Daniel Py and Richard Py");
    Vector vt3b = a1.search_by_birth_month(6);
    Test_backend.printOutVector(vt3b);
    System.out.println("should be Taylor Bowne");
    System.out.println("This is testing search_by_phone_number");
    Person pt4a = a1.search_by_phone_number("516-944-7530");
    System.out.println(pt4a.first_name + " " + pt4a.last_name +
    " should be Daniel Py");
    Person pt4b = a1.search_by_phone_number("516-551-0829");
    System.out.println(pt4b.first_name + " " + pt4b.last_name +
    " should be Sloan Mergler");
    public static void printOutVector(Vector v1)
    for (int x = 0; x < v1.size(); x++)
    Person p1 = (Person) v1.get(x);
    String s1 = p1.first_name +" " + p1.last_name + "";
    System.out.println(s1);
    return;
    package back_end;
    public enum Relation_type
    FAMILY_MEMBER,
    FRIEND,
    BUSINESS_ASSOCIATE
    package back_end;
    public class Person
    String first_name;
    String last_name;
    String address;
    String phoneNumber;
    Birthday birthday;
    Relation_type relation;
    public Person (String first_name, String last_name, String address, String phoneNumber, Birthday birthday, Relation_type relation)
    this.first_name = first_name;
    this.last_name = last_name;
    this.address = address;
    this.phoneNumber = phoneNumber;
    this.birthday = birthday;
    this.relation = relation;
    // default constructor
    public Person (){}
    package back_end;
    public class Birthday
    int birth_month;
    int birth_day;
    int birth_year;
    Birthday(int birth_month, int birth_day, int birth_year)
    this.birth_month = birth_month;
    this.birth_day = birth_day;
    this.birth_year = birth_year;
    package back_end;
    import java.util.*;
    * This class is the addressbook, it is to keep track of all your associates
    public class Address_book
    int MAX_SIZE = 500;
    public ArrayList book;
    // constructor
    public Address_book()
    this.book = new ArrayList(MAX_SIZE);
    // methods
    public void add_to_book(Person newPerson)
    boolean it_worked = this.book.add(newPerson);
    if (it_worked){ return ;}
    else
    throw new RuntimeException ("Too many items in book, it is filled up");
    * Functionality for this class
    * a) Search for all of the names and phone numbers by first letter of
    * last name (this can be displayed in a message box).
    * b) Search for a particular person by last name, displaying their
    * phone number, address, and date of birth.
    * c) Display the names of people whose birthdays are in a given month.
    * d) Search for a person by phone number, displaying their name,
    * address, and their relationship (ie Family, Friend, or Associate).
    * This method shold work for functionality part a
    * Given a string containing one letter, this function will search through
    * this and try to find all occurances of people whose last name start
    * with the given string and return it in a vector
    public Vector search_by_last_initial (final String last_initial)
    // this is for input error checking
    if (last_initial.length() != 1){
    throw new RuntimeException("Input was not supposed to be that long");
    Vector v1 = new Vector();
    final int current_size = this.book.size();
    for ( int x = 0; x < current_size; x++)
    final Person listed_person = (Person) this.book.get(x);
    if (listed_person.last_name.startsWith(last_initial))
    v1.add( listed_person);
    return v1;
    * this will work for parth b
    * Given a string, it will search for anyone with last name equal
    * to given string and return the first occurance of a person
    * with that last name
    public Person search_by_last_name ( final String last_name)
    final int current_size = this.book.size();
    for ( int x = 0; x < current_size; x++)
    final Person listed_person = (Person) this.book.get(x);
    if (listed_person.last_name.equalsIgnoreCase(last_name))
    return listed_person;
    return null;
    * This method should work for part c
    * Given the month, given in the form of an int, it will return a list
    * of people whose Birthdays are in that month
    public Vector search_by_birth_month (final int birth_month)
    // this is for input checking
    if (birth_month > 12 || birth_month < 1)
    throw new RuntimeException("That is not a month");
    // main stuff
    Vector v1 = new Vector();
    final int current_size = this.book.size();
    for ( int x = 0; x < current_size; x++)
    final Person listed_person = (Person) this.book.get(x);
    if (listed_person.birthday.birth_month == birth_month)
    v1.add( listed_person);
    return v1;
    * This method should satisfy part d
    * Given a phone number in the form 'xxx-xxx-xxxx', this function will
    * return the person with that number
    public Person search_by_phone_number (final String pnumber)
    if (pnumber.length() != 12
    || ! is_It_A_PhoneNumber(pnumber)
    throw new RuntimeException("This phone number is not of right form (ex. xxx-xxx-xxxx)");
    final int current_size = this.book.size();
    for ( int x = 0; x < current_size; x++)
    final Person listed_person = (Person) this.book.get(x);
    if (listed_person.phoneNumber.equalsIgnoreCase(pnumber))
    return listed_person;
    return null;
    // this function uses the regex features of java which i am not so sure about....
    private boolean is_It_A_PhoneNumber(final String possPnum)
    boolean return_value = true;
    String[] sa1 = possPnum.split("-");
    if (sa1[0].length() != 3 ||
    sa1[1].length() != 3 ||
    sa1[2].length() != 4 ){ return_value = false;}
    return return_value;
    Thanks to anyone who can help me out

    Code:
    package back_end;
    import java.util.*;
    public class Test_backend
    * @param args
    public static void main(String[] args)
    //Relation_type FRIEND;
    // TODO Auto-generated method stub
    Birthday b1 = new Birthday(9,2,1985);
    Birthday b2 = new Birthday(6,21,1985);
    Birthday b3 = new Birthday(1,2,1990);
    Birthday b4 = new Birthday(1,3,1950);
    Person p1 = new Person ("Sloan", "Mergler", "4 vanderbilt drive",
    "516-551-0829", b1, Relation_type.FRIEND );
    Person p2 = new Person ("Taylor", "Bowne", "21 greywood street",
    "516-944-6812", b2, Relation_type.FRIEND);
    // these are random numbers for birthdays
    Person p3 = new Person ("Daniel", "Py", "21 roger drive apt 2",
    "516-944-7530", b3, Relation_type.FAMILY_MEMBER);
    Person p4 = new Person ("Richard", "Py", "21 roger drive apt 1",
    "516-944-7530", b4, Relation_type.FAMILY_MEMBER);
    Address_book a1 = new Address_book();
    a1.add_to_book(p1);
    a1.add_to_book(p2);
    a1.add_to_book(p3);
    a1.add_to_book(p4);
    System.out.println("This is testing search_by_last_initial");
    Vector vt1a = a1.search_by_last_initial("M");
    Test_backend.printOutVector(vt1a);
    System.out.println("Sloan Mergler should be : ");
    Vector vt1b = a1.search_by_last_initial("P");
    Test_backend.printOutVector(vt1b);
    System.out.println("Daniel Py and Richard Py should be :");
    System.out.println("This is testing search_by_last_Name");
    Person lastname1 = a1.search_by_last_name("Mergler");
    System.out.println(lastname1.first_name + " " + lastname1.last_name +
    " should be Sloan Mergler " );
    Person lastname2 = a1.search_by_last_name("Bowne");
    System.out.println(lastname2.first_name + " " + lastname2.last_name +
    "should be Taylor Bowne" );
    System.out.println("This is testing search_by_birth_month");
    Vector vt3a = a1.search_by_birth_month(1);
    Test_backend.printOutVector(vt3a);
    System.out.println("should be Daniel Py and Richard Py");
    Vector vt3b = a1.search_by_birth_month(6);
    Test_backend.printOutVector(vt3b);
    System.out.println("should be Taylor Bowne");
    System.out.println("This is testing search_by_phone_number");
    Person pt4a = a1.search_by_phone_number("516-944-7530");
    System.out.println(pt4a.first_name + " " + pt4a.last_name +
    " should be Daniel Py");
    Person pt4b = a1.search_by_phone_number("516-551-0829");
    System.out.println(pt4b.first_name + " " + pt4b.last_name +
    " should be Sloan Mergler");
    public static void printOutVector(Vector v1)
    for (int x = 0; x < v1.size(); x++)
    Person p1 = (Person) v1.get(x);
    String s1 = p1.first_name +" " + p1.last_name + "";
    System.out.println(s1);
    return;
    package back_end;
    public enum Relation_type
    FAMILY_MEMBER,
    FRIEND,
    BUSINESS_ASSOCIATE
    package back_end;
    public class Person
    String first_name;
    String last_name;
    String address;
    String phoneNumber;
    Birthday birthday;
    Relation_type relation;
    public Person (String first_name, String last_name, String address, String phoneNumber, Birthday birthday, Relation_type relation)
    this.first_name = first_name;
    this.last_name = last_name;
    this.address = address;
    this.phoneNumber = phoneNumber;
    this.birthday = birthday;
    this.relation = relation;
    // default constructor
    public Person (){}
    package back_end;
    public class Birthday
    int birth_month;
    int birth_day;
    int birth_year;
    Birthday(int birth_month, int birth_day, int birth_year)
    this.birth_month = birth_month;
    this.birth_day = birth_day;
    this.birth_year = birth_year;
    package back_end;
    import java.util.*;
    * This class is the addressbook, it is to keep track of all your associates
    public class Address_book
    int MAX_SIZE = 500;
    public ArrayList book;
    // constructor
    public Address_book()
    this.book = new ArrayList(MAX_SIZE);
    // methods
    public void add_to_book(Person newPerson)
    boolean it_worked = this.book.add(newPerson);
    if (it_worked){ return ;}
    else
    throw new RuntimeException ("Too many items in book, it is filled up");
    * Functionality for this class
    * a) Search for all of the names and phone numbers by first letter of
    * last name (this can be displayed in a message box).
    * b) Search for a particular person by last name, displaying their
    * phone number, address, and date of birth.
    * c) Display the names of people whose birthdays are in a given month.
    * d) Search for a person by phone number, displaying their name,
    * address, and their relationship (ie Family, Friend, or Associate).
    * This method shold work for functionality part a
    * Given a string containing one letter, this function will search through
    * this and try to find all occurances of people whose last name start
    * with the given string and return it in a vector
    public Vector search_by_last_initial (final String last_initial)
    // this is for input error checking
    if (last_initial.length() != 1){
    throw new RuntimeException("Input was not supposed to be that long");
    Vector v1 = new Vector();
    final int current_size = this.book.size();
    for ( int x = 0; x < current_size; x++)
    final Person listed_person = (Person) this.book.get(x);
    if (listed_person.last_name.startsWith(last_initial))
    v1.add( listed_person);
    return v1;
    * this will work for parth b
    * Given a string, it will search for anyone with last name equal
    * to given string and return the first occurance of a person
    * with that last name
    public Person search_by_last_name ( final String last_name)
    final int current_size = this.book.size();
    for ( int x = 0; x < current_size; x++)
    final Person listed_person = (Person) this.book.get(x);
    if (listed_person.last_name.equalsIgnoreCase(last_name))
    return listed_person;
    return null;
    * This method should work for part c
    * Given the month, given in the form of an int, it will return a list
    * of people whose Birthdays are in that month
    public Vector search_by_birth_month (final int birth_month)
    // this is for input checking
    if (birth_month > 12 || birth_month < 1)
    throw new RuntimeException("That is not a month");
    // main stuff
    Vector v1 = new Vector();
    final int current_size = this.book.size();
    for ( int x = 0; x < current_size; x++)
    final Person listed_person = (Person) this.book.get(x);
    if (listed_person.birthday.birth_month == birth_month)
    v1.add( listed_person);
    return v1;
    * This method should satisfy part d
    * Given a phone number in the form 'xxx-xxx-xxxx', this function will
    * return the person with that number
    public Person search_by_phone_number (final String pnumber)
    if (pnumber.length() != 12
    || ! is_It_A_PhoneNumber(pnumber)
    throw new RuntimeException("This phone number is not of right form (ex. xxx-xxx-xxxx)");
    final int current_size = this.book.size();
    for ( int x = 0; x < current_size; x++)
    final Person listed_person = (Person) this.book.get(x);
    if (listed_person.phoneNumber.equalsIgnoreCase(pnumber))
    return listed_person;
    return null;
    // this function uses the regex features of java which i am not so sure about....
    private boolean is_It_A_PhoneNumber(final String possPnum)
    boolean return_value = true;
    String[] sa1 = possPnum.split("-");
    if (sa1[0].length() != 3 ||
    sa1[1].length() != 3 ||
    sa1[2].length() != 4 ){ return_value = false;}
    return return_value;
    }

  • Problem with InternalFrame. Help!!

    hai,
    I am having two classes of internalframes. I want to open 'IFrame1',first internalframe by giving command. It is coming correctly. After 'IFrame1' is opened, if anyone presses 'IFrame2' button, internalframe2 should be opened. It is opening correctly. But it looks in the 'Cascading' format, one internalFrame on the top and another one on the bottom in the cascading style. I tried with more different ways to overcome this problem. Hope u can understand the problem. Please do reply, if anyone knows. thanks.
    bhuvana.

    hi,
    herewith I am attaching my sample code.
    public class IFrame1 extends JInternalFrame implements ActionListener
         Container cp=getContentPane();
         JPanel jp1,jp2;
         JButton click;
         public IFrame1(String title,boolean b1,boolean b2,boolean b3,boolean b4)
              super(title,b1,b2,b3,b4);
              jp1=new JPanel();
              cp.setLayout(null);
              jp1.setLayout(null);
              jp2=new JPanel();
              jp2.setLayout(null);
              jp1.setBounds(0,0,800,600);
              cp.add(jp1);
              click=new JButton("click");
              click.setBounds(50,50,100,20);
              jp1.add(click);
              click.addActionListener(this);
         public void actionPerformed(ActionEvent ae)
              if(ae.getSource()==click)
                   IFrame2 iframe2=new IFrame2("IFrame2",true,true,true,true);
                   iframe2.setBounds(0,0,800,600);
                   jp2.setBounds(0,0,800,600);
                   jp1.setVisible(false);
                   jp2.add(iframe2);
                   ip2.setVisible(true);
                   iframe2.setVisible(true);
                   cp.add(jp2);
         public static void main(String args[])
                   JFrame jf=new JFrame();
                   IFrame1 iframe1=new IFrame1("IFrame1",true,true,true,true);
                   jf.getContentPane().add(iframe1);
                   jf.setSize(800,600);
                   jf.setVisible(true);
                   iframe1.setVisible(true);
    }//eof IFrame1
    //class for IFrame2
    public class IFrame2 extends JInternalFrame
         Container cp1=getContentPane();
         Button b;
    //constructor
         public IFrame2(String title,boolean b1,boolean b2,boolean b3,boolean b4)
              super(title,b1,b2,b3,b4);
              cp1.setLayout(null);
              b=new JButton("IFrame2");
              b.setBounds(10,10,120,20);
              cp1.add(b);
    }//eof IFrame2
              Please take note of it, and reply whats the bug. Thanks in advance.
    bhuvana.

  • JFrame decorations problem

    Greetings:
    I've found searching at the net, that it is suggested "that the L&F (rather than the system) decorate all windows. This must be invoked before creating the JFrame. Native look and feels will ignore this hint". The command that does this is the static JFrame.setDefaultLookAndFeelDecorated(true); .
    If I install Metal L&F as default, and then go to Full Screen and change the L&F, it partially WORKS (the Metal L&Fdecorations are set like in an InternalFrame); but if I set the System L&F as default and change the L&F, the new L&F does not recive its propper decorations but rather the system ones.
    Could anyone help me in this issue?
    Thanks a lot in advanced.
    Javier
    // java scope
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import com.sun.java.swing.plaf.motif.*;
    public abstract class LandFTest {
       public static void main(String[] args) {
          try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } //UIManager.getCrossPlatformLookAndFeelClassName()
          catch (Exception e) { }
          SwingUtilities.invokeLater(new Runnable() {
             public void run() { JFrame.setDefaultLookAndFeelDecorated(true);
                                 MainWin myWindow = new MainWin(" Look & Feel Test");
                                 myWindow.pack();
                                 myWindow.setVisible(true); }
    class MainWin extends JFrame {
          public Box mainLayout = new MainComponent(this);
             public JScrollPane mainLayoutScrollPane = new JScrollPane(mainLayout);
          public Boolean FullScrnOn=false;
       public MainWin (String mainWin_title) {
          Container framePanel = this.getContentPane();
          this.setTitle(mainWin_title);
          this.setLocationRelativeTo(null);
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          framePanel.add(mainLayoutScrollPane,BorderLayout.CENTER);
    class MainComponent extends Box {
          Box controls_Box = Box.createHorizontalBox();
          Box lfControl_Box = Box.createVerticalBox();
          JRadioButton landfRadioButton1 = new JRadioButton(" Metal skin (Java)"),
                       landfRadioButton2 = new JRadioButton(" System skin",true),
                       landfRadioButton3 = new JRadioButton(" Motif skin");
          ButtonGroup lanfFButtonGroup = new ButtonGroup();
          JButton fullScrnButton = new JButton("Full Screen On");
    public MainComponent(MainWin refFrame){
          super(BoxLayout.Y_AXIS);
          this.initMainCompopent(refFrame);
          this.setMainComponent();
       public void initMainCompopent (MainWin refFrame) {
           LookAndFeel_ActionListener landFListener = new LookAndFeel_ActionListener(lanfFButtonGroup, refFrame);
           FullScreen_ActionListener fullSCrnListener = new FullScreen_ActionListener(refFrame);
          lfControl_Box.setBorder(BorderFactory.createTitledBorder(" Look & Feel Control "));
          landfRadioButton1.setActionCommand("Java");
             landfRadioButton1.addActionListener(landFListener);
             lanfFButtonGroup.add(landfRadioButton1);
          landfRadioButton2.setActionCommand("System");
             landfRadioButton2.addActionListener(landFListener);
             lanfFButtonGroup.add(landfRadioButton2);
          landfRadioButton3.setActionCommand("Motif");
             landfRadioButton3.addActionListener(landFListener);
             lanfFButtonGroup.add(landfRadioButton3);
          fullScrnButton.addActionListener(fullSCrnListener);
          fullScrnButton.setAlignmentX(Component.CENTER_ALIGNMENT);
       public void setMainComponent () {
          controls_Box.add(Box.createHorizontalGlue());
          controls_Box.add(lfControl_Box);
             lfControl_Box.add(landfRadioButton1);
             lfControl_Box.add(landfRadioButton2);
             lfControl_Box.add(landfRadioButton3);
          controls_Box.add(Box.createHorizontalGlue());
          this.add(Box.createVerticalGlue());
          this.add(controls_Box);
          this.add(Box.createVerticalGlue());
          this.add(fullScrnButton);
          this.add(Box.createVerticalGlue());
    class LookAndFeel_ActionListener implements ActionListener {
          private ButtonGroup eventButtonGroup;
          private MainWin eventFrame;
       public LookAndFeel_ActionListener (ButtonGroup buttonGroup, MainWin eventFrame) {
          this.eventButtonGroup = buttonGroup;
          this.eventFrame = eventFrame;
       public void actionPerformed(ActionEvent event) {
          String command = eventButtonGroup.getSelection().getActionCommand();
          GraphicsDevice scrnDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
          eventFrame.dispose();
          if (command.equals("System")) {
            try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
            catch (Exception e) { }
          else { if (command.equals("Java")) {
                   try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());}
                   catch (Exception e) { }
                 else { if (command.equals("Motif")) {
                          try { UIManager.setLookAndFeel(new MotifLookAndFeel()); }
                          catch (Exception e) { }
                        else { }
          SwingUtilities.updateComponentTreeUI(eventFrame);
          if (eventFrame.FullScrnOn){ try {scrnDevice.setFullScreenWindow(eventFrame); }
                                      finally {  }
          } else { JFrame.setDefaultLookAndFeelDecorated(true); }
          eventFrame.setVisible(true);
          //eventFrame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
    class FullScreen_ActionListener implements ActionListener {
          private MainWin eventFrame;
       public FullScreen_ActionListener (MainWin eventFrame) {
          this.eventFrame = eventFrame;
       public void actionPerformed(ActionEvent event) {
             MainComponent mainFrameLayout = (MainComponent)eventFrame.mainLayout;
             GraphicsDevice scrnDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
          if (!eventFrame.FullScrnOn){
             if (scrnDevice.isFullScreenSupported()) {
                // Enter full-screen mode with an undecorated JFrame
                eventFrame.dispose();
                eventFrame.setUndecorated(true);
                eventFrame.setResizable(false);
                mainFrameLayout.fullScrnButton.setText("Full Screen Off");
                eventFrame.FullScrnOn=!eventFrame.FullScrnOn;
                try {scrnDevice.setFullScreenWindow(eventFrame); }
                finally {  }
             } else { JOptionPane.showMessageDialog(eventFrame, "Full Screen mode is not allowed \nby the system in this moment.",
                                                                " Full Screen Info", JOptionPane.INFORMATION_MESSAGE); }
          else { // Return to Windowed mode mode with JFrame decorations
                  eventFrame.dispose();
                  eventFrame.setUndecorated(false);
                  eventFrame.setResizable(true);
                  mainFrameLayout.fullScrnButton.setText("Full Screen On");
                  eventFrame.FullScrnOn=!eventFrame.FullScrnOn;
                  try { scrnDevice.setFullScreenWindow(null); }
                  finally { }
          eventFrame.setVisible(true);
    }

    Greetings:
    Thanks a lot for your kind answer:
    After reading your reply, I've done some studies directly in the API in how does the L&F's are managed. Of what I've understood (please correct me if I'm wrong), the things are as follow:
    i) System and Motif Look and Feel's does NOT support decorations, so that's why you should let the JVM do the decoration work (that is, use myFrame.setUndecorated(false); ).
    In this case, it does not matter if you use JFrame.setDefaultLookAndFeelDecorated(true); before the creation of the frame: it won't show decorations if you don't use the command mentioned.
    ii) Metal (Java) Look and Feel DOES support decorations; that's why, if you use JFrame.setDefaultLookAndFeelDecorated(true); before the creation of the frame, you'll see it's own decorations. In this case, you should use myFrame.setUndecorated(true); so the L&F does all the decorating work, avoiding the weird sitiuation of showing double decorating settings (L&F's and native system's).
    iii) So, the real problem here would be if you want to have, as a user choice, that the System/Motif L&F's will be available together with the Java's (Metal). I've made the next variation to my code, so that this will be possible:
    class LookAndFeel_ActionListener implements ActionListener {
    private ButtonGroup eventButtonGroup;
    private MainWin eventFrame;
    public LookAndFeel_ActionListener (ButtonGroup buttonGroup, MainWin eventFrame) {
    this.eventButtonGroup = buttonGroup;
    this.eventFrame = eventFrame;
    public void actionPerformed(ActionEvent event) {
    String command = eventButtonGroup.getSelection().getActionCommand();
    GraphicsDevice scrnDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    eventFrame.dispose();
    if (command.equals("System")) {
    try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    eventFrame.setUndecorated(false); // make sure the native system controls decorations as this L&F doesnt's manage one's.
    catch (Exception e) { }
    else { if (command.equals("Java")) {
    try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); }
    catch (Exception e) { }
    eventFrame.setUndecorated(true); // make sure the L&F controls decorations as it actually has one's.
    else { if (command.equals("Motif")) {
    try { UIManager.setLookAndFeel(new MotifLookAndFeel()); }
    catch (Exception e) { }
    eventFrame.setUndecorated(false); // make sure the native system controls decorations as this L&F doesnt's manage one's.
    else { }
    SwingUtilities.updateComponentTreeUI(eventFrame);
    if (eventFrame.FullScrnOn){ try {scrnDevice.setFullScreenWindow(eventFrame); }
    finally { }
    } else { }
    eventFrame.setVisible(true);
    }iv) The issue here is that, as I needed to use myFrame.dispose() (the JVM says that it is not possible to use setUndecorated(false); in a displayable frame), I recieve and error:
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Buffers have not been created
    at sun.awt.windows.WComponentPeer.getBackBuffer(WComponentPeer.java:846)
    at java.awt.Component$FlipBufferStrategy.getBackBuffer(Component.java:3815)
    at java.awt.Component$FlipBufferStrategy.updateInternalBuffers(Component.java:3800)
    at java.awt.Component$FlipBufferStrategy.revalidate(Component.java:3915)
    at java.awt.Component$FlipBufferStrategy.revalidate(Component.java:3897)
    at java.awt.Component$FlipBufferStrategy.getDrawGraphics(Component.java:3889)
    at javax.swing.BufferStrategyPaintManager.prepare(BufferStrategyPaintManager.java:508)
    at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:264)
    at javax.swing.RepaintManager.paint(RepaintManager.java:1220)
    at javax.swing.JComponent.paint(JComponent.java:1015)
    and, yet, the Metal (Java's) L&F keeps without decorations. Is it there a way to solve this without having to create a new instance of the frame and use JFrame.setDefaultLookAndFeelDecorated(true); before the creation of such new instance of the frame for the Metal's (Java) L&F?
    Thanks again for al lthe help: this was, definetelly, something not obvious to figure out (or to find a hint on the net).
    Regards,

  • JTable on JPanel on JFrame, not appearing

    I can't see the JTable that I was expecting to between the two labels, any ideas why?
    public class Workout extends JFrame {
            final String[] exercisesDoneColumnNames = {"Exercise", "# Sets", "Set 1", "Set 2", "Set 3", "Set 4", "Set 5", "Set 6", "Set 7", "Set 8", "Set 9", "Set 10"};
            private ExercisesDoneTable myModel = new ExercisesDoneTable exercisesDoneColumnNames,0);
            private JTable table = new JTable(myModel);
            public Workout() {
                super.setTitle("Workout");
                buildExerciseDoneTable();
                Toolkit tk = Toolkit.getDefaultToolkit();
                Dimension d = new Dimension();
                d = tk.getScreenSize();
                setSize((int)d.getWidth(), (int)d.getHeight());
                setLocation(0,0);
                super.setName("Workout");
                addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent evt) {   
                        System.exit(0);
                JPanel p = new JPanel();
                p.setBackground(java.awt.Color.white);
                p.add(new JLabel("left of"));
                p.add(table);
                p.add(new JLabel("right of"));
                getContentPane().add(p);
                setVisible(true);
        //helper method just splits the code to make it more readable
        private void buildExerciseDoneTable(){
            table.setPreferredScrollableViewportSize(new Dimension(500,100));
            myModel.addTableModelListener(myModel);
            table.setVisible(true);
        }

    JPanel has a default FlowLayout.
    I think you table is there, but is not displaying anything as you have specified 0 rows when creating your table model. Change that number to 1 and you will see it appear.

  • JInternalFrame vs JFrame behaviour

    I have a tested JFrame with a set of swing components. This frame works fine, but when
    I used the code of the frame to create a JInternalFrame with the same components the
    lower part of the frame is not shown. The frame is cutted in the lower border.
    Thanks in advance.

    Did you use:
    internalFrame.pack();
    This makes sure the size of the frame is large
    enought to show all the components at their preferred
    sizes.In addition to that, verify that the JInternalFrame is not simply bigger than its JDesktopPane.

  • Shortcut in internalframe

    im making shortcut (jmenuBar method setAcceleratorKeyStroke.getKeyStroke(KeyEvent.VK_K,Event.CTRL_MASK)) )in internalframe
    and it notwork exactly how i want
    if i click to panel, or jmenuBar(they are on this internalframe )
    it not work
    whatis problem with this internalframe ?? on JFrame everything works ok but not hear

    Post a small demo program code that can reproduce your problem.

  • Drag and drop icons from onside of the split pane to the other side.

    Hello All,
    I am tring to write a program where i can drag and drop icons from the left side of the split pane to the right side. I have to draw a network on the right side of the split pane from the icons provided on the left side. Putting the icons on the labels donot work as i would like to drag multiple icons from the left side and drop them on the right side. CAn anyone please help me with this.
    Thanks in advance
    smitha

    The other option besides the drag_n_drop support
    http://java.sun.com/docs/books/tutorial/uiswing/dnd/intro.htmlis to make up something on your own. You could use a glasspane (see JRootPane api for overview) as mentioned in the tutorial.
    Here's another variation using an OverlayLayout. One advantage of this approach is that you can localize the overlay component and avoid some work.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class DragRx extends JComponent {
        JPanel rightComponent;
        BufferedImage image;
        Point loc = new Point();
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(image != null)
                g2.drawImage(image, loc.x, loc.y, this);
        public void setImage(BufferedImage image) {
            this.image = image;
            repaint();
        public void moveImage(int x, int y) {
            loc.setLocation(x, y);
            repaint();
        public void dropImage(Point p) {
            int w = image.getWidth();
            int h = image.getHeight();
            p = SwingUtilities.convertPoint(this, p, rightComponent);
            JLabel label = new JLabel(new ImageIcon(image));
            rightComponent.add(label);
            label.setBounds(p.x, p.y, w, h);
            setImage(null);
        private JPanel getContent(BufferedImage[] images) {
            JSplitPane splitPane = new JSplitPane();
            splitPane.setLeftComponent(getLeftComponent(images));
            splitPane.setRightComponent(getRightComponent());
            splitPane.setResizeWeight(0.5);
            splitPane.setDividerLocation(225);
            JPanel panel = new JPanel();
            OverlayLayout overlay = new OverlayLayout(panel);
            panel.setLayout(overlay);
            panel.add(this);
            panel.add(splitPane);
            return panel;
        private JPanel getLeftComponent(BufferedImage[] images) {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            for(int j = 0; j < images.length; j++) {
                gbc.gridwidth = (j%2 == 0) ? GridBagConstraints.RELATIVE
                                           : GridBagConstraints.REMAINDER;
                panel.add(new JLabel(new ImageIcon(images[j])), gbc);
            CopyDragHandler handler = new CopyDragHandler(panel, this);
            panel.addMouseListener(handler);
            panel.addMouseMotionListener(handler);
            return panel;
        private JPanel getRightComponent() {
            rightComponent = new JPanel(null);
            MouseInputAdapter mia = new MouseInputAdapter() {
                Component selectedComponent;
                Point offset = new Point();
                boolean dragging = false;
                public void mousePressed(MouseEvent e) {
                    Point p = e.getPoint();
                    for(Component c : rightComponent.getComponents()) {
                        Rectangle r = c.getBounds();
                        if(r.contains(p)) {
                            selectedComponent = c;
                            offset.x = p.x - r.x;
                            offset.y = p.y - r.y;
                            dragging = true;
                            break;
                public void mouseReleased(MouseEvent e) {
                    dragging = false;
                public void mouseDragged(MouseEvent e) {
                    if(dragging) {
                        int x = e.getX() - offset.x;
                        int y = e.getY() - offset.y;
                        selectedComponent.setLocation(x,y);
            rightComponent.addMouseListener(mia);
            rightComponent.addMouseMotionListener(mia);
            return rightComponent;
        public static void main(String[] args) throws IOException {
            String[] ids = { "-c---", "--g--", "---h-", "----t" };
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int j = 0; j < images.length; j++) {
                String path = "images/geek/geek" + ids[j] + ".gif";
                images[j] = ImageIO.read(new File(path));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new DragRx().getContent(images));
            f.setSize(500,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class CopyDragHandler extends MouseInputAdapter {
        JComponent source;
        DragRx target;
        JLabel selectedLabel;
        Point start;
        Point offset = new Point();
        boolean dragging = false;
        final int MIN_DIST = 5;
        public CopyDragHandler(JComponent c, DragRx dr) {
            source = c;
            target = dr;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            Component[] c = source.getComponents();
            for(int j = 0; j < c.length; j++) {
                Rectangle r = c[j].getBounds();
                if(r.contains(p) && c[j] instanceof JLabel) {
                    offset.x = p.x - r.x;
                    offset.y = p.y - r.y;
                    start = p;
                    selectedLabel = (JLabel)c[j];
                    break;
        public void mouseReleased(MouseEvent e) {
            if(dragging && selectedLabel != null) {
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                target.dropImage(new Point(x,y));
            selectedLabel = null;
            dragging = false;
        public void mouseDragged(MouseEvent e) {
            Point p = e.getPoint();
            if(!dragging && selectedLabel != null
                         && p.distance(start) > MIN_DIST) {
                dragging = true;
                copyAndSend();
            if(dragging) {
                int x = p.x - offset.x;
                int y = p.y - offset.y;
                target.moveImage(x, y);
        private void copyAndSend() {
            ImageIcon icon = (ImageIcon)selectedLabel.getIcon();
            BufferedImage image = copy((BufferedImage)icon.getImage());
            target.setImage(image);
        private BufferedImage copy(BufferedImage src) {
            int w = src.getWidth();
            int h = src.getHeight();
            BufferedImage dst =
                source.getGraphicsConfiguration().createCompatibleImage(w,h);
            Graphics2D g2 = dst.createGraphics();
            g2.drawImage(src,0,0,source);
            g2.dispose();
            return dst;
    }geek images from
    http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html

  • How can I split long words to feet the line in JEditorPane

    Hi,
    Can someone help me ?
    I'm trying to write long words in JEditorPane,
    and I want the JEditorPane to split them, so it will feet the line...
    (something like word wrapping in JTExtArea).
    How can I fix my code so it will work?
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.html.*;
    public class Testing extends JFrame {
        public Testing() {
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-210)/2, (screenSize.height-200)/2, 210, 200);
            editorPane = new JEditorPane();
            HTMLEditorKit kit = new HTMLEditorKit();
            editorPane.setEditorKit( kit );
            HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
            editorPane.setDocument( doc );
            editorPane.setEditable(false); // or true
            String htmlText =
                    "<html>"
                    +"<body>"
                    +"How can I use word wrapping with html JEditorPane?"
                    +"<br>How can I split the next long word, so it will feet the line?"
                    +"<br>loooooooooooooooooooooooooooooooooooooooong"
                    +"</body>"
                    +"</html>";
            try {
                kit.insertHTML(doc, editorPane.getCaretPosition(), htmlText.substring(6) + "<br>", 0, 0, HTML.Tag.HTML);
            catch( Exception exp ) {
                exp.printStackTrace();
            getContentPane().add(editorPane, BorderLayout.CENTER);
        public static void main(String args[]) {
            new Testing().setVisible(true);
        private JEditorPane editorPane;
    }Thanks,
    Maoz

    Sorry forget about paragraph view.
    Here the new code.
    regards,
    Stas
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.html.*;
    import javax.swing.text.*;
    public class Test extends JFrame
        public Test()
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-210)/2, (screenSize.height-200)/2, 210, 200);
            editorPane = new JEditorPane();
            MyHTMLEditorKit kit = new MyHTMLEditorKit();
            editorPane.setEditorKit( kit );
            HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
            editorPane.setDocument( doc );
    //        editorPane.setEditable(false); // or true
            String htmlText =
                "<html>"
                +"<body>"
                +"<br>How can I split the next long word, so it will feet the line?"
                +"<br>loooooooooooooooooooooooooooooooooooooooong"
                +"</body>"
                +"</html>";
            try
                 kit.insertHTML(doc, editorPane.getCaretPosition(), htmlText.substring(6) + "<br>", 0, 0, HTML.Tag.HTML);
            catch( Exception exp )
                exp.printStackTrace();
            getContentPane().add(new JScrollPane(editorPane), BorderLayout.CENTER);
        public static void main(String args[])
            new Test().setVisible(true);
        private JEditorPane editorPane;
    class MyHTMLEditorKit extends HTMLEditorKit
        private static final ViewFactory defaultFactory = new MyViewFactory ();
        public ViewFactory getViewFactory()
             return defaultFactory;
        static class MyViewFactory extends HTMLFactory
            public View create(Element elem)
                View v=super.create(elem);
                if (v instanceof InlineView )
                    return new LabelView(elem);
                else if (v instanceof javax.swing.text.html.ParagraphView) {
                    return new MyParagraphView(elem);
                return v;
        static class MyParagraphView extends javax.swing.text.html.ParagraphView {
            public MyParagraphView(Element elem) {
                super(elem);
            protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
                if (r == null) {
                    r = new SizeRequirements();
                float pref = layoutPool.getPreferredSpan(axis);
                float min = layoutPool.getMinimumSpan(axis);
                // Don't include insets, Box.getXXXSpan will include them.
                r.minimum = (int)min;
                r.preferred = Math.max(r.minimum, (int) pref);
                r.maximum = Short.MAX_VALUE;
                r.alignment = 0.5f;
                return r;
    }

Maybe you are looking for