JTabbedPane with JTextField

Can anyone provide me with an example on how to incorporate a JTextField into a JTabbedPane? There are many examples of creating JButtons as components of a JTabbedPanes but nothing for JTextFields. Can this be done? I get some wierd compiler errors when I try it?
Any help will be much appreciated. Thanks.

Thanks for the quick response but...
My question was "how to incorporate these fields into a JTabbedPane."
I'm new to Java so I have "borrowed" a Sun Tutorial JTabbedPane example which includes one JLable component per tab and tried to add a JTextField.
Here is "my" code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TabbedPaneDemo extends JFrame {
// Initialize Screen Text Fields
private JTextField lastName = null;
//Vector recordData = new Vector(20);
public TabbedPaneDemo() {
ImageIcon icon = new ImageIcon("images/middle.gif");
JTabbedPane tabbedPane = new JTabbedPane();
Component panel1 = makeRecordPanel("Teacher Record");
tabbedPane.addTab("Teacher", icon, panel1, "Update Teacher Information");
tabbedPane.setSelectedIndex(0);
Component panel2 = makeRecordPanel("Parent Record");
tabbedPane.addTab("Parent", icon, panel2, "Update Parent Information");
Component panel3 = makeRecordPanel("Child Record");
tabbedPane.addTab("Child", icon, panel3, "Update Child Information");
//Add the tabbed pane to this panel.
setLayout(new GridLayout(1, 1));
add(tabbedPane);
protected Component makeRecordPanel(String text) {
JPanel panel = new JPanel(false);
JLabel label1 = new JLabel("Last Name");
JTextField lastName = new JTextField(20);
label1.setHorizontalAlignment(JLabel.LEFT);
panel.setLayout(new GridLayout(1, 1));
panel.add(label1);
panel.add(lastName);
return panel;
public static void main(String[] args) {
JFrame frame = new JFrame("Maintain DayCare Records");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
frame.getContentPane().add(new TabbedPaneDemo(),
BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setVisible(true);
This compiles OK but when I try to run it I get the following run-time errors.
java.lang.Error: Do not use TabbedPaneDemo.setLayout() use TabbedPaneDemo.getContentPane().setLayout() instead
     at javax.swing.JFrame.createRootPaneException(JFrame.java:333)
     at javax.swing.JFrame.setLayout(JFrame.java:394)
     at TabbedPaneDemo.<init>(TabbedPaneDemo.java:29)
     at TabbedPaneDemo.main(TabbedPaneDemo.java:53)
Any thoughts?

Similar Messages

  • JTabbedpane with JRadiobutton?

    I have a JTabbedpane with 2 tabs (tab1, tab2).
    I have 2 radiobutton (JRadioButton).
    So for now, i want to when i click on radiobutton1 it will be show tab1
    when i click on radiobutton2 it will be show tab2.
    Here is my source code, please help me to slove it:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    public class JTablePaneTest extends JFrame implements ActionListener{
    private JTabbedPane pane;
    private JRadioButton radioButton1 = new JRadioButton("Radiobutton1", true);
    private JRadioButton radioButton2 = new JRadioButton("Radiobutton2", false);
    JPanel radioPanel =null;
    public JTablePaneTest() {
    super("TEST");
    this.setLayout(new BorderLayout());
    this.setSize(new Dimension(300,300));
    this.getContentPane().add(this.getAllRadioButton(), BorderLayout.SOUTH);
    this.getContentPane().add(this.getPane(), BorderLayout.CENTER);
    this.pack();
    this.setVisible(true);
    private JPanel getAllRadioButton(){
    if(radioPanel==null){
    radioPanel = new JPanel();
    radioPanel.setLayout(new FlowLayout());
    radioPanel.setBorder(BorderFactory.createEmptyBorder());
    ButtonGroup bg = new ButtonGroup();
    bg.add(radioButton1);
    bg.add(radioButton2);
    radioPanel.add(radioButton1);
    radioPanel.add(radioButton2);
    return radioPanel;
    private JTabbedPane getPane(){
    if(pane == null){
    pane = new JTabbedPane();
    pane.addTab("Tab1", null, panel1(), "Tab1");
    pane.addTab("Tab2", null, panel2(), "Tab2");
    return pane;
    private JPanel panel1(){
    JPanel panel1 = new JPanel();
    panel1.setLayout(new GridBagLayout());
    panel1.add(new JButton("TEST1"));
    return panel1;
    private JPanel panel2(){
    JPanel panel2 = new JPanel();
    panel2.setLayout(new GridBagLayout());
    panel2.add(new JTextField(12));
    return panel2;
    public static void main(String[] args) {
    new JTablePaneTest();
    @Override
    public void actionPerformed(ActionEvent e) {
    if(e.getSource() == radioButton1){
    //show tab1
    if(e.getSource() == radioButton2){
    //show tab2
    }Thanks you very much.
    Edited by: ecard104 on Sep 1, 2008 10:01 AM

    ecard104 wrote:
    can you tell me the method you want to say?I'd prefer to have you look at the API and the tutorial. It would be better for you in the long run. It's spelled out in the tutorial.
    [http://java.sun.com/docs/books/tutorial/uiswing/components/tabbedpane.html]
    [http://java.sun.com/javase/6/docs/api/javax/swing/JTabbedPane.html]
    Edited by: Encephalopathic on Sep 1, 2008 10:17 AM

  • Memory problem with JTextFields

    Hello,
    I have a wierd problem with JTextField and the memory.
    I need to fill a JPanel with different Components (including JTextFields), then do some calculation, remove the Components and filling the JPanel again.
    When i so this too often my i get an OutOfMemory Exception. I narrowed to problem down and wrote a small sample program to demonstrate the problem.
    When i call the method doIT (where the Panel is repeatedly filled) from the main-function everything works fine, but when it is called as a result from the GUI-Button-Event the memory for the JTextFields is not freed (even the call of the Garbage collector changes nothing)
    When i only use JButtons to fill the Panel everything works fine.
    Has anyone an idea why this problem occurs and how i can work around it?
    [Edit] I tested it whith java 1.5.0_06, 1.5.0_11, 1.6.0_02
    Thanks
    Marc
    import java.awt.Frame;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.management.ManagementFactory;
    import java.lang.management.MemoryUsage;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class MemoryTestDLG extends JDialog {
         public MemoryTestDLG(Frame owner) {
              // create Dialog with one Button that calls the testMethod
              super(owner);
              JButton b = new JButton("doIT ...");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doIT();
                        setVisible(false);
              getContentPane().add(b);
              pack();
         public void doIT() {
              // Testmethod that fills a JPanel 20 times with Components and clears it
              // again
              JPanel p = new JPanel();
              long memUse1 = 0;
              long memUse2 = 0;
              long memUseTemp = 0;
              for (int count = 0; count < 20; count++) {
                   // Clear the panel
                   p.removeAll();
                   // Get memory usage before the task
                   Runtime.getRuntime().gc();
                   memUse1 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // Fill Panel with components
                   for (int i = 0; i < 200; i++) {
                        // The Buttons seem to be released without any problem
                        p.add(new JButton("test" + Math.random()));
                        // JTextFields are not released when used from the dialog.
                        p.add(new JTextField("test " + Math.random()));
                   // get memory usage after the task
                   Runtime.getRuntime().gc();
                   memUseTemp = memUse2;
                   memUse2 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // print Memory results
                   System.out.println("Memory Usage: " + f(memUse1) + "   ->"
                             + f(memUse2) + " [ Used:" + f(memUse2 - memUse1)
                             + " ] [ Freed: " + f(memUseTemp - memUse1) + "]");
         public String f(long m) // formats the output
              String s = "" + m;
              while (s.length() < 8)
                   s = " " + s;
              return s;
         public static void main(String[] args) {
              MemoryTestDLG d = new MemoryTestDLG(null);
              System.out
                        .println("------------------ Direct Call (all is OK) -------------------");
              d.doIT(); // Memory is freed with every call to JPanel.removeAll()
              System.out
                        .println("------------ Call from Dialog (memory is not freed) -------------");
              // The Memory keeps blocked
              d.setModal(true);
              d.setVisible(true);
              System.exit(0);
    }Message was edited by:
    marcvomorc

    Thank you for your answer,
    In this sample the programm does not run out of memory. But when you look at the output you see, that in the first run (direct call) the memory ist freed immediately when tha panel is cleared but in the second run (from the Button) the memory usage is getting bigger and bigger. Wenn you change the number of components to 2000 (4000)
    // Fill Panel with components
            for (int i = 0; i < 2000; i++) {
                // The Buttons seem to be released without any problem
    //... ...and use the default memory settings (69mb heap) the programm runns out of memory.
    I get the following output:
    ------------------ Direct Call (all is OK) -------------------
    Memory Usage:   445504   -> 8121016 [ Used: 7675512 ] [ Freed:  -445504]
    Memory Usage:   617352   -> 8114336 [ Used: 7496984 ] [ Freed:  7503664]
    Memory Usage:   810488   -> 8491768 [ Used: 7681280 ] [ Freed:  7303848]
    Memory Usage:   943704   -> 8114976 [ Used: 7171272 ] [ Freed:  7548064]
    Memory Usage:   836760   -> 8505072 [ Used: 7668312 ] [ Freed:  7278216]
    Memory Usage:   978352   -> 8114784 [ Used: 7136432 ] [ Freed:  7526720]
    Memory Usage:   835552   -> 8498288 [ Used: 7662736 ] [ Freed:  7279232]
    Memory Usage:   977096   -> 8114312 [ Used: 7137216 ] [ Freed:  7521192]
    Memory Usage:   835640   -> 8498376 [ Used: 7662736 ] [ Freed:  7278672]
    Memory Usage:   977296   -> 8115000 [ Used: 7137704 ] [ Freed:  7521080]
    Memory Usage:   835392   -> 8504872 [ Used: 7669480 ] [ Freed:  7279608]
    Memory Usage:   976968   -> 8115192 [ Used: 7138224 ] [ Freed:  7527904]
    Memory Usage:   836224   -> 8501624 [ Used: 7665400 ] [ Freed:  7278968]
    Memory Usage:   977840   -> 8115120 [ Used: 7137280 ] [ Freed:  7523784]
    Memory Usage:   835664   -> 8498256 [ Used: 7662592 ] [ Freed:  7279456]
    Memory Usage:   976856   -> 8114384 [ Used: 7137528 ] [ Freed:  7521400]
    Memory Usage:   835784   -> 8502848 [ Used: 7667064 ] [ Freed:  7278600]
    Memory Usage:   977360   -> 8114592 [ Used: 7137232 ] [ Freed:  7525488]
    Memory Usage:   835496   -> 8502720 [ Used: 7667224 ] [ Freed:  7279096]
    Memory Usage:   976440   -> 8115128 [ Used: 7138688 ] [ Freed:  7526280]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   866504   -> 8784320 [ Used: 7917816 ] [ Freed:  -866504]
    Memory Usage:  7480760   ->14631152 [ Used: 7150392 ] [ Freed:  1303560]
    Memory Usage: 14245264   ->22127104 [ Used: 7881840 ] [ Freed:   385888]
    Memory Usage: 19302896   ->27190744 [ Used: 7887848 ] [ Freed:  2824208]
    Memory Usage: 27190744   ->35073944 [ Used: 7883200 ] [ Freed:        0]
    Memory Usage: 31856624   ->39740176 [ Used: 7883552 ] [ Freed:  3217320]
    Memory Usage: 39740176   ->47623040 [ Used: 7882864 ] [ Freed:        0]
    Memory Usage: 44410480   ->52293864 [ Used: 7883384 ] [ Freed:  3212560]
    Memory Usage: 52293864   ->58569304 [ Used: 6275440 ] [ Freed:        0]
    Memory Usage: 58569304   ->64846400 [ Used: 6277096 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spacewhen I outcomment the adding of the JButtons the amount of freed memory is 0 in the second run. So my guess is, that there is a problem with freeing the memory for the JTextFields.
    Memory Usage:   447832   -> 6509960 [ Used: 6062128 ] [ Freed:  6332768]
    Memory Usage:   722776   -> 6785632 [ Used: 6062856 ] [ Freed:  5787184]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   468880   -> 6770240 [ Used: 6301360 ] [ Freed:  -468880]
    Memory Usage:  6770240   ->13016264 [ Used: 6246024 ] [ Freed:        0]
    Memory Usage: 13016264   ->19297080 [ Used: 6280816 ] [ Freed:        0]
    Memory Usage: 19297080   ->25570152 [ Used: 6273072 ] [ Freed:        0]
    Memory Usage: 25570152   ->31849160 [ Used: 6279008 ] [ Freed:        0]
    Memory Usage: 31849160   ->38124368 [ Used: 6275208 ] [ Freed:        0]
    Memory Usage: 38124368   ->44402072 [ Used: 6277704 ] [ Freed:        0]
    Memory Usage: 44402072   ->50677928 [ Used: 6275856 ] [ Freed:        0]
    Memory Usage: 50677928   ->56955880 [ Used: 6277952 ] [ Freed:        0]
    Memory Usage: 56955880   ->63232152 [ Used: 6276272 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spaceAdditionally the JPanel I am using is not displayed on the screen. It stays invisible the whole time, but i cannot work around that, because the calculation is depending on the values being in components on the JPanel)
    Marc

  • JTabbedPane with close Icons

    Ok, so I was trying to get a JTabbedPane with 'X' icons on each tab. Searched this site, and found no answers, but loads of questions on how to do it. I've done it now, and here's my code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    * A JTabbedPane which has a close ('X') icon on each tab.
    * To add a tab, use the method addTab(String, Component)
    * To have an extra icon on each tab (e.g. like in JBuilder, showing the file type) use
    * the method addTab(String, Component, Icon). Only clicking the 'X' closes the tab.
    public class JTabbedPaneWithCloseIcons extends JTabbedPane implements MouseListener {
      public JTabbedPaneWithCloseIcons() {
        super();
        addMouseListener(this);
      public void addTab(String title, Component component) {
        this.addTab(title, component, null);
      public void addTab(String title, Component component, Icon extraIcon) {
        super.addTab(title, new CloseTabIcon(extraIcon), component);
      public void mouseClicked(MouseEvent e) {
        int tabNumber=getUI().tabForCoordinate(this, e.getX(), e.getY());
        if (tabNumber < 0) return;
        Rectangle rect=((CloseTabIcon)getIconAt(tabNumber)).getBounds();
        if (rect.contains(e.getX(), e.getY())) {
          //the tab is being closed
          this.removeTabAt(tabNumber);
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
    * The class which generates the 'X' icon for the tabs. The constructor
    * accepts an icon which is extra to the 'X' icon, so you can have tabs
    * like in JBuilder. This value is null if no extra icon is required.
    class CloseTabIcon implements Icon {
      private int x_pos;
      private int y_pos;
      private int width;
      private int height;
      private Icon fileIcon;
      public CloseTabIcon(Icon fileIcon) {
        this.fileIcon=fileIcon;
        width=16;
        height=16;
      public void paintIcon(Component c, Graphics g, int x, int y) {
        this.x_pos=x;
        this.y_pos=y;
        Color col=g.getColor();
        g.setColor(Color.black);
        int y_p=y+2;
        g.drawLine(x+1, y_p, x+12, y_p);
        g.drawLine(x+1, y_p+13, x+12, y_p+13);
        g.drawLine(x, y_p+1, x, y_p+12);
        g.drawLine(x+13, y_p+1, x+13, y_p+12);
        g.drawLine(x+3, y_p+3, x+10, y_p+10);
        g.drawLine(x+3, y_p+4, x+9, y_p+10);
        g.drawLine(x+4, y_p+3, x+10, y_p+9);
        g.drawLine(x+10, y_p+3, x+3, y_p+10);
        g.drawLine(x+10, y_p+4, x+4, y_p+10);
        g.drawLine(x+9, y_p+3, x+3, y_p+9);
        g.setColor(col);
        if (fileIcon != null) {
          fileIcon.paintIcon(c, g, x+width, y_p);
      public int getIconWidth() {
        return width + (fileIcon != null? fileIcon.getIconWidth() : 0);
      public int getIconHeight() {
        return height;
      public Rectangle getBounds() {
        return new Rectangle(x_pos, y_pos, width, height);
    }You can also specify an extra icon to put on each tab. Read my comments on how to do it.

    With the following code you'll be able to have use SCROLL_TAB_LAYOUT and WRAP_TAB_LAYOUT. With setCloseIcons() you'll be able to set images for the close-icons.
    The TabbedPane:
    import javax.swing.Icon;
    import javax.swing.JComponent;
    import javax.swing.JTabbedPane;
    import javax.swing.JViewport;
    import javax.swing.SwingUtilities;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.event.EventListenerList;
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    import javax.swing.plaf.metal.MetalTabbedPaneUI;
    * A JTabbedPane which has a close ('X') icon on each tab.
    * To add a tab, use the method addTab(String, Component)
    * To have an extra icon on each tab (e.g. like in JBuilder, showing the file
    * type) use the method addTab(String, Component, Icon). Only clicking the 'X'
    * closes the tab.
    public class CloseableTabbedPane extends JTabbedPane implements MouseListener,
      MouseMotionListener {
       * The <code>EventListenerList</code>.
      private EventListenerList listenerList = null;
       * The viewport of the scrolled tabs.
      private JViewport headerViewport = null;
       * The normal closeicon.
      private Icon normalCloseIcon = null;
       * The closeicon when the mouse is over.
      private Icon hooverCloseIcon = null;
       * The closeicon when the mouse is pressed.
      private Icon pressedCloseIcon = null;
       * Creates a new instance of <code>CloseableTabbedPane</code>
      public CloseableTabbedPane() {
        super();
        init(SwingUtilities.LEFT);
       * Creates a new instance of <code>CloseableTabbedPane</code>
       * @param horizontalTextPosition the horizontal position of the text (e.g.
       * SwingUtilities.TRAILING or SwingUtilities.LEFT)
      public CloseableTabbedPane(int horizontalTextPosition) {
        super();
        init(horizontalTextPosition);
       * Initializes the <code>CloseableTabbedPane</code>
       * @param horizontalTextPosition the horizontal position of the text (e.g.
       * SwingUtilities.TRAILING or SwingUtilities.LEFT)
      private void init(int horizontalTextPosition) {
        listenerList = new EventListenerList();
        addMouseListener(this);
        addMouseMotionListener(this);
        if (getUI() instanceof MetalTabbedPaneUI)
          setUI(new CloseableMetalTabbedPaneUI(horizontalTextPosition));
        else
          setUI(new CloseableTabbedPaneUI(horizontalTextPosition));
       * Allows setting own closeicons.
       * @param normal the normal closeicon
       * @param hoover the closeicon when the mouse is over
       * @param pressed the closeicon when the mouse is pressed
      public void setCloseIcons(Icon normal, Icon hoover, Icon pressed) {
        normalCloseIcon = normal;
        hooverCloseIcon = hoover;
        pressedCloseIcon = pressed;
       * Adds a <code>Component</code> represented by a title and no icon.
       * @param title the title to be displayed in this tab
       * @param component the component to be displayed when this tab is clicked
      public void addTab(String title, Component component) {
        addTab(title, component, null);
       * Adds a <code>Component</code> represented by a title and an icon.
       * @param title the title to be displayed in this tab
       * @param component the component to be displayed when this tab is clicked
       * @param extraIcon the icon to be displayed in this tab
      public void addTab(String title, Component component, Icon extraIcon) {
        boolean doPaintCloseIcon = true;
        try {
          Object prop = null;
          if ((prop = ((JComponent) component).
                        getClientProperty("isClosable")) != null) {
            doPaintCloseIcon = (Boolean) prop;
        } catch (Exception ignored) {/*Could probably be a ClassCastException*/}
        super.addTab(title,
                     doPaintCloseIcon ? new CloseTabIcon(extraIcon) : null,
                     component);
        if (headerViewport == null) {
          for (Component c : getComponents()) {
            if ("TabbedPane.scrollableViewport".equals(c.getName()))
              headerViewport = (JViewport) c;
       * Invoked when the mouse button has been clicked (pressed and released) on
       * a component.
       * @param e the <code>MouseEvent</code>
      public void mouseClicked(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when the mouse enters a component.
       * @param e the <code>MouseEvent</code>
      public void mouseEntered(MouseEvent e) { }
       * Invoked when the mouse exits a component.
       * @param e the <code>MouseEvent</code>
      public void mouseExited(MouseEvent e) {
        for (int i=0; i<getTabCount(); i++) {
          CloseTabIcon icon = (CloseTabIcon) getIconAt(i);
          if (icon != null)
            icon.mouseover = false;
        repaint();
       * Invoked when a mouse button has been pressed on a component.
       * @param e the <code>MouseEvent</code>
      public void mousePressed(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when a mouse button has been released on a component.
       * @param e the <code>MouseEvent</code>
      public void mouseReleased(MouseEvent e) { }
       * Invoked when a mouse button is pressed on a component and then dragged.
       * <code>MOUSE_DRAGGED</code> events will continue to be delivered to the
       * component where the drag originated until the mouse button is released
       * (regardless of whether the mouse position is within the bounds of the
       * component).<br/>
       * <br/>
       * Due to platform-dependent Drag&Drop implementations,
       * <code>MOUSE_DRAGGED</code> events may not be delivered during a native
       * Drag&Drop operation.
       * @param e the <code>MouseEvent</code>
      public void mouseDragged(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when the mouse cursor has been moved onto a component but no
       * buttons have been pushed.
       * @param e the <code>MouseEvent</code>
      public void mouseMoved(MouseEvent e) {
        processMouseEvents(e);
       * Processes all caught <code>MouseEvent</code>s.
       * @param e the <code>MouseEvent</code>
      private void processMouseEvents(MouseEvent e) {
        int tabNumber = getUI().tabForCoordinate(this, e.getX(), e.getY());
        if (tabNumber < 0) return;
        CloseTabIcon icon = (CloseTabIcon) getIconAt(tabNumber);
        if (icon != null) {
          Rectangle rect= icon.getBounds();
          Point pos = headerViewport == null ?
                      new Point() : headerViewport.getViewPosition();
          Rectangle drawRect = new Rectangle(
            rect.x - pos.x, rect.y - pos.y, rect.width, rect.height);
          if (e.getID() == e.MOUSE_PRESSED) {
            icon.mousepressed = e.getModifiers() == e.BUTTON1_MASK;
            repaint(drawRect);
          } else if (e.getID() == e.MOUSE_MOVED || e.getID() == e.MOUSE_DRAGGED ||
                     e.getID() == e.MOUSE_CLICKED) {
            pos.x += e.getX();
            pos.y += e.getY();
            if (rect.contains(pos)) {
              if (e.getID() == e.MOUSE_CLICKED) {
                int selIndex = getSelectedIndex();
                if (fireCloseTab(selIndex)) {
                  if (selIndex > 0) {
                    // to prevent uncatchable null-pointers
                    Rectangle rec = getUI().getTabBounds(this, selIndex - 1);
                    MouseEvent event = new MouseEvent((Component) e.getSource(),
                                                      e.getID() + 1,
                                                      System.currentTimeMillis(),
                                                      e.getModifiers(),
                                                      rec.x,
                                                      rec.y,
                                                      e.getClickCount(),
                                                      e.isPopupTrigger(),
                                                      e.getButton());
                    dispatchEvent(event);
                  //the tab is being closed
                  //removeTabAt(tabNumber);
                  remove(selIndex);
                } else {
                  icon.mouseover = false;
                  icon.mousepressed = false;
                  repaint(drawRect);
              } else {
                icon.mouseover = true;
                icon.mousepressed = e.getModifiers() == e.BUTTON1_MASK;
            } else {
              icon.mouseover = false;
            repaint(drawRect);
       * Adds an <code>CloseableTabbedPaneListener</code> to the tabbedpane.
       * @param l the <code>CloseableTabbedPaneListener</code> to be added
      public void addCloseableTabbedPaneListener(CloseableTabbedPaneListener l) {
        listenerList.add(CloseableTabbedPaneListener.class, l);
       * Removes an <code>CloseableTabbedPaneListener</code> from the tabbedpane.
       * @param l the listener to be removed
      public void removeCloseableTabbedPaneListener(CloseableTabbedPaneListener l) {
        listenerList.remove(CloseableTabbedPaneListener.class, l);
       * Returns an array of all the <code>SearchListener</code>s added to this
       * <code>SearchPane</code> with addSearchListener().
       * @return all of the <code>SearchListener</code>s added or an empty array if
       * no listeners have been added
      public CloseableTabbedPaneListener[] getCloseableTabbedPaneListener() {
        return listenerList.getListeners(CloseableTabbedPaneListener.class);
       * Notifies all listeners that have registered interest for notification on
       * this event type.
       * @param tabIndexToClose the index of the tab which should be closed
       * @return true if the tab can be closed, false otherwise
      protected boolean fireCloseTab(int tabIndexToClose) {
        boolean closeit = true;
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        for (Object i : listeners) {
          if (i instanceof CloseableTabbedPaneListener) {
            if (!((CloseableTabbedPaneListener) i).closeTab(tabIndexToClose)) {
              closeit = false;
              break;
        return closeit;
       * The class which generates the 'X' icon for the tabs. The constructor
       * accepts an icon which is extra to the 'X' icon, so you can have tabs
       * like in JBuilder. This value is null if no extra icon is required.
      class CloseTabIcon implements Icon {
         * the x position of the icon
        private int x_pos;
         * the y position of the icon
        private int y_pos;
         * the width the icon
        private int width;
         * the height the icon
        private int height;
         * the additional fileicon
        private Icon fileIcon;
         * true whether the mouse is over this icon, false otherwise
        private boolean mouseover = false;
         * true whether the mouse is pressed on this icon, false otherwise
        private boolean mousepressed = false;
         * Creates a new instance of <code>CloseTabIcon</code>
         * @param fileIcon the additional fileicon, if there is one set
        public CloseTabIcon(Icon fileIcon) {
          this.fileIcon = fileIcon;
          width  = 16;
          height = 16;
         * Draw the icon at the specified location. Icon implementations may use the
         * Component argument to get properties useful for painting, e.g. the
         * foreground or background color.
         * @param c the component which the icon belongs to
         * @param g the graphic object to draw on
         * @param x the upper left point of the icon in the x direction
         * @param y the upper left point of the icon in the y direction
        public void paintIcon(Component c, Graphics g, int x, int y) {
          boolean doPaintCloseIcon = true;
          try {
            // JComponent.putClientProperty("isClosable", new Boolean(false));
            JTabbedPane tabbedpane = (JTabbedPane) c;
            int tabNumber = tabbedpane.getUI().tabForCoordinate(tabbedpane, x, y);
            JComponent curPanel = (JComponent) tabbedpane.getComponentAt(tabNumber);
            Object prop = null;
            if ((prop = curPanel.getClientProperty("isClosable")) != null) {
              doPaintCloseIcon = (Boolean) prop;
          } catch (Exception ignored) {/*Could probably be a ClassCastException*/}
          if (doPaintCloseIcon) {
            x_pos = x;
            y_pos = y;
            int y_p = y + 1;
            if (normalCloseIcon != null && !mouseover) {
              normalCloseIcon.paintIcon(c, g, x, y_p);
            } else if (hooverCloseIcon != null && mouseover && !mousepressed) {
              hooverCloseIcon.paintIcon(c, g, x, y_p);
            } else if (pressedCloseIcon != null && mousepressed) {
              pressedCloseIcon.paintIcon(c, g, x, y_p);
            } else {
              y_p++;
              Color col = g.getColor();
              if (mousepressed && mouseover) {
                g.setColor(Color.WHITE);
                g.fillRect(x+1, y_p, 12, 13);
              g.setColor(Color.black);
              g.drawLine(x+1, y_p, x+12, y_p);
              g.drawLine(x+1, y_p+13, x+12, y_p+13);
              g.drawLine(x, y_p+1, x, y_p+12);
              g.drawLine(x+13, y_p+1, x+13, y_p+12);
              g.drawLine(x+3, y_p+3, x+10, y_p+10);
              if (mouseover)
                g.setColor(Color.GRAY);
              g.drawLine(x+3, y_p+4, x+9, y_p+10);
              g.drawLine(x+4, y_p+3, x+10, y_p+9);
              g.drawLine(x+10, y_p+3, x+3, y_p+10);
              g.drawLine(x+10, y_p+4, x+4, y_p+10);
              g.drawLine(x+9, y_p+3, x+3, y_p+9);
              g.setColor(col);
              if (fileIcon != null) {
                fileIcon.paintIcon(c, g, x+width, y_p);
         * Returns the icon's width.
         * @return an int specifying the fixed width of the icon.
        public int getIconWidth() {
          return width + (fileIcon != null ? fileIcon.getIconWidth() : 0);
         * Returns the icon's height.
         * @return an int specifying the fixed height of the icon.
        public int getIconHeight() {
          return height;
         * Gets the bounds of this icon in the form of a <code>Rectangle<code>
         * object. The bounds specify this icon's width, height, and location
         * relative to its parent.
         * @return a rectangle indicating this icon's bounds
        public Rectangle getBounds() {
          return new Rectangle(x_pos, y_pos, width, height);
       * A specific <code>BasicTabbedPaneUI</code>.
      class CloseableTabbedPaneUI extends BasicTabbedPaneUI {
        * the horizontal position of the text
        private int horizontalTextPosition = SwingUtilities.LEFT;
         * Creates a new instance of <code>CloseableTabbedPaneUI</code>
        public CloseableTabbedPaneUI() {
         * Creates a new instance of <code>CloseableTabbedPaneUI</code>
         * @param horizontalTextPosition the horizontal position of the text (e.g.
         * SwingUtilities.TRAILING or SwingUtilities.LEFT)
        public CloseableTabbedPaneUI(int horizontalTextPosition) {
          this.horizontalTextPosition = horizontalTextPosition;
         * Layouts the label
         * @param tabPlacement the placement of the tabs
         * @param metrics the font metrics
         * @param tabIndex the index of the tab
         * @param title the title of the tab
         * @param icon the icon of the tab
         * @param tabRect the tab boundaries
         * @param iconRect the icon boundaries
         * @param textRect the text boundaries
         * @param isSelected true whether the tab is selected, false otherwise
        protected void layoutLabel(int tabPlacement, FontMetrics metrics,
                                   int tabIndex, String title, Icon icon,
                                   Rectangle tabRect, Rectangle iconRect,
                                   Rectangle textRect, boolean isSelected) {
          textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
          javax.swing.text.View v = getTextViewForTab(tabIndex);
          if (v != null) {
            tabPane.putClientProperty("html", v);
          SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
                                             metrics, title, icon,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             //SwingUtilities.TRAILING,
                                             horizontalTextPosition,
                                             tabRect,
                                             iconRect,
                                             textRect,
                                             textIconGap + 2);
          tabPane.putClientProperty("html", null);
          int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
          int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
          iconRect.x += xNudge;
          iconRect.y += yNudge;
          textRect.x += xNudge;
          textRect.y += yNudge;
       * A specific <code>MetalTabbedPaneUI</code>.
      class CloseableMetalTabbedPaneUI extends MetalTabbedPaneUI {
        * the horizontal position of the text
        private int horizontalTextPosition = SwingUtilities.LEFT;
         * Creates a new instance of <code>CloseableMetalTabbedPaneUI</code>
        public CloseableMetalTabbedPaneUI() {
         * Creates a new instance of <code>CloseableMetalTabbedPaneUI</code>
         * @param horizontalTextPosition the horizontal position of the text (e.g.
         * SwingUtilities.TRAILING or SwingUtilities.LEFT)
        public CloseableMetalTabbedPaneUI(int horizontalTextPosition) {
          this.horizontalTextPosition = horizontalTextPosition;
         * Layouts the label
         * @param tabPlacement the placement of the tabs
         * @param metrics the font metrics
         * @param tabIndex the index of the tab
         * @param title the title of the tab
         * @param icon the icon of the tab
         * @param tabRect the tab boundaries
         * @param iconRect the icon boundaries
         * @param textRect the text boundaries
         * @param isSelected true whether the tab is selected, false otherwise
        protected void layoutLabel(int tabPlacement, FontMetrics metrics,
                                   int tabIndex, String title, Icon icon,
                                   Rectangle tabRect, Rectangle iconRect,
                                   Rectangle textRect, boolean isSelected) {
          textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
          javax.swing.text.View v = getTextViewForTab(tabIndex);
          if (v != null) {
            tabPane.putClientProperty("html", v);
          SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
                                             metrics, title, icon,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             //SwingUtilities.TRAILING,
                                             horizontalTextPosition,
                                             tabRect,
                                             iconRect,
                                             textRect,
                                             textIconGap + 2);
          tabPane.putClientProperty("html", null);
          int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
          int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
          iconRect.x += xNudge;
          iconRect.y += yNudge;
          textRect.x += xNudge;
          textRect.y += yNudge;
    }The Listener:
    import java.util.EventListener;
    * The listener that's notified when an tab should be closed in the
    * <code>CloseableTabbedPane</code>.
    public interface CloseableTabbedPaneListener extends EventListener {
       * Informs all <code>CloseableTabbedPaneListener</code>s when a tab should be
       * closed
       * @param tabIndexToClose the index of the tab which should be closed
       * @return true if the tab can be closed, false otherwise
      boolean closeTab(int tabIndexToClose);
    }

  • Jtabbedpane with replacing tab content

    Hello,
    I am developing an applet that should contain a JTabbedPane with 2 tabs.
    The second tab is easy to do because ti contains one Jpanel all the way.
    the first however is an issue, because i am supposed to change its content when the applet is running.
    this means i have 3 JPanels, J1, J2, J3.
    At tge beginning the applet contains J1 in the first tab.
    and J1 contains a button. when i click that button the applet should replace J1 with J2.
    the problem is i haven't managed to find a solution yet :(
    I have tried with setvisible(false) and validate(). It won't work. I also tried to add the J2 panel over J1, but encountered no succes.
    anybody has any idea ?
    Message was edited by:
    asrfel

    If you want to change back and forth repeatedly then wrap J1/2/3 in a JPanel with a CardLayout.
    If you can discard one when it's done with, use the remove() and insertTab() methods of JTabbedPane.

  • A component within JTabbedPane with overlay layout

    Hi, I use the following solution to have a component within the upper right corner of the JTabbedPane: [http://forums.sun.com/thread.jspa?forumID=57&threadID=636289&start=2|http://forums.sun.com/thread.jspa?forumID=57&threadID=636289&start=2] . It works great, but when I'm resizing a window with the JTabbedPane with the JTabbedPane.WRAP_TAB_LAYOUT and width of all of the tabs is higher than size of the window the tabs are wrapped. But it should be wrapped when width of all tabs + width of the added component is higher than the size. I have no idea how to do this. Any ideas?
    Please see the screenshot: [http://img150.imageshack.us/img150/5629/btn.png|http://img150.imageshack.us/img150/5629/btn.png]

    Just a quick idea:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    class TabbedPaneTest {
      public JComponent makeUI() {
        UIManager.put("TabbedPane.tabAreaInsets",
                      new InsetsUIResource(6, 2, 0, 60));
        JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        sp.setTopComponent(makeTabPanel(new JTabbedPane()));
        sp.setBottomComponent(makeTabPanel(new ClippedTitleTabbedPane()));
        sp.setPreferredSize(new Dimension(320, 240));
        return sp;
      private JPanel makeTabPanel(final JTabbedPane tab) {
        tab.addTab("asdfasd", new JLabel("456746"));
        tab.addTab("1234123", new JScrollPane(new JTree()));
        tab.addTab("6780969", new JLabel("zxcvzxc"));
        tab.setAlignmentX(1.0f);
        tab.setAlignmentY(0.0f);
        JButton b = new JButton(new AbstractAction("add") {
          @Override public void actionPerformed(ActionEvent e) {
            tab.addTab("test", new JScrollPane(new JTree()));
        b.setAlignmentX(1.0f);
        b.setAlignmentY(0.0f);
        JPanel p = new JPanel();
        p.setLayout(new OverlayLayout(p));
        p.add(b);
        p.add(tab);
        return p;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new TabbedPaneTest().makeUI());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    class ClippedTitleTabbedPane extends JTabbedPane {
      //XXX Nimbus NPE
      Insets tabInsets = UIManager.getInsets("TabbedPane.tabInsets");
      Insets tabAreaInsets = UIManager.getInsets("TabbedPane.tabAreaInsets");
      public ClippedTitleTabbedPane() {
        super(JTabbedPane.TOP);
        setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        addComponentListener(new ComponentAdapter() {
          @Override public void componentResized(ComponentEvent e) {
            initTabWidth();
      @Override
      public void insertTab(String title, Icon icon, Component component,
                            String tip, int index) {
        super.insertTab(title, icon, component, tip==null?title:tip, index);
        JLabel label = new JLabel(title, JLabel.CENTER);
        Dimension dim = label.getPreferredSize();
        label.setPreferredSize(
            new Dimension(0, dim.height+tabInsets.top+tabInsets.bottom));
        setTabComponentAt(index, label);
        initTabWidth();
      private void initTabWidth() {
        Insets insets = getInsets();
        int areaWidth = getWidth() - tabAreaInsets.left - tabAreaInsets.right
                                   - insets.left        - insets.right;
        int tabCount = getTabCount();
        int tabWidth = 0;
        switch(getTabPlacement()) {
          case LEFT: case RIGHT:
          tabWidth = areaWidth/4;
          break;
          case BOTTOM: case TOP: default:
          tabWidth = areaWidth/tabCount;
        int gap = areaWidth - (tabWidth * tabCount);
        if(tabWidth>80) {
          tabWidth = 80;
          gap = 0;
        tabWidth = tabWidth - tabInsets.left - tabInsets.right - 3;
        for(int i=0;i<tabCount;i++) {
          JLabel l = (JLabel)getTabComponentAt(i);
          if(l==null) break;
          int h = l.getPreferredSize().height;
          l.setPreferredSize(new Dimension(tabWidth+((gap>0)?1:0), h));
          gap--;
        revalidate();
    }

  • JTabbedPane with two rows of tabs

    Hi,
    I need to create a JTabbedPane with layout policy as SCROLL_TAB_LAYOUT with two rows of tabs. The first level will have say 10 tabs and the all the remaining tabs (say 20) will be added in the next level. Please help me out on this, to how to proceed with it?
    Edited by: Soundarapandian on Nov 25, 2009 3:10 PM

    Soundarapandian wrote:
    I need to create a JTabbedPane with layout policy as SCROLL_TAB_LAYOUT with two rows of tabs. The first level will have say 10 tabs and the all the remaining tabs (say 20) will be added in the next level. Please help me out on this, to how to proceed with it?Try this (imho better) approach:
    create a new tabbedpane for each level and add each of these tabbedpanes to an upperlevel tabbedpane, thus allowing you to pre-select the desired level.

  • How to create a password with JTextField

    Hi, I need to create a password field on the JTabbedPane. I can create a TextField and setEchoChar to make it a password field. However it is not working well with the rest of the JComponents. Can I do this on a JTextField? I could not find the functionality.
    Thanks for the help!
    -Joanne

    use JPasswordField instead

  • JTabbedPane with JSplitPane - HELP !!!

    What am I missing??? I have a JSplitPane in a TabbedPane. The topComponent contains a JComboBox with Key values, the Bottom Component will display details based on the key value passed. The bottomComponent has 2 constructors: one default and one accepting an Argument. The default constructor instantiate the class that would represent the data and formats the bottomComponent. The second constructor retrieves the data from the Oracle database and formats the BottomComponent using the same method. I put System.out messages and the values are showing using the Second constructor. Your help is greatly appreciated.

    This is the complete set of code. I hope you can follow the logic. I tried your last suggestion without any success. Maybe by reviewing the code you can see a problem. I appreciate your help greatly. Thanks.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Management extends JPanel implements ChangeListener{
    //private JFrame dlframe;
    private JTabbedPane propPane;
    public Management(){
    propPane = new JTabbedPane(SwingConstants.TOP);
    propPane.setSize(795, 550);
    propPane.addChangeListener(this);
    populateTabbedPane();
    // getContentPane().add(propPane);
    add(propPane);
    } // end of constructor
    // create tabs with titles
    private void populateTabbedPane(){
         propPane.addTab("Management", null, new Mgmt(), "Management");
         propPane.addTab("Management Contact", null,
    new Management_Contact(), "Management Contact");
    } // end of populateTabbedPane
    public void stateChanged(ChangeEvent e){
         System.out.println("\n\n ****** Management.java " + propPane.getSelectedIndex() + " " + propPane.getTabPlacement());
    public static void main(String[] args){
    Home dl = new Home();
    dl.pack();
    dl.setSize(800, 620);
    dl.setBackground(Color.white);
    dl.setVisible(true);
    } // end of class Management
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Management_Contact extends JPanel {
         Mgmt_Class mgmt = null;
         Mgmt_Contact mgmtContact = null;
         public Management_Contact() {
              JSplitPane split = new JSplitPane();
              split.setOrientation(JSplitPane.VERTICAL_SPLIT);
              Mgmt_Header hdr = new Mgmt_Header();
              split.setTopComponent(hdr);
              Mgmt_Contact mgmtContact = new Mgmt_Contact();
              JScrollPane scrollPane = new JScrollPane(mgmtContact,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
              JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scrollPane.setPreferredSize(new Dimension(650,300));
              split.setBottomComponent(scrollPane);
              add(split);
    } // end of Management class
    import java.util.Vector;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Mgmt_Header extends JPanel implements ActionListener{
    private JComboBox cmbMgmt;
    private JTextField txtMgmtCode;
    private JTextField txtMgmtAddr1;
    private JTextField txtMgmtAddr2;
    private JTextField txtMgmtCity;
    private JButton sel;
    private JLabel lblBlk;
    private JPanel pWork;
    private Box vertBox;     
    private Box topBox;     
    private Box midBox;     
    private Box botBox;     
    JToolTip toolTip = null;
    private Mgmt_Class mClass = null;
    private Mgmt_Contact cnt = null;
    Vector mgmtVct = null;
    public Mgmt_Header(){
         vertBox = Box.createVerticalBox();
         topBox = Box.createHorizontalBox();
         midBox = Box.createHorizontalBox();
         botBox = Box.createHorizontalBox();
    mClass = new Mgmt_Class();
    mgmtVct = new Vector();
         cmbMgmt = new JComboBox();
         cmbMgmt.addItem(" ");
         mgmtVct = mClass.bldMgmtHeader();
         for (int x1=0; x1<mgmtVct.size() ;x1++ )
         mClass = (Mgmt_Class)mgmtVct.get(x1);
         cmbMgmt.addItem(mClass.getManagementName());
    System.out.println("MgmtHeader " + mgmtVct.size() + " " + cmbMgmt.getItemCount());
         cmbMgmt.setEditable(false);
         cmbMgmt.setBackground(Color.white);
         cmbMgmt.setName("cmbMgmt");
         cmbMgmt.setPreferredSize(new Dimension(250,27));
         cmbMgmt.setFont(new Font("Times-Roman",Font.PLAIN,12));
         cmbMgmt.addActionListener(this);
         pWork = new JPanel();
         pWork.setLayout(new FlowLayout(FlowLayout.CENTER));
         pWork.setBorder(BorderFactory.createTitledBorder(" Select Management Name "));
         pWork.add(new JLabel("Name: "));
         pWork.add(cmbMgmt);
         topBox.add(pWork);
         txtMgmtAddr1 = new JTextField("Address line 1",15);
         txtMgmtAddr1.setEditable(false);
         txtMgmtAddr2 = new JTextField("Address line 2",15);
         txtMgmtAddr2.setEditable(false);
         txtMgmtCity = new JTextField("City",15);
         txtMgmtCity.setEditable(false);
         midBox.add(midBox.createVerticalStrut(10));
         botBox.add(new JLabel("Address:"));
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtAddr1);
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtAddr2);
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtCity);
         vertBox.add(topBox);
         vertBox.add(midBox);
         vertBox.add(botBox);
         add(vertBox);
    } // end of constructor
         public void actionPerformed(ActionEvent evt){
         if (evt.getSource() instanceof JComboBox){
         if (((JComboBox)evt.getSource()).getName() == "cmbMgmt"){
         int sel = ((JComboBox)evt.getSource()).getSelectedIndex();
         System.out.println("ActionListener " + sel + " " + ((JComboBox)evt.getSource()).getItemAt(sel) + " " + cmbMgmt.getItemAt(sel));
         Mgmt_Class mClass = (Mgmt_Class)mgmtVct.get(sel - 1);
         System.out.println("From Vector " + mClass.getAddress1() + " " + mClass.getAddress2() + " " + mClass.getManagementCode());
         txtMgmtAddr1.setText(mClass.getAddress1());
         txtMgmtAddr2.setText(mClass.getAddress2());
         txtMgmtCity.setText(City.getCityName(mClass.getCityCode()));
         System.out.println("\n\nListener " + ((JComboBox)evt.getSource()).getSelectedItem() + " " + (((JComboBox)evt.getSource()).getSelectedIndex()) );
         int mCode = mClass.getManagementCode();
         cnt = new Mgmt_Contact(mCode);
    System.out.println("\n After new Mgmt_Contact constructor");
         } // end of JComboBox
    } // end of actionPerformed
    } // end of Mgmt_Header
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.io.*;
    public class Mgmt_Contact extends JPanel implements KeyListener{
         private Mgmt_Contact_Class contact = null;
         private DefaultFocusManager mgr = null;
         private JTextField txtFName = null;
         private JTextField txtLName = null;
         private JTextField txtAddr1 = null;
         private JTextField txtAddr2 = null;
         private JButton btnUpd = null;
         private JButton btnNew = null;
         private JButton btnDel = null;
         private JButton btnNext = null;
         private JButton btnPrior = null;
         private JButton btnSel = null;
         private JPanel cntct = null;
         private JPanel pWork = null;
         private JPanel pWest = null;
         private JPanel pEast = null;
         private JPanel pNorth = null;
         private JPanel pSouth = null;
         private JPanel pCenter = null;
         public Mgmt_Contact() {
         System.out.println("\n MgmtContact default constructor");
              contact = new Mgmt_Contact_Class();
              bldPage();
         System.out.println("\n ******* After bldPage() routine");
         public Mgmt_Contact(int mCode) {
    System.out.println("\n MgmtContact second constructor " + mCode);
         Vector mgmtVct = new Vector();
         contact = new Mgmt_Contact_Class();
         mgmtVct = contact.bldMgmtContactTbl(mCode);
         contact =(Mgmt_Contact_Class)mgmtVct.get(0);
    System.out.println("\n ******* Management Contact Table *** " + contact.getFirstName());          
         bldPage();
    System.out.println("\n ******* After bldPage() routine");
         public void bldPage(){
    System.out.println("\n MgmtContact bldPage ");
              cntct = new JPanel();
              cntct.setLayout(new BorderLayout());
              pWest = new JPanel();
              pWest.setLayout(new GridLayout(0,1));
              pCenter = new JPanel();
              pCenter.setLayout(new GridLayout(0,1));
              pNorth = new JPanel();
              pNorth.setLayout(new FlowLayout(FlowLayout.CENTER));
              pSouth = new JPanel();
              pSouth.setLayout(new FlowLayout());
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              pWest.add(new JLabel("First :"));
              txtFName = new JTextField(15);
              txtFName.setText(contact.getFirstName());
    System.out.println("\n First Name " + txtFName.getText() + " " + contact.getFirstName());
              txtFName.setPreferredSize(new Dimension(200,27));
              txtFName.addKeyListener(this);
              txtFName.setName("txtFName");
              pWork.add(txtFName);
              pWork.add(new JLabel("Last :"));
              txtLName = new JTextField(15);
              txtLName.setText(contact.getLastName());
              txtLName.setPreferredSize(new Dimension(200,27));
              txtLName.setName("txtLName");     
              txtLName.addKeyListener(this);
              pWork.add(txtLName);
              pCenter.add(pWork);
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              pWest.add(new JLabel("Address :"));
              txtAddr1 = new JTextField(15);
              txtAddr1.setText(contact.getAddress1());
              txtAddr1.setPreferredSize(new Dimension(200,27));
              txtAddr1.addKeyListener(this);
              txtAddr1.setName("txtAddr1");
              pWork.add(txtAddr1);
              pWork.add(new JLabel(" "));
              txtAddr2 = new JTextField(15);
              txtAddr2.setText(contact.getAddress2());
              txtAddr2.setPreferredSize(new Dimension(200,27));
              txtAddr2.setName("txtAddr2");
              txtAddr2.addKeyListener(this);
              pWork.add(txtAddr2);
              pCenter.add(pWork);
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              btnUpd = new JButton("Update");
              btnUpd.addActionListener(new ButtonListener());
              btnDel = new JButton("Delete");
              btnDel.addActionListener(new ButtonListener());
              btnNew = new JButton(" Add ");
              btnNew.addActionListener(new ButtonListener());
              btnNext = new JButton(" Next ");
              btnNext.addActionListener(new ButtonListener());
              btnPrior = new JButton(" Prior ");
              btnPrior.addActionListener(new ButtonListener());
              btnSel = new JButton(" Select ");
              btnSel.addActionListener(new ButtonListener());
              pSouth.add(btnNew);
              pSouth.add(btnUpd);
              pSouth.add(btnDel);
              pSouth.add(btnNext);
              pSouth.add(btnPrior);
              pSouth.add(btnSel);
              cntct.add("West", pWest);
              cntct.add("Center", pCenter);
              cntct.add("South", pSouth);
              add(cntct);
         class ButtonListener implements ActionListener{
         public void actionPerformed(ActionEvent e){
    System.out.println("ButtonListener " + e.getActionCommand() + " " +
              contact.getString());
    // KeyListener Interface
         public void keyPressed(KeyEvent e){
         public void keyReleased(KeyEvent e){
              mgr = new DefaultFocusManager();
              Component comp = e.getComponent();
              Object obj = ((JTextField)e.getSource());
              if ((ColUtils.isMaxField(obj))){
              mgr.focusNextComponent(comp);
         } // end of KeyReleased
         public void keyTyped(KeyEvent e){
              char num = e.getKeyChar();
              Object obj = ((JTextField)e.getSource());
              if (ColUtils.isDataValid(num, obj)){
              else {
              e.consume();
              System.out.println(num + " Rejected Data");
         } // end of keyTyped
    } // end of Mgmt_Contact class

  • JTabbedPane with JScrollPane

    The application uses a JTabbedPane, each Tab contains a JScrollPane, the TopComponent contains the same Class with different Classes for the BottomComponent. Each BottomComponent is a separate class and relates to a different table. How can I interface with with the other classes without knowing which Tab is active?

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Property_Features extends JPanel implements ActionListener{
         private JTextArea txtFeature;
         private JLabel image;
         private JButton btnNew = null;
         private JButton btnUpd = null;
         private JButton btnDel = null;
         private JToolTip toolTip = null;
         private Prop_Header propHdr = null;
         private JPanel fPanel = null;
         private JPanel wPanel = null;
         private Box vertBox;     
         private Box topBox;     
         private Box midBox;     
         private Box botBox;     
    public Property_Features(){
         toolTip = new JToolTip();
         vertBox = Box.createVerticalBox();
         topBox = Box.createHorizontalBox();
         midBox = Box.createHorizontalBox();
         botBox = Box.createHorizontalBox();
         wPanel = new JPanel();
         wPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
         txtFeature = new JTextArea(5,50);
         txtFeature.setFont(new Font("SansSerif", Font.PLAIN, 14));
         txtFeature.setLineWrap(true);
         txtFeature.setWrapStyleWord(true);
         txtFeature.setEditable(true);
         txtFeature.setBorder(BorderFactory.createTitledBorder(" Describe the Property Features"));
         toolTip.setComponent(txtFeature);
         txtFeature.setToolTipText("Enter Property Feature of Major Interest");
         wPanel.add(txtFeature);
         topBox.add(wPanel);
         wPanel = new JPanel();
         wPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
         btnNew = new JButton(" Add ");
         btnNew.addActionListener(this);
         toolTip.setComponent(btnNew);
         btnNew.setToolTipText("Add Property Feature Information");
         btnUpd = new JButton("Update");
         btnUpd.addActionListener(this);
         toolTip.setComponent(btnUpd);
         btnUpd.setToolTipText("Update Property Feature Information");
         btnDel = new JButton("Delete");
         btnDel.addActionListener(this);
         toolTip.setComponent(btnDel);
         btnDel.setToolTipText("Delete Property Information");
         wPanel.add(btnNew);
         wPanel.add(btnUpd);
         wPanel.add(btnDel);
         midBox.add(wPanel);
         wPanel = new JPanel();
         wPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
         image = new JLabel("", new      ImageIcon("c:/ATC_Application/images/skiing.jpg"), JLabel.CENTER);
         wPanel.add(image);
         botBox.add(image);
         vertBox.add(topBox);
         vertBox.add(midBox);
         vertBox.add(botBox);
         JSplitPane split = new JSplitPane();
         split.setOrientation(JSplitPane.VERTICAL_SPLIT);
         Prop_Header propHdr = new Prop_Header();
         split.setTopComponent(propHdr);
         split.setBottomComponent(vertBox);
         JScrollPane scrollPane = new JScrollPane(vertBox,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         scrollPane.setPreferredSize(new Dimension(650,400));
         split.add(scrollPane);
         add(split);
    } // end of Property_Features constructor
    // ActionListener Interface
         public void actionPerformed(ActionEvent e){
              System.out.println("Action Listener " + e.getActionCommand());
    } // end of class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Prop_Header extends JPanel implements ActionListener{
    private JComboBox cmbProp;
    private JTextField txtPropCode;
    private JTextField txtPropAddr1;
    private JTextField txtPropAddr2;
    private JTextField txtPropCity;
    private JTextField txtPropState;
    private JButton sel;
    private JLabel lblBlk;
    private JPanel pWork;
    private Box vertBox;     
    private Box topBox;     
    private Box midBox;     
    private Box botBox;     
    JToolTip toolTip = null;
    public Prop_Header(){
         vertBox = Box.createVerticalBox();
         topBox = Box.createHorizontalBox();
         midBox = Box.createHorizontalBox();
         botBox = Box.createHorizontalBox();
         cmbProp = new JComboBox();
         cmbProp.addItem(" ");
         cmbProp.setEditable(false);
         cmbProp.setBackground(Color.white);
         cmbProp.setPreferredSize(new Dimension(250,27));
         cmbProp.setFont(new Font("Times-Roman",Font.PLAIN,12));
         cmbProp.addActionListener(this);
         txtPropCode = new JTextField(5);
         txtPropCode.setFont(new Font("Times-Roman",Font.PLAIN,12));
         txtPropCode.setPreferredSize(new Dimension(5,27));
         txtPropCode.addActionListener(this);
         lblBlk = new JLabel(" ");
         sel = new JButton("Select");
         sel.addActionListener( this);
         toolTip = new JToolTip();
         toolTip.setComponent(cmbProp);
         cmbProp.setToolTipText("Select Property Name & Press
    Select button ");
         toolTip.setComponent(txtPropCode);
         txtPropCode.setToolTipText("Enter Property Code & Press
    Select Button ");
         toolTip.setComponent(sel);
         sel.setToolTipText("Display Property Information Based on
    Name or Code Entered ");
         pWork = new JPanel();
         pWork.setLayout(new FlowLayout(FlowLayout.CENTER));
         pWork.setBorder(BorderFactory.createTitledBorder(" Select
    Property Name or Enter Code "));
         pWork.add(new JLabel("Name: "));
         pWork.add(cmbProp);
         pWork.add(new JLabel(" Code: "));
         pWork.add(txtPropCode);
         pWork.add(lblBlk);
         pWork.add(sel);
         topBox.add(pWork);
         txtPropAddr1 = new JTextField("Address line 1",15);
         txtPropAddr1.setEditable(false);
         txtPropAddr2 = new JTextField("Address line 2",15);
         txtPropAddr2.setEditable(false);
         txtPropCity = new JTextField("City",15);
         txtPropCity.setEditable(false);
         txtPropState = new JTextField("State",3);
         txtPropState.setEditable(false);
         toolTip.setComponent(txtPropAddr1);
         txtPropAddr1.setToolTipText("First Address Line of Property");
         toolTip.setComponent(txtPropAddr2);
         txtPropAddr2.setToolTipText("Second Address Line of Property");
         toolTip.setComponent(txtPropCity);
         txtPropCity.setToolTipText("City Name of Property location");
         toolTip.setComponent(txtPropState);
         txtPropState.setToolTipText("State Code of Property location");
         midBox.add(midBox.createVerticalStrut(10));
         botBox.add(new JLabel("Address:"));
         botBox.add(topBox.createHorizontalStrut(10));
         botBox.add(txtPropAddr1);
         botBox.add(topBox.createHorizontalStrut(10));
         botBox.add(txtPropAddr2);
         botBox.add(topBox.createHorizontalStrut(10));
         botBox.add(txtPropCity);
         botBox.add(topBox.createHorizontalStrut(10));
         botBox.add(txtPropState);
         vertBox.add(topBox);
         vertBox.add(midBox);
         vertBox.add(botBox);
         add(vertBox);
    } // end of constructor
         public void actionPerformed(ActionEvent evt){
         } // end of actionPerformed
    } // end of Prop_Header

  • JTable disturbs gridbaglayout with jtextfields

    Hello, my problem is a JTable, that shrinks my two JTextFields to zero length. I tried to create the gui without the JTable and it works as expected. There should be two JTextFields with fixed length in a row below the JTable in a JTabbedPane. Code:
        jT1 = new JTable( 10,10);
        jSP1 = new JScrollPane( jT1);// without jT1 everything is fine
        jP1 = new JPanel( new BorderLayout());
        jP1.add( jSP1, BorderLayout.CENTER);
        jTP = new JTabbedPane();
        jTP.add( "Tab1", jP1);
        jL1 = new JLabel( "Txt1:");
        jTF1 = new JTextField( "0.00",10);
        jL2 = new JLabel( "Txt2:");
        jTF2 = new JTextField( "0.00",10);
        jP0 = new JPanel(new GridBagLayout());
        jP0.add(jTP, new GridBagConstraints(0, 0, 4, 1, 1.0, 1.0
            ,GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
        jP0.add(jL1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 0), 0, 0));
        jP0.add(jTF1, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 10, 0, 0), 0, 0));
        jP0.add(jL2, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 20, 0, 0), 0, 0));
        jP0.add(jTF2, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 10, 0, 0), 0, 0));Setting weightx to 0.5 and GriBagConstraints.HORIZONTAL for the JTextFields makes them variable size, but that' not what I want.

    What about setting iPadx parameter in GridBagConstraints?
    regards,
    Stas

  • Can't Copy text unless console is opened before applet with JTextField

    If an applet uses JTextFields, it is impossible to copy text from the console to the clipboard (or anywhere else) if the console is opened after the applet.
    See http://demo.capmon.dk/~pvm/nocopy/nocopy.html for a working applet with source and class file to try it out on...
    So if something bad has happened, and there are hints in the console e.g. a stack trace, it all has to be retyped by hand, since all Copy or export is impossible...
    Does anyone know of a workaround for this? I'd like to be able to e.g. copy stack traces to bug reports.
    Try these test cases:
    * Close all browser windows. Open a browser and visit this page. After the page with this applet has loaded, then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Select some text in the console. There is no way to put this text on the clipboard; the "Copy" button doesn't work, and neither does CTRL+Insert, CTRL+C or anything else.
    * Close all browser windows. Open a browser window no some non-java page and then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Then visit this page. Select some text in the console. Now the "Copy" button does work, enabling "export" of e.g. stack traces to other applicaitons e.g. email.
    The difference is which is opened first: The console or the applet. If you look at the very rudimentary Java source code, it is the mere creation of a JTextField is what disables or breaks the Copy functionality.
    I've tried this on Windows XP with IE 6.0 and Mozilla 1.3 and they behave exactly the same. The JVM is Sun's 1.4.2 and I've tried 1.4.1_02 also with the same behavior. I've also tried javac from both 1.4.2 and 1.4.1_01

    hey .. this seems like a bug.. can you please file a bug at
    http://java.sun.com/webapps/bugreport
    thanks...

  • Issue with JTextField Locking

    Hey All!
    I'm working on a database access project and have most things working pretty well, with one glaring exception.
    I've got a JInternalFrame form with 13 data fields to act as a front-end for a table in my database. Most of these data fields are JTextFields, some two are JRadioButtons, one is a JCheckbox and the last one is a JCombobox.
    To prevent accidental data editing, I lock the text fields down by setting JTextField.setEditable(false) and disable the other controls. I have the following method in my form:
    // Locks the form from allowing accidental edits.
        private void unlockForm( boolean unlock ) {
            this.isModifying = unlock;
            this.txtAniv.setEditable(unlock);
            this.txtApt.setEditable(unlock);
            this.txtBDate.setEditable(unlock);
            this.txtCity.setEditable(unlock);
            this.txtFName.setEditable(unlock);
            this.txtLName.setEditable(unlock);
            this.txtPhone.setEditable(unlock);
            this.txtStreet.setEditable(unlock);
            this.txtZip.setEditable(unlock);
            this.chkSearchable.setEnabled(unlock);
            this.optAM.setEnabled(unlock);
            this.optRA.setEnabled(unlock);
            // Set up the toolbar.
            this.setupToolbar();
        } // End of unlockForm() function.If I call this method from a toolbar button ActionPerformed() event and supply `true' as the parameter, it should set the editability of the text fields to true and also enable the other widgets. This seems to work pretty much as expected, except with my txtCity field, for some reason.
    When I click on my edit or add toolbar buttons, they call the unlockForm() method with the parameter set to `true'. However, when I attempt to change the data in the txtCity field, it acts as though it is still not editable. So, in an attempt to figure out what is going on here, I placed the following code in the FocusGained() event for the txtCity textbox:
            // DEBUGGING CODE:  Remove before release build!                      //
            // The following MessageBox is being displayed because I can not find //
            // the reason for the city field to not unlock and, yet, it will not  //
            // unlock for editing.  I need to figure this out!                    //
            MessageBox mb = new MessageBox();                                     //
            String msg = "The following are the settings of the city text field:";//
            msg += "\n-----------------------------------------------------\n";   //
            msg+ = "txtCity.getName() = "  +this.txtCity.getName();               //
            msg+ = "txtCity.getText() = "  +this.txtCity.getText();               //
            msg+ = "txtCity.isEditable() = "  +this.txtCity.isEditable();         //
            msg+ = "txtCity.isEnabled() = " + this.txtCity.isEnabled();           //
            mb.codeRequired(msg, this);                                           //
            ////////////////////////////////////////////////////////////////////////Now, when I click on the txtCity text field, I get this message box as expected, with one glaring problem. I get it more than once. Then, when I click on another control, I somehow go into an infinite loop of this message box being displayed and cannot get out of it. Here is my code for the FocusLost() event:
        private void txtCityFocusLost(java.awt.event.FocusEvent evt) {
            // Deselect the text.
            this.txtCity.select(0, 0);
            // Make sure that data was entered.
            if ( this.txtCity.getText() == null ||
                    this.txtCity.getText().length() == 0 ||
                    this.txtCity.getText().equals("") ) {
                this.txtCity.setBackground(errBG);
                this.txtCity.setForeground(errFG);
                this.txtCity.setFont(errFont);
                this.getToolkit().beep();
            } else {
                this.txtCity.setBackground(stdBG);
                this.txtCity.setFont(stdFont);
                this.txtCity.setForeground(stdFG);
                // Make sure the data was stored.
                this.entry.setCity(this.txtCity.getText());
        }Does anyone have any ideas as to what is going on? Maybe you could point me to a web site or book that actually has this problem and shows how to resolve it. I am at a complete loss as to what's happening, especially since I don't have any code in my FocusLost() event that points to my FocusGained() event. Any help that you can provide will be greatly appreciated.
    If it would help to see what the form looks like, you can view it here:
    http://pekinsoft.homelinux.org/CongregationManager.png
    Thank you for any and all help you may provide.
    Cheers,
    Sean C.
    PekinSOFT Systems
    Edited by: PekinSOFT.Systems on Oct 1, 2009 2:34 PM

    warnerja and camickr:
    I think you all hit it on the nose. My problem was that NetBeans would not go into debug mode due to some vague NullPointerException. However, I deleted my NetBeans user directory and, voila, I can debug again.
    So, when I debugged the code (without my crappy work-around attempt), I found that for some reason, when I click on or tab into the JTextField in question, it actually does go through the FocusGained event more than once, which I still cannot figure out, even going into the source for the Java APIs that get called. It's really weird and the strangest thing of all is that it is now, all of a sudden, working as expected. So, even though I have no clue what caused the issue to begin with, it seems to have cleared up.
    In reference to the post about the SSCCE, I tried to post one, but when I created it, it worked as expected and so was no help in showing my problem. However, when I created the SSCCE, I had already taken the action on my NetBeans user directory, so I'm thinking that something was broken there. Hazards of verifying plugins, I guess.
    Anyway, thank you all very much for your (unneeded, as it turns out) help to my (not actually a) Java problem. Next time I get some strange behavior like this, I think that I'll check my IDE first. ;-)
    Cheers,
    Sean C.
    PekinSOFT Systems

  • JTabbedPane with FormLayout problems

    I created form which contain JTabbedPane within JPanel with FormLayout. In the JTabbedPane, I put JPanel with FormLayout. In Design Mode, there is nothing problem, I can put whatever item into the JPanel of JTabbedPane. But in Runtime Mode, JTabbedPane display nothing, many items I've put on it are not displayed. But when I change the Layout into another like XY Layout or FlowLayout, items are displayed correctly.
    any idea to solve this?
    and why JDeveloper doesn't implement SpringLayout?

    Hi user567546, i faced the same problem.
    Fortunately, I solved it by using PanelBuilder instead of Panel,
    take a look at this example:
    http://www.java2s.com/Code/Java/Swing-Components/DemonstratesthebasicFormLayoutsizesconstantminimumpreferred.htm
    Regards,
    Luis R.

  • Input only working once with JTextField

    Hi,
    I've created an GUI with one JTextField, a JTextArea and a JLabel that I use to display an imageIcon. I want the user to be able to input text into the JTextField without having to click on it with the mouse. I've used requestFocus() to do this and it works the first time. I then clear the JTextField using setText(""), so the user can enter more input. After I do this the cursor is still flashing but when I type nothing comes up in the JTextField. I've tried calling requestFocus() after setText() as well but it didn't work either. Does anyone have any ideas?
    Thanks in advance
    JFrame frame = new JFrame("SubjectGUI");
    JPanel pane = new JPanel();
    ImageIcon icon;
    JLabel diagram;
    JTextArea task;
    JTextField textField;
    boolean done = false;
    public SubjectGUI(){
         diagram = new JLabel(icon, JLabel.CENTER);
         icon = new ImageIcon("images/blank.JPEG");
         textField = new JTextField(10);
         task = new JTextArea(new String(""));
         textField.addActionListener(this);
    pane.setLayout(new BorderLayout());
         pane.add(diagram, BorderLayout.NORTH);
         pane.add(task, BorderLayout.CENTER);
         pane.add(textField, BorderLayout.SOUTH);
         task.setEditable(false);
         frame.getContentPane().add(pane);
         frame.pack();
         frame.setVisible(true);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public void setTextField(String text){
         textField.setText( setTexttext);
    public void setGraph(String filePath){
         ImageIcon icon = new ImageIcon(filePath);
         diagram.setIcon(icon);
    public void setTask(String taskString){
         task.setText(taskString);
    public void focus(){
         textField.requestFocus();
    public static void main(String args[]){
         SubjectGUI sgui = new SubjectGUI();
         long start = System.currentTimeMillis();
         sgui.focus();
         for(int i=0;i<3;i++){
         if(i==0){
              sgui.setTextField("");
              sgui.setTask("2+2");
              sgui.setGraph("./images/graph1.JPEG");
         if(i==1){
              sgui.setTextField("");
              sgui.setTask("4+4");
              sgui.setGraph("./images/graph2.JPEG");
         // sgui.focus();
         while((System.currentTimeMillis()<start + 10000) && !(sgui.done())){

    Sorry,
    Here is the entire code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SubjectGUI implements ActionListener{
    JFrame frame = new JFrame("SubjectGUI");
    JPanel pane = new JPanel();
    ImageIcon icon;
    JLabel diagram;
    JTextArea task;
    JTextField textField;
    boolean done = false;
    public SubjectGUI(){
         diagram = new JLabel(icon, JLabel.CENTER);
         icon = new ImageIcon("images/blank.JPEG");
         textField = new JTextField(10);
         task = new JTextArea(new String(""));
         //textField.setActionCommand(this);
         textField.addActionListener(this);
    pane.setLayout(new BorderLayout());
         pane.add(diagram, BorderLayout.NORTH);
         pane.add(task, BorderLayout.CENTER);
         pane.add(textField, BorderLayout.SOUTH);
         task.setEditable(false);
         textField.setMinimumSize(new Dimension(200,400));
         task.setMinimumSize(new Dimension(200,400));
         diagram.setMinimumSize(new Dimension(200,400));
         pane.setPreferredSize(new Dimension(200,400));
         frame.getContentPane().add(pane);
         frame.pack();
         frame.setVisible(true);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public void setTextField(String text){
         textField.setText(text);
    public void setGraph(String filePath){
         ImageIcon icon = new ImageIcon(filePath);
         diagram.setIcon(icon);
    public void setTask(String taskString){
         task.setText(taskString);
    public void focus(){
         textField.requestFocus();
    public void close(){
         frame.dispose();
    public void actionPerformed(ActionEvent evt){
    String text = textField.getText();
         System.out.println(text);
         done=true;
    public static void main(String args[]){
         SubjectGUI sgui = new SubjectGUI();
         long start = System.currentTimeMillis();
         sgui.focus();
         for(int i=0;i<3;i++){
         if(i==0){
              sgui.setTextField("");
              sgui.setTask("2+2");
              sgui.setGraph("./images/graph1.JPEG");
         if(i==1){
              sgui.setTextField("");
              sgui.setTask("4+4");
              sgui.setGraph("./images/graph2.JPEG");
         //sgui.focus();//see previous focus() outside loop
         while((System.currentTimeMillis()<start + 10000) && !(sgui.done)){

Maybe you are looking for

  • Saving forms Acrobat X

    Hello all Got a really frustrating problem which should be simple, but isnt... Acrobat Pro X (Trial) created a form and want to allow users permission to save. From reading Adobe help I'm told its something in advanced menu I need to set but cant eve

  • Submitting pdf via email

    I have a form that is submitting a pdf through email. Usage rights are enabled. When I hit submit I get an error. The operation failed. Any ideas?

  • Designer Repository meta-model

    The elements that make up the Designer Repository are fully documented at http://technet.oracle.com/docs/products/designer/doc_library/6i_release42/CDOC72/api/index.htm but does anyone know where I could find the same information in diagram form i.e.

  • ICloud disk in Finder.

    Hello everyone. This might sound trivial to some, but let me ask anyhow. Should iCloud "disk" appear in Finder and on the desktop of iMac, similar to the old iDisk and mobileMe disk?? After upgrading to Mountain Lion, I do not see the iCloud disk ima

  • After the most recent Firefox update I am unable to use Yahoo instant messenger. Any ideas?

    I can see that someone is IM'ing me, but it does not pop up on the screen nor can I create or start IM while in yahoo mail.