JSplitPane with JFrame

Hi All,
I have a JSplitPane on which left Component is JTree and right component is multiple mini JFrames...So after adding frames on the right side i am able to drag tha frame whereever i want..If i want to restrict it only into the right window available..How can i do that??
Thanks in advance.
regards,
Viswanadh

Ya Camic...I got an example when i searched in google...Here it is.
import javax.swing.*; 
public class DTopTest extends JFrame { 
    public static void main( String[] arg ) { 
        new DTopTest(); 
    public DTopTest() { 
        JDesktopPane desktop = new JDesktopPane(); 
        setContentPane( desktop ); 
        JInternalFrame top = new JInternalFrame( "Top" ); 
        top.setBounds( 10, 10, 200, 200 ); 
        top.setVisible( true ); 
        desktop.add( top, new Integer( 10 ) ); 
        JInternalFrame normal1 = new JInternalFrame( "Normal 1" ); 
        normal1.setBounds( 100, 100, 300, 300 ); 
        normal1.setVisible( true ); 
        desktop.add( normal1 ); 
        JInternalFrame normal2 = new JInternalFrame( "Normal 2" ); 
        normal2.setBounds( 300, 300, 300, 300 ); 
        normal2.setVisible( true ); 
        desktop.add( normal2 ); 
        setDefaultCloseOperation( EXIT_ON_CLOSE ); 
        setSize( 500, 500 ); 
        setVisible( true ); 
    private class TopFrame extends JInternalFrame { 
        TopFrame( String title ) { 
            super( title ); 
        public boolean isSelected() { 
            return true; 
}  In this example InternalFrames are added to Main frame with the help of JDesktopPane..My question is apart from me adding JInternalFrames i will be adding some textfields or labels on the same..So i require GridLayout to be enabled for the container,but JDesktopPane doesnt support either
setLayout(new GridLayout(0,1,5,5));
or
JDesktopPane jdp=new JDesktopPane() //argument as GridLayout.So i just wanna know how to do this??
Thanks in advance.
regards,
Viswanadh

Similar Messages

  • Problem with JFrame, it goes blank

    i
    My problem is with JFrame, when it's carrying operation which takes a bit of time, if somethhing goes on
    top of the frame the frame goes blank, all the components vanished and when the operation is completed the components bacome visible. I dont know why this is happening,. The code is below, since my code is very complicated I am sending some code whcih shows the problem I have, when you press the button it execute's a for loop, whcih takes some time. If you minimize the frame and maximize again, you'll see what I mean.
    Please help!!!
    Many Thanks
    Lilylay
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Frame1 extends JFrame {
    JPanel contentPane;
    JButton jButton2 = new JButton();
    /**Construct the frame*/
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(null);
    this.setSize(new Dimension(407, 289));
    this.setTitle("Frame Title");
    contentPane.setBackground(SystemColor.text);
    contentPane.setForeground(Color.lightGray);
    jButton2.setText("Press me!");
    jButton2.setBounds(new Rectangle(107, 111, 143, 48));
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    jButton2_mousePressed(e);
    contentPane.add(jButton2, null);
    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton2_mousePressed(MouseEvent e) {
    for(int i=0; i<256898; i++){
    for(int j=0; j<5656585; j++){
    System.out.println("hello");
    public static void main(String [] args){
    Frame1 frame=new Frame1();
    frame.show();
    }

    The reason this is happening is because your loop is so intensive that your program doesn't have time to refresh its JFrame. There is no great way to get past this stumbling block without decreasing the efficiency of your code. One possible solution is to call repaint() from within your loop, but of course this slows down your loop.
    Hope that helps

  • Problem with JFrame's dispose();

    Hello everyone,
    I'm having a problem with JFrame's dispose() method. In my program I have 2 classes which go into full screen. On each screen there is a button to switch to the other screen. The first time I push the button on both of them the other screen closes, which is what I want. However, if I push the same button more than twice - like by going from Screen1 to Screen2 and Screen2 to Screen1 and then Screen1 to Screen2 - I get 2 screens. If I keep doing that I eventually get 10+ screens up, which is bad. How do I prevent that?

    There's a lot of code, so I'll just post up the part that does it.
    backButton.addActionListener(new ActionListener()
                  public void actionPerformed(ActionEvent e)
                      soundManagerM.close();
                        new MenuScreen().setVisible(true);
                        dispose();
             });I don't think it opens up 2 at once, because it would play multiple music right?

  • All is fine with JFrame, but the same code doesn't work in JApplet?

    I try to manage XML files using Xerces-perser,
    and all is ok if I work with JFrame,
    but when I try to do the same thing in JApplet,
    I get ClassDefNotFound error at the initializing
    of applet. It writes that the problem is with
    Xerces-classes (org.w3c.dom.Node f.e.),
    it seems to me that "appletviewer" (1.3.01) which
    I use to launch JApplet doesn't see these classes,
    while "java" does when I do the same with JFrame.
    May be, do you have some ideas?

    add "crimson.jar" and "jaxp.jar" in your archive list in your html, which lunch your applet.

  • 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);
    }

  • JSplitPane with external panel

    Hi,
    I want to use a JSplitPane wich:
    Displays a JTree in the left-component
    Displays application selected from JTree in right-component
    Sounds simple. The right-component has a 'card-deck' which will
    swap whenever an other application is selected in the JTree.
    I have written a short test which does almost exactly what I want.
    Problem is that a panel, which was a standalone Frame-app first,
    is not shown in the right-component (but it is running!)
    It seems that cannot put a standalone application (extending a JFrame) on a component.
    So I decided to change the application and use a JPanel in stead
    of a JFrame. The panel is accepted but isn't shown. (application is
    running though).
    I created a short testpanel_class which should be shown when
    the first app is selected from JTree.
    Current Result when JSplitPane-app is started
    ==> I get the 'home'-card first
    ==> When App2 is selected, I get correct card
    ==> When App1 is selected, the right-component is blank (app runs!)
    Herewith the codesnippet of my JSplitPane-app which is showing
    how I put the components on the left/right components:
    ===================================================
         private JSplitPane getJSplitPane() {
              if (jSplitPane == null) {
                   jLabel = new JLabel("Tekst");
                   jSplitPane = new JSplitPane();
                   jSplitPane.setLeftComponent(getJTree());               
                   myPanel.setLayout(new BorderLayout());
                   pCards.setLayout(cardlayout);
                   pCards.add("home", new JLabel("Home"));
                   pCards.add("App1", new SplitBasePanel());
                   pCards.add("App2", new JLabel("Menu2 Selected"));
                   myPanel.add(pCards, BorderLayout.CENTER);
                   myApp.getViewport().add(myPanel);
                   jSplitPane.setRightComponent(myApp);
              return jSplitPane;
    ===================================================
    And I swap the cards as follows:
    ===================================================
         public void valueChanged(TreeSelectionEvent event) {
              if (!firstRun){
    System.out.println
    ("Current Selection: " +
    jTree.getLastSelectedPathComponent().toString());
    if ((jTree.getLastSelectedPathComponent().toString()).equals("App 1")){
                   cardlayout.show(pCards, "App1");
    if ((jTree.getLastSelectedPathComponent().toString()).equals("App 2")){
                   cardlayout.show(pCards, "App2");
              firstRun = false;
    ======================================================
    Here is my application-panel to be shown
    =================================
    package application;
    import javax.swing.*;
    import java.awt.*;
    public class SplitBasePanel
         extends JPanel {
         // Panel Layout
         private JPanel c = new JPanel();
         // APPLICATION BASE FRAME
         public SplitBasePanel() {
         // Create Application panel
         c.setLayout(new BorderLayout());
         // Initialize CardDeck with basepanels
         c.add(new JLabel("my External Application"), BorderLayout.CENTER);
    }

    a) Sorry for the "code"-formatting, i just copy & paste from my developersoft.
    b) SSCCE ????
    c) I have placed this in this forum because it is not only a question about usage of swing components but also about the concept I try to implement. Maybe what I'm trying to do is just not the right concept !
    d) what do you mean by your final remark (history reply postings)?
    I do not make daily usage of this Developer Forums. So please forgive me when I don't follow the rules completely. I will post the message again in the SWING-forum and try to use the correct formatting.
    Patrick.

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    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.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • 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. :)

  • Problem with JFrame and JPanel

    Okay, well I'm busy doing a lodge management program for a project and I have programmed this JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FinalTest extends JFrame
         public JPanel contentPane;
         public JImagePanel imgPanel;
         private JLabel[] cottageIcon;
         private boolean keepMoving;
         private int selectedCottage;
         public FinalTest()
              super();
              initializeComponent();
              addActionListeners();
              this.setVisible(true);
         private void initializeComponent()
              contentPane = (JPanel)getContentPane();
              contentPane.setLayout(null);
              imgPanel = new JImagePanel("back.png");
               imgPanel.setLayout(null);
              imgPanel.setBackground(new Color(1, 0, 0));
                   addComponent(contentPane, imgPanel, 10,10,imgPanel.getImageWidth(),imgPanel.getImageHeight());
              cottageIcon = new JLabel[6];
              keepMoving = true;
              selectedCottage = 0;
              cottageIcon[0] =  new JLabel();
              //This component will never be added or shown, but needs to be there to cover for no cottage selected
              for(int a = 1; a < cottageIcon.length; a++)
                   cottageIcon[a] = new JLabel("C" + (a));
                   cottageIcon[a].setBackground(new Color(255, 0, 0));
                    cottageIcon[a].setHorizontalAlignment(SwingConstants.CENTER);
                    cottageIcon[a].setHorizontalTextPosition(SwingConstants.LEADING);
                    cottageIcon[a].setForeground(new Color(255, 255, 255));
                    cottageIcon[a].setOpaque(true);
                    addComponent(imgPanel,cottageIcon[a],12,(a-1)*35 + 12,30,30);
                this.setTitle("Cottage Chooser");
                this.setLocationRelativeTo(null);
              this.setSize(new Dimension(540, 430));
         private void addActionListeners()
              imgPanel.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        imgPanel_mousePressed(e);
                   public void mouseReleased(MouseEvent e)
                        imgPanel_mouseReleased(e);
                   public void mouseEntered(MouseEvent e)
                        imgPanel_mouseEntered(e);
              imgPanel.addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseDragged(MouseEvent e)
                        imgPanel_mouseDragged(e);
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         private void imgPanel_mousePressed(MouseEvent e)
              for(int a = 1; a < cottageIcon.length; a++)
                   if(withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()))
                        System.out.println("B" + withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()));
                        selectedCottage = a;
                        keepMoving = true;
         private void imgPanel_mouseReleased(MouseEvent e)
              System.out.println("called");
              selectedCottage = 0;
              keepMoving = false;
         private void imgPanel_mouseDragged(MouseEvent e)
               System.out.println("XXX" + Math.random() * 100);
              if(keepMoving)
                   int x = e.getX();
                    int y = e.getY();
                    if(selectedCottage!= 0)
                         cottageIcon[selectedCottage].setBounds(x-(30/2),y-(30/2),30,30);
                    if(!legalBounds(imgPanel,cottageIcon[selectedCottage]))
                        keepMoving = false;
                        cottageIcon[selectedCottage].setBounds(imgPanel.getWidth()/2,imgPanel.getHeight()/2,30,30);
              System.out.println(cottageIcon[selectedCottage].getBounds());
         private void imgPanel_mouseEntered(MouseEvent e)
               System.out.println("entered");
         private void but1_actionPerformed(ActionEvent e)
              String input = JOptionPane.showInputDialog(null,"Enter selected cottage");
              selectedCottage = Integer.parseInt(input) - 1;
         public boolean legalBounds(Component containerComponent, Component subComponent)
              int contWidth = containerComponent.getWidth();
              int contHeight = containerComponent.getHeight();
              int subComponentX = subComponent.getX();
              int subComponentY = subComponent.getY();
              int subComponentWidth = subComponent.getWidth();
              int subComponentHeight = subComponent.getHeight();
              if((subComponentX < 0) || (subComponentY < 0) || (subComponentX > contWidth) || (subComponentY > contHeight))
                   return false;
              return true;
         public boolean withinBounds(int mouseX, int mouseY, Rectangle componentRectangle)
              int componentX = (int)componentRectangle.getX();
              int componentY = (int)componentRectangle.getY();
              int componentHeight = (int)componentRectangle.getHeight();
              int componentWidth = (int)componentRectangle.getWidth();
              if((mouseX >= componentX) && (mouseX <= (componentX + componentWidth)) && (mouseY >= componentY) && (mouseY <= (componentY + componentWidth)))
                   return true;
              return false;
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              FinalTest ft = new FinalTest();
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class JImagePanel extends JPanel
      private Image image;
      public JImagePanel(String imgFileName)
           image = new ImageIcon(imgFileName).getImage();
        setLayout(null);
      public void paintComponent(Graphics g)
        g.drawImage(image, 0, 0, null);
      public Dimension getImageSize()
                Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
             return size;
      public int getImageWidth()
                int width = image.getWidth(null);
                return width;
      public int getImageHeight()
              int height = image.getHeight(null);
              return height;
    }Now the problem I'm having is changing that class to a JFrame, it seems simple but I keep having problems like when it runs from another JFrame nothing pops up. I can do it like this:
    FinalTest ft = new FinalTest();
    ft.setVisible(false);
    JPanel example = ft.contentPanehowever I will probably be marked down on this for bad code. I'm not asking for the work to be done for me, but I'm really stuck on this and just need some pointers so I can carry on with the project. Thanks,
    Steve

    CeciNEstPasUnProgrammeur wrote:
    I'd actually consider your GUI being a JPanel instead of a JFrame quite good design - makes it easy to put the stuff into an applet when necessary...
    Anyway, you should set setVisible() to true to make it appear, not to false. Otherwise, I don't seem to understand your problem.That is actually my problem. I am trying to convert this JFrame to a JPanel

  • Problem with JFrame , please help !

    hello , all !
    I define a JFrame1 as ancestor
    I set the JFrame's contentPane Layout to borderLayout ,
    and add some component in south , north , and add a menu , in its constructor
    then I define a new JFrame2 inherit from JFrame1, I also add a Jpanel component
    to contentPane center in its constructor !
    but something a wrong , I can't see the Jpanel , only see the components which add in JFrame1?
    this is why ?
    thanks
    /* source code */
    public class JFrame1{
    public JFrame1(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(borderLayout1);
    statusBar.setBorder(BorderFactory.createEtchedBorder());
    statusBar.setText("Hello , Young follow! ");
    contentPane.add(statusBar, BorderLayout.SOUTH);
    toolbar = new Toolbar_DataEntry(this);
    contentPane.add(toolbar, BorderLayout.NORTH);
    menubar = new Menu_DataEntry(this);
    this.setJMenuBar(menubar);
    public class JFrame2 extends JFrame1 {
    public JFrame2() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    JPanel bodyPane = new JPanel();
    bodyPane.setDataModule(queryDataSet1);
    queryDataSet1.Opendatabase();
    bodyPane.setBorder(null);
    this.setTitle("Frame Title");
    bodyPane.setBounds(new Rectangle(4, 5, 427, 114));
    contentPane.setPreferredSize(bodyPane.getPreferredSize());
    contentPane.setMinimumSize(bodyPane.getMinimumSize());
    Frame_Resize();

    The problem is that the constructor for JFrame2 does not automatically call the constructor for JFrame1. Therefore the JFrame1 constructor never gets called.
    You must do this yourself with the super() method.
    public JFrame2() {
    super();
    try {
    jbinit();
    catch( Exception e )
    e.printStackTrace();
    Remember that this rule applies to all descendent classes.

  • Problem with JFrame

    I can't get rid of the previous frame I have used, when I create a new frame with added data the previous frame overlaps with the new frame and it all gets a bit messy !

    My fault I think I worded it wrong.
    basically I have a JFrame with many components in it, when a client clicks on one of the Jlists items and presses select I get the item from the Jlist and pass it to a private variable. now what I want to do is scrap this JFrame and produce an identical one but with the JList next to the previous one filled in with the data which is dependant on the choice just made !
    i am sure i am doing something wrong ! maybe JPanels not JFrames?

  • Problem with JFrame.setUndecorated(true)

    I am using a L&F that overrides the JFrame's default title bar, which requires that the following methods are called before showing my main gui.
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);after gui is shown, i have a process that pops up a new JFrame with a progress bar, with a splash screen feel (no title bar), but ever since i called the above methods, i cant get the title bar to go away.
    JFrame frame = new JFrame("go away");
    frame.setUndecorated(true);how can i have my cake and eat it too? (draw main gui with new title bar L&F, then show splash/progress without title bar)
    thanks,
    mark

    I don't play with the default LAF but have you tried something like:
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame(...)
    frame.setVisible(true);
    JFrame.setDefaultLookAndFeelDecorated(false);
    JDialog.setDefaultLookAndFeelDecorated(false);
    Show your splash screen here
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);

  • Problem with JFrame updating

    I'm having trouble making this application remove the "Client 1: 127.0.0.1 [localhost]" (and Client 2: or how ever many are connected) from a Box inside of a JPanel inside of a JFrame...
    I searched around a bit, but nothing fixed my problem. (SwingUtilities.invokeLater(new Runnable() etc is from another post, but with or without it I can't get it to work...)
    Running Fedora Core 2, JDK 1.4.2_04.
    Thanks in advance.
    (Hrmm, I had to mess with some of the longer lines to get them to display correctly...)
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class PennyServer extends JFrame implements ActionListener
         private Boolean finished;
         private Border border;
         private Box clientBox;
         private BoxLayout boxlayout;
         private Container content;
         private Dimension size;
         private JButton button;
         private JPanel buttonList;
         private JPanel clientList;
         private LinkedList llClient, llInput, llOutput;
         PennyServer()
              setBounds(100, 100, 400, 400);
    //          setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              setTitle("Test Server - by Joshua");
              content = getContentPane();
              border = BorderFactory.createRaisedBevelBorder();
              boxlayout = new BoxLayout(content, BoxLayout.Y_AXIS);
              clientBox = Box.createVerticalBox();
              size = new Dimension(80, 20);
              clientList = new JPanel(new BorderLayout());
              buttonList = new JPanel();
              content.setLayout(boxlayout);
              clientList.setBorder(new TitledBorder(new EtchedBorder(), "Client List"));
              clientList.add(clientBox, BorderLayout.CENTER);
              buttonList.add(button = new JButton("Start"));
              button.setBorder(border);
              button.setPreferredSize(size);
              button.addActionListener(this);
              buttonList.add(button = new JButton("Quit"));
              button.setBorder(border);
              button.setPreferredSize(size);
              button.addActionListener(this);
              buttonList.setBorder(
                   new CompoundBorder(
                        BorderFactory.createLineBorder(Color.black, 1),
                        BorderFactory.createBevelBorder(BevelBorder.RAISED)
              content.add(clientList);
              content.add(buttonList);
              setVisible(true);
              finished = new Boolean(false);
              llClient = new LinkedList();
              llInput = new LinkedList();
              llOutput = new LinkedList();
         public void addClient(Socket s)
              try
                   s.setSoTimeout(0100);
                   s.setTcpNoDelay(true);
                   llClient.addLast(s);
                   llInput.addLast(
                        new BufferedReader(
                             new InputStreamReader(
                                  s.getInputStream()
                   llOutput.addLast(new PrintStream(s.getOutputStream()));
              catch (Exception e)
                   System.out.println ("<" + e + ">");
              SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        refreshClientList();
         public void refreshClientList()
              InetAddress addr;
              ListIterator iter = llClient.listIterator(0);
              clientBox.removeAll();
              clientBox.add(Box.createVerticalStrut(20));
              while(iter.hasNext())
                   addr = ((Socket) iter.next()).getInetAddress();
    System.out.println (
         "Debug:  refreshClientList():  adding client " +
         (iter.previousIndex() + 1)
                   // This is not going away on the display...
                   clientBox.add(
                        new JLabel(
                             "Client " + (iter.previousIndex() + 1) + ": " +
                             addr.getHostAddress() + " [" + addr.getHostName() + "]"
                   if (iter.hasNext())
                        clientBox.add(Box.createVerticalStrut(20));
              clientBox.revalidate();
         public void select()
              BufferedReader in;
              ListIterator iterClient = llClient.listIterator(0);
              ListIterator iterInput = llInput.listIterator(0);
              ListIterator iterOutput = llOutput.listIterator(0);
              PrintStream out;
              Socket s;
              String userInput;
              while(iterClient.hasNext() && iterInput.hasNext() && iterOutput.hasNext())
                   s = (Socket) iterClient.next();
                   in = (BufferedReader) iterInput.next();
                   out = (PrintStream) iterOutput.next();
                   try
                        userInput = in.readLine();
                        if (userInput == null)
                             System.out.println (
                                  "Client " + (iterClient.previousIndex() + 1) +
                                  " has disconnected from the server."
                             iterClient.remove();
                             iterInput.remove();
                             iterOutput.remove();
                             SwingUtilities.invokeLater(new Runnable()
                                  public void run()
                                       refreshClientList();
                             continue;
                        System.out.println (
                             "Client " + (iterClient.previousIndex() + 1) +
                             ": " + userInput
                   catch (SocketTimeoutException e)
                   {}  // Do nothing, 100 millisecond time expired
                   catch (Exception e)
                        System.out.println ("<" + e + ">");
                   userInput = null;
         public boolean alive()
              return (!(finished.booleanValue()));
         public static void main (String[] args)
              try
                   PennyServer penny = new PennyServer();
                   ServerSocket ss;
                   Socket client;
                   ss = new ServerSocket(1234);  // Start a listening socket on port 1234
                   ss.setReuseAddress(true);  // Reuse local address/port combonation
                   ss.setSoTimeout(0100);  // 100 milliseconds, to simulate nonblocking IO
                   while(penny.alive())
                        penny.select();  // Poll sockets for input
                        try
                             penny.addClient(client = ss.accept());
                        catch (SocketTimeoutException e)
                        {}  // Do nothing, 100 millisecond time expired
                   penny.dispose();
                   ss.close();
              catch (Exception e)
                   System.out.println ("<" + e + ">");
         public void actionPerformed(ActionEvent event)
              if (event.getActionCommand().equals("Start"))
              else if (event.getActionCommand().equals("Quit"))
                   finished = new Boolean(true);
    }Joshua

    Ahha! Thank you, sjl. It works perfectly now.
    I thought it would be something silly, but I couldn't for the life of me figure out what.
    Joshua

  • Problem with JFrame class.

    To risolve my problem i need for few diferent frame
    ( for esample in one i put JTextFild that take the user input, in a nother one i need for program output ) . But, th problem is, all my frames using the same object.
    If i construct diferent JFrame window class i have problem that i don't acess in the same object from all the window. And if i dont use a object, i have static acess .
    I risolve the problem with 1 JFrame class with diferent constructors, but i wont a diferent way to risolve my problem, because there are few windows.
    Help me.....

    Make the class that extends JFrame an inner class of the the main class. You can then access all members of the outer class.

Maybe you are looking for

  • How long does it take to format a seagate 1 TB hard drive for usage on both the PC and Mac?

    We just bought a Seagate 1TB hard drive, and we are are trying to formatting it for use on both the PC and Mac.  It seem to take forever, we ran it last night at 9pm and it still running.  This is normal.  How long does it mormally takes?  And advise

  • Installing Flash Player... Please Help

    Hi, I continue to have difficulty installing flash player on my computer and am out of ideas.  I'm running Windows 7 on my computer and have tried installing flash player for both Internet explorer version 9 and firefox version 10.0.2.  In both situa

  • My iphone 5 is bent

    I see a lot of people have this issue. What are the answers from Apple when you complain about this? I was one of the first ones to get one. It is a white 64GB and it has been in my purse or in a flat surface all of the time, unless in my hands. It h

  • SATSA smartcards

    Hi all, I have developed an application using the JSR177 in order to generate a CSR and to sign some content from a WIM/PKCS#15 smartcard. My code works right fine in the emulator (Sun Java Wireless Toolkit 2.5 Beta and cref as the smartcard emulator

  • Quicktime player opens behind browser window

    I have have a webpage that has several quicktime movies, each one is linked to another quicktime movie that opens a rtsp stream which is located in a password protected directory (using htaccess). When a movie is clicked a password dialog box opens,