Diasppearing JButtons in a JToolbar

Hi,
I am using a JToolbar in an applet, but I am facing the following problem: the applet is resizeable, and by that, a user can possibly resize it in such a way that the buttons which are on the toolbar will not all fit any more. I have been trying to find a means of signaling this (i.e. as it happens in Windows all the time, if something does not fit, you get something that looks like >> on the far end of the toolbar, and if you click there, you see the remaining buttons) to users, but without success. I would be very glad for any help. Thanks.
Chris

Basically you can add your own default cell editor for the table which returns either the super method's component or one shared JButton.
One only has to know, that the used editor/view component is intended to be shared by several cells, and so should not conserve any state.

Similar Messages

  • Fitting JButton width to JToolBar width

    Hello everyone,
    In my application I need to have a vertical set of buttons (only one column), so I thought using JToolBar and JButton would be okay. Unfortunately, I would like to make JButtons to fit the whole width of JToolBox, and can't do this. I've looked through this forum, google, tried to chang BoxLayout, but nothing really works.
    Is the only solution to use JTable and put JButtons in it?
    Generally speaking- funcionality I'am currently trying to achieve is to get the list of users, who are 'clickable' (I mean, when I doubleclick on the user's nicname an Action is going to be launched)
    I hope anyone is going to help me :)
    regards
    MD

    I had forgotten to tell you, that the list of users may change dynamically.
    JToolBox is not an only solution, but at first I thought it'd be ok.
    What about JButton in JTable?
    According to JButtons in JLabel.
    I also thought about that solution, but...does any LayoutManager allows to change number of "rows" without repainting again? (when I add or remove any user)

  • Problem in JButton while changing look and feel to CDE/Motif

    In my application i'm using JButtons placed in JToolbar. I've setIcons for the JButtons. The top of the icons i.e the JButtons get hided while i changing the look & feel to CDE/Motif. But again if i change the look & feel to Metal, no problem is there. Expecting a favourable response from someone well versed / faced such problems earlier problems.
    Cheers
    sunil s

    Sounds suspiciously like you are setting absolute sizes for your buttons or elsewhere in application. Can you post code snippets showing how you layout your application.
    Cheers
    DB

  • Dynamic border for JToolbar buttons

    Hi,
    How can I make the border appear on a JButton within a JToolbar dynamically when the mouse is moved over the button and make the border dissapear when the mouse is moved away from the button?

    Hi,
    do this,
    toolbar.putClientProperty("JToolbar.isRollover", Boolean.TRUE);
    but this property is look and feel sensitive. This works with metal laf.

  • JToolBar trouble

    The problem is basically me trying to add a ToolBar and some tool bar buttons to a Frame in a GUI that I have designed. Any ideas as to why guys??? Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.util.*;
    public class DissertationInterface extends JFrame implements ActionListener
         private JPanel onePanel, twoPanel, bottomPanel;
           private JButton quit,search;
           JToolBar ToolBar = new JToolBar(); //the tool bar
           private BorderLayout layout;
           //Canvas that images should be drew on
           drawTheImages Dti;
         //Instances of other classes
         DatabaseComms2 db2 = new DatabaseComms2();
         Configuration cF = new Configuration();
           public DissertationInterface()
                setTitle("Find My Pics - University Application") ;
                layout = new BorderLayout(50,50);
                Container container = getContentPane();
                container.setLayout(layout);
                Dti = new drawTheImages();
              container.add(Dti);
                quit = new JButton("Quit");
                search = new JButton("Search");
                ToolBar = new JToolBar();
                addButtons(ToolBar);          //call to method see below
                //Create 4 panels
                onePanel = new JPanel();
                onePanel.setLayout(new GridLayout(5,2,5,5));
                twoPanel = new JPanel();
                twoPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 200, 200)) ;
                bottomPanel = new JPanel();
                bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
              //Create buttons and textfields
                bottomPanel.add(quit);
                quit.addActionListener(this);
                bottomPanel.add(search);
                search.addActionListener(this);
              twoPanel.add(ToolBar);  //Attempt to add toolbar
              //ToolBar.addWindowListener(this);
                //Add panels to window
                container.add(twoPanel,BorderLayout.NORTH);
                container.add(onePanel, BorderLayout.CENTER);
                container.add(bottomPanel, BorderLayout.SOUTH);
                setSize(350,350);
                setVisible(true);
            public void leaveWindow()
                 this.dispose() ;
            public static void main(String args[])
                DissertationInterface DI = new DissertationInterface();
                DI.setVisible(true);
              }//End
         protected void processWindowEvent(WindowEvent e)
                super.processWindowEvent(e);
                if(e.getID()== WindowEvent.WINDOW_CLOSING)
                      System.exit(0);
              }//End of processWindowEvent
    //METHOD TO ADD BUTTONS TO THE TOOL BAR
    protected void addButtons(JToolBar toolBar)
         JButton file,search,help;
        //first button
        file = new JButton("File");
        toolBar.add(file);
        //second button
        search = new JButton("Search");
        toolBar.add(search);
        //third button
        help = new JButton("Help");
        toolBar.add(help);
    }//End of class

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.util.*;
    public class martylan extends JFrame implements ActionListener {
      private JPanel onePanel, twoPanel, bottomPanel;
      private JButton quit, search;
      JToolBar toolBar = new JToolBar(); //the tool bar
      private BorderLayout layout;
      //Canvas that images should be drew on
    //  drawTheImages Dti;
      //Instances of other classes
    //  DatabaseComms2 db2 = new DatabaseComms2();
    //  Configuration cF = new Configuration();
      public martylan() {
        setTitle("Find My Pics - University Application") ;
        layout = new BorderLayout(/*50,50*/);
        Container container = getContentPane();
        container.setLayout(layout);
    //    Dti = new drawTheImages();
    //    container.add(Dti);
        quit = new JButton("Quit");
        search = new JButton("Search");
        toolBar = new JToolBar();
        addButtons(toolBar);          //call to method see below
        //Create 4 panels
        onePanel = new JPanel();
        onePanel.setBackground(Color.blue);
        onePanel.setLayout(new GridLayout(5,2,5,5));
        twoPanel = new JPanel();
        twoPanel.setBackground(Color.red);
        twoPanel.setPreferredSize(new Dimension(200,50));
        twoPanel.setLayout(new BorderLayout(/*200, 200*/)) ;
        bottomPanel = new JPanel();
        bottomPanel.setBackground(Color.yellow);
        bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
        //Create buttons and textfields
        bottomPanel.add(quit);
        quit.addActionListener(this);
        bottomPanel.add(search);
        search.addActionListener(this);
        twoPanel.add(toolBar, "North");  //Attempt to add toolbar
        //toolBar.addWindowListener(this);
        //Add panels to window
        container.add(twoPanel,BorderLayout.NORTH);
        container.add(onePanel, BorderLayout.CENTER);
        container.add(bottomPanel, BorderLayout.SOUTH);
        setSize(350,350);
        setLocationRelativeTo(null);
        setVisible(true);
      public void leaveWindow() {
        this.dispose() ;
      public static void main(String args[]) {
        martylan DI = new martylan();
        DI.setVisible(true);
      }//End
    protected void processWindowEvent(WindowEvent e) {
       super.processWindowEvent(e);
       if(e.getID()== WindowEvent.WINDOW_CLOSING) {
         System.exit(0);
    }//End of processWindowEvent
      //METHOD TO ADD BUTTONS TO THE TOOL BAR
      protected void addButtons(JToolBar toolBar) {
        JButton file, search, help;
        //first button
        file = new JButton("File");
        toolBar.add(file);
        //second button
        search = new JButton("Search");
        toolBar.add(search);
        //third button
        help = new JButton("Help");
        toolBar.add(help);
      public void actionPerformed(ActionEvent e) {
    }//End of class

  • Get JToolBar position in BorderLayout

    Greetings:
    I've a JToolBar put in a JPanel with BorderLayout. I would like to capture where the user last left the JToolBar, based in the 4 possible corners (+borders+); I've tried BorderLayout.getLayoutComponent (Container target, Object constraints) with not much luck (it always throws me an exception, not matter if I do it before or after the JtoolBar instantiation).
    Do anyone knows what can I do besides getting the raw x,y position? (or the propper use of BorderLayout.getLayoutComponent)
    Thanks a lot in advanced

    Greetings:
    You are right, DarrylBurke and I were assuming incorrectly the context. Here I put the full code: my sincere appologies about this.
    // java scope
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public abstract class ToolBarTest {
       public static void main(String[] args) {
          try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
          catch (Exception e) { }
          SwingUtilities.invokeLater(new Runnable() {
             public void run() { MainWin myWindow = new MainWin(" ToolBar Test");
                                 myWindow.pack();
                                 myWindow.setVisible(true);
    class MainWin extends JFrame {
          public BorderLayout toolBarPanelLayout = new BorderLayout();
          public JPanel toolBarPanel = new JPanel(toolBarPanelLayout);
          public JToolBar toolBar = new JToolBar(JToolBar.VERTICAL);
          public JButton buttonOpen = new JButton("Open"),
                         buttonSave = new JButton("Save"),
                         buttonPrint = new JButton(" Print");
          public JToolBar.Separator separator = new JToolBar.Separator();
    public MainWin (String mainWin_title) {
          Container framePanel = this.getContentPane();
          Insets buttons_Insets = new Insets(1, 1, 1, 1);
          this.setTitle(mainWin_title);
          this.setLocationRelativeTo(null);
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          // init.components
          toolBar.setRollover(true);
          // Identify if our toolBar is docked; for that, we check if it is dependant of our frame or
          // of the current L&F manager; when it is docked, it will be part of our frame's hierarchy,
          // else, it will be part of javax.swing.plaf.basic.BasicToolBarUI.ToolBarDialog
          // (controled by the current L&F manager).
         toolBar.addHierarchyListener(new HierarchyListener() {
             public void hierarchyChanged(HierarchyEvent e) {
                Window window = SwingUtilities.getWindowAncestor(toolBar);
                if (window == MainWin.this) {
                  // getLayoutComponent code here
                  System.out.println("ToolBarConstraints = " + toolBarPanelLayout.getLayoutComponent(toolBar));
                  System.out.println("ToolBarConstraints = " + toolBarPanelLayout.getConstraints(toolBar));
                } else if (window != null) { toolBar.setOrientation(JToolBar.HORIZONTAL); }
          buttonOpen.setMargin(buttons_Insets);
             buttonOpen.setBorder(BorderFactory.createTitledBorder(""));
          buttonSave.setMargin(buttons_Insets);
             buttonSave.setBorder(BorderFactory.createTitledBorder(""));
          buttonPrint.setMargin(buttons_Insets);
             buttonPrint.setBorder(BorderFactory.createTitledBorder(""));
          // set.components
          toolBar.add(buttonOpen);
             toolBar.add(buttonSave);
             toolBar.add(separator);
             toolBar.add(buttonPrint);
          framePanel.add(toolBar,BorderLayout.WEST);
    }

  • Multiple font colors

    what's up
    does anybody know how to display font in multiple colors in a Jtextarea or another text component every time i change the font color in my jtextarea it changes for all the words i want it to change for only the next words that i type.
    thanks

    the following sample might be useful to u. i am not sure whether this works for textarea.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class test extends JApplet
         private JTextPane pane;
         private JButton colors;
         private JToolBar tb;
         public void init()
              pane = new JTextPane();
              tb = new JToolBar(JToolBar.HORIZONTAL);
              colors=new JButton("Colors");
              colors.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        Color newColor = javax.swing.JColorChooser.showDialog(null,"Choose Text Color",Color.cyan);     
                                  if(newColor!=null){
                                            MutableAttributeSet attr = new SimpleAttributeSet();
                                            StyleConstants.setForeground(attr,newColor);
                                            pane.setCharacterAttributes(attr,false);
              tb.add(colors);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(tb,"North");
              getContentPane().add(pane,"Center");
    //<applet code=test.class width=300 height=300></applet>
    for more information follow this link.
    http://manning.spindoczine.com/sbe/files/uts2/Chapter20html/Chapter20.htm
    cheers
    sri

  • Home key not working in JTextPane?

    Hi all,
    I have a very simple example with a JTextPane. I call the method:
    pane.setPage("someHTMLPage.html");
    to load the html page. When I'm editing the JTextPane and press the "home" key, the cursor disapears. This only happens on the first line of text, and if you then press the right arrow key, the cursor appears again. But you can't input any text in the JTextPane when the cursor has disapeared.
    Is this a bug? Its a very simple example I'm using, so I can't see it being my code thats introducing the issue.
    any help?
    thanks,
    Justin

    Just adding the example I'm using.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Enumeration;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.JToolBar;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Element;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.html.HTML;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    import javax.swing.text.html.HTMLWriter;
    * Simple class to print out the html from the text pane.
    * Got the basic code to do this from a posting on the swing forms on the javasoft website.
    public class WISIWIGTextPane extends JFrame {
        private JTextPane pane;
        private JButton bold;
        private JButton italic;
        private JButton underline;
        private JButton dump;
        private JToolBar tb;
        private HTMLEditorKit kit;
        private HTMLDocument doc;
        public WISIWIGTextPane() {
            super("WISIWIGTextPane");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            init();
        public void init() {
            pane = new JTextPane();
            kit = (HTMLEditorKit)(pane.getEditorKitForContentType("text/html"));
            doc = (HTMLDocument)(kit.createDefaultDocument());
            pane.setEditorKit(kit);
            pane.setDocument(doc);
            try {
                pane.setPage("file:///c:/java/testingJava/TextSamplerDemoHelp.html"); //my html file
            catch(java.io.IOException e) {
                System.out.println(e.toString());
            tb = new JToolBar(JToolBar.HORIZONTAL);
            bold=new JButton(new StyledEditorKit.BoldAction());
            italic=new JButton(new StyledEditorKit.ItalicAction());
            underline=new JButton(new StyledEditorKit.UnderlineAction());
            dump=new JButton("Dump");
            // prints the underlying html code on the console for verifying
            dump.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println(pane.getText());
            tb.add(bold);
            tb.add(italic);
            tb.add(underline);
            tb.add(dump);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(tb,"North");
            getContentPane().add(new JScrollPane(pane),"Center");
        public static void main(String[] args) {
            new WISIWIGTextPane().setVisible(true);
    }

  • Printing black background on paper, instead of actual image

    hi,
    i am having a JPanel with some photos drawn on it using g.drawImage(..) method, for printing. while running the program the panel is showing fine on the screen. since in my room as i dont have a printer, i am printing with adobe printer in which the content to be printed will be saved as pdf file.
    Even the created pdf file while printing is showing perfectly what is supposed to be printed. but when i tried the same program and asked to print on real printer, strangely only a large full black background is printed on paper instead of the image.
    plz explain why such thing is happening.
    thanx.

    Here is sample code based on your description. Maybe you find some hints in it to help you.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class PrintPanel extends JFrame {
        public PrintPanel() {
            initComponents();
        private void initComponents() {
            toolBar = new JToolBar();
            printB = new JButton();
            panel = new MyPanel();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Print Panel");
            toolBar.setFloatable(false);
            printB.setText("Print");
            printB.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    printBActionPerformed(evt);
            toolBar.add(printB);
            getContentPane().add(toolBar, BorderLayout.NORTH);
            getContentPane().add(panel, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-375)/2, (screenSize.height-480)/2, 375, 480);
        private void printBActionPerformed(ActionEvent evt) {
            PrinterJob pj=PrinterJob.getPrinterJob();
            pj.setPrintable((Printable)panel);
            try{
                pj.print();
            }catch (PrinterException ex) {
                ex.printStackTrace();
        public static void main(String args[]) {new PrintPanel().setVisible(true);}
        private JButton printB;
        private JToolBar toolBar;
        private JPanel panel;
        class MyPanel extends JPanel implements Printable{
            MyPanel() {
                Toolkit T=this.getToolkit();
                img=T.getImage("c:\\javalogo.gif");
                MediaTracker mediaTracker = new MediaTracker(this);
                mediaTracker.addImage(img, 0);
                try {
                    mediaTracker.waitForID(0);
                } catch (InterruptedException ex) {
                    System.err.println(ex);
            public void paint(Graphics g) {
                g.drawImage(img, 150, 150, this);
            public int print(Graphics g, PageFormat pageFormat,
                    int pageIndex) throws PrinterException {
                if(pageIndex>0) {
                    return NO_SUCH_PAGE;
                paint(g);
                return Printable.PAGE_EXISTS;
            private Image img=null;
    }

  • KeyTyped Event: funny behaviour

    This should be a very simple question... but I am stuck with it.
    I want to implement the usual feature of enabling a button only if a text field is not empty. I suppose you all have seen this before.
    I am catching the KeyTyped event and in the event handler I am checking for the length of the text. This is the code inside the handler:
    String txt=myTextField.getText();
    myButton.setEnabled(txt.length()>0);
    So yes, it works, but with a funny behaviour: the button is enabled only after the second keystroke, that is, when the length of the text is >=2 and not >0. A quick explanation is that my event handler is being called before the event handler of the textfield itself so at that moment the text is still empty. But when pressing the "backspace" key... it works fine, so the theory is wrong!!
    My workaround is to catch the KeyReleased event... but visual effect is not so satisfactory, and anyway, why is this happening?
    And what is the "official" way of implementing this trick?
    Thanks in advance,
    Luis.
    (P.S.: I am using a JTextField and a JButton, and have tested this with JDK 1.2 and 1.4 with the same results.)

    You'd want to do something like this:
    JTextField watchedField = new JTextField();
    // construct the action
    FieldWatcherAction watcher = new FieldWatcherAction( watchedField );
    // make a button with the action
    JButton b = new JButton( watcher );
    // add a button to a toolbar with the action
    jtoolBar.add( watcher );
    // etc...
    class FieldWatcherAction extends AbstractAction implements DocumentListener
      JTextField  field;
      public FieldWatcherAction( JTextField f )
        super( "", someIcon );
        setEnabled( false );
        field = f;
        field.getDocument().addDocumentListener( this );
      protected void updateState()
        setEnabled( field.getDocument().getLength() > 0 );
      public void insertUpdate( DocumentEvent evt )
        updateState();
      public void removeUpdate( DocumentEvent evt )
        updateState().;
      public void changedUpdate( DocumentEvent evt )
        updateState();
    }The action would need to be fleshed out more, obviously. You'd probably want to add text for a label ( empty string in super call in constructor ), define the icon ( second arg in super call ). You can also set tooltip text and other things. All of this can be changed by editing various properties of the action. Relevant constants would be:
    javax.swing.Action.ACCELERATOR_KEY  // key accelerator for JMenuItems
    javax.swing.Action.MNEMONIC_KEY // mnemonic key for JMenuItems
    javax.swing.Action.NAME // JButton text or JMenuItem text
    javax.swing.Action.SHORT_DESCRIPTION // Tooltip text
    javax.swing.Action.SMALL_ICON // image icon for JButton, JMenuItem and JToolBar buttons.

  • JProgressBar and ObserverPattern in multiple document app??

    Hi,
    I'm working on a multiple document application with jInternalFrames. There is one very time-consuming process and therefore I'd like to show a progressbar for the user to know, that the programm is still running.
    So Icreated a seperate internalFrame with a jProgressBar and I implemented the observer pattern.
    Now the problem is: my time-consuming process (which is in the observable-class) notifies the internalFrame whenever one percent of work is done,
    and the programm even enters the update method of the internal frame. In this update method i set the value of the
    progress bar, but nothing happens. I tried a repaint() and even a paintImmediately() but nothing happens until
    my time-consuming process is done. That's not exactly what i call a progressbar... ;-) It is even worse as the whole view of the application is faulty once I minimized and then resized the main window while my time-consuming process is running.
    So I already found some articles and I fear I have to work with threads. But how?
    can anyone explain to me what method I have to run as a thread and how can I refresh my internalFrame respectively the progressbar then?
    I hope anyone can help me...

    * Progress_Test.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Progress_Test extends JFrame {
        public Progress_Test() {
            initComponents();
        private void initComponents() {
            desktop = new JDesktopPane();
            internalFrame = new JInternalFrame();
            panel = new JPanel();
            progressBar = new JProgressBar();
            progressBar.setVisible(false);
            toolbar = new JToolBar();
            startBtn = new JButton();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Test Progress");
            internalFrame.setPreferredSize(new Dimension(200, 100));
            internalFrame.setVisible(true);
            panel.add(progressBar);
            internalFrame.getContentPane().add(panel, BorderLayout.CENTER);
            startBtn.setText("Start");
            startBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    startBtnActionPerformed(evt);
            toolbar.add(startBtn);
            internalFrame.getContentPane().add(toolbar, BorderLayout.NORTH);
            internalFrame.setBounds(0, 0, 200, 100);
            desktop.add(internalFrame, JLayeredPane.DEFAULT_LAYER);
            getContentPane().add(desktop, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
        private void startBtnActionPerformed(ActionEvent evt) {
            if( ltThread == null || !ltThread.isAlive() ){
                progressBar.setValue(0);
                LongTask lt = new LongTask();
                ltThread = new Thread(lt);
                ltThread.start();
        public static void main(String args[]) {
            new Progress_Test().setVisible(true);
        private JDesktopPane desktop;
        private JInternalFrame internalFrame;
        private JPanel panel;
        private JProgressBar progressBar;
        private JButton startBtn;
        private JToolBar toolbar;
        private Thread ltThread;
        public class LongTask implements Runnable{
            public LongTask() {
                progressBar.setMaximum(max);
            public void run(){
                progressBar.setVisible(true);
                int n=0;
                while ( n<max ){
                    n++;
                    progressBar.setValue(n);
                    try{Thread.sleep(1000);}catch(Exception ex){}
                progressBar.setVisible(false);
            private int max=10;
    }

  • HTML-TAG br

    Hello,
    I found out a strange thing in my HTML-Editor-Applet.
    I defined shift+ENTER as a <BR>-Tag (break row):
    htmlKit.insertHTML((HTMLDocument)editPane.getDocument(), editPane.getCaretPosition(),
    "<br>",0,0, HTML.Tag.BR);
    The strange thing is he following case:
    I've written some text, press shift+RETURN, writing some other text and again press shift+RETURN.
    When I press shift+RETURN the second time all he text I've written after the first shift+RETURN is deleted and the caret change it's position.
    Any ideas what this could be?
    thank you in advance.
    J&ouml;rn

    in case u still have problems in inserting the <br> tag, i am sending an example which is working perfectly. much of the code is taken from the discussion forum..thanks to richard and drew. http://forums.java.sun.com/thread.jsp?forum=57&thread=126795
    public class breakTest extends JApplet
         private JTextPane pane;
         private JButton dump;
         private JToolBar tb;
         private HTMLEditorKit kit;
         private HTMLDocument doc;
    public void init()
         pane = new JTextPane();
         kit = (HTMLEditorKit)(pane.getEditorKitForContentType("text/html"));
         doc = (HTMLDocument)(kit.createDefaultDocument());
         pane.setEditorKit(kit);
         pane.setDocument(doc);
         tb = new JToolBar(JToolBar.HORIZONTAL);
         dump=new JButton("Dump");
         //prints the underlying html code on the console for verifying
         dump.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   System.out.println(pane.getText());
         tb.add(dump);
         getContentPane().setLayout(new BorderLayout());
         getContentPane().add(tb,"North");
         getContentPane().add(new JScrollPane(pane),"Center");
         breakAction brAction = new breakAction();
         Keymap map = pane.getKeymap();
         KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 1);
         map.removeKeyStrokeBinding(key);
         map.addActionForKeyStroke(key, brAction);
    public void fireAction(String name)
         Action[] actions = pane.getActions();
         Hashtable actionHash = new Hashtable();
         int count = actions.length;
         for(int h = 0; h < count; h++)
              actionHash.put(actions[h].getValue(Action.NAME), actions[h]);
         Action action=(Action)actionHash.get(name);
         action.actionPerformed(new ActionEvent(this,0,"blah"));
    //inner class for break action
    class breakAction extends AbstractAction
         public breakAction()
              super();
         public void actionPerformed(ActionEvent event)
              int offset = pane.getSelectionStart();
              HTMLDocument doc = (HTMLDocument)pane.getDocument();
              EditorKit kit = pane.getEditorKit();
              if(kit instanceof HTMLEditorKit){
                   try{
                        ((HTMLEditorKit)kit).insertHTML(doc, offset, "<br>", 0, 0, HTML.Tag.BR);
                        fireAction("caret-down");
                        pane.requestFocus();
                        pane.setCaretPosition(offset+1);
                        }catch(Exception e){
    //<applet code=breakTest.class width=500 height=300></applet>
    hth

  • Interactive with 2 forms

    Dear all,
    I have 2 forms, the first one for filling personal data, the second one for selecting the an email from a list of emails.
    How could I calling the second form for selecting the email and return the email to the first form?
    Thanks a lot :)

    * Window_1.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Window_1 extends JFrame {
        public Window_1() {
            initComponents();
            setVisible(true);
            //setup dialog:
            JDialog jDialog1 = new MyDialog(this,"Test",true);
            jDialog1.setSize(200,200);
            jDialog1.setLocationRelativeTo(this);
            jDialog1.setVisible(true);
        private void initComponents() {
            textarea = new JTextArea();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            getContentPane().add(textarea, BorderLayout.CENTER);
            setSize(400,300);
            setLocationRelativeTo(null);
        public void setEmail(String email){
            textarea.append(email+"\n");
        public static void main(String args[]) { new Window_1(); }
        private JTextArea textarea;
    class MyDialog extends JDialog{
        MyDialog(JFrame parent, String title, boolean modal ){
            super(parent,title,modal);
            initComponents();
        private void initComponents(){
            toolbar = new JToolBar();
            button = new JButton();
            button.setText("Select");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    buttonActionPerformed(evt);
            toolbar.add(button);
            getContentPane().add(toolbar, BorderLayout.NORTH);
        private void buttonActionPerformed(ActionEvent evt) {
            ((Window_1)getParent()).setEmail("[email protected]");
        private JButton button;
        private JToolBar toolbar;
    }

  • Getting instance of Jframe ContetntPane

    Hi All,
    Is it possible to comapre
    if(getParent() instanceof JFrame.ContentPane)
    like below
    if(getParent() instanceof JSplitPane)
    basically i have a button in a class say classA extending jpanel whose action method should check th parent of class.
    So I have class A which has JFrame frame whose contentPane is provided with instance of classA .
    so if classA's parent==JFrame .ContentPane() i need to close the frame.
    Any idea if it is pssible to do compare
    getParent() instanceof JFrame.ContentPane

    Thank alot for your response.
    Please see my dummy code below
    public class xyz{
    JFrame frame;
    xyz(){
    frame=new JFrame();
    public displayResult(ArrayList resultFromdb)
    ArrayList emptyArraylist = new ArrayList();
    JPanelA Ainstance 1= new JPanelA (emptyArraylist );
    JPanelA Ainstance 1= new JPanelA (resultFromdb);
    frame.getContentPane().setName("displaySearchresultPanel");
    frame.setContentPane( Ainstance 1);
    frame.setContentPane( Ainstance 2);
    frame.repaint();
    frame.setVisible(true);
    public class JPanelA extends JPanel{
    JButton closeButton;
    JToolBar toolbar;
    JScrollPane scroll;
    JPanelA (ArrayList list){
    scroll=newJScrollPane ();
    //display aaraylist in jtable and put in scrollpane
    closeButton=new JButton();
    toolbar=new JToolBar();
    this.add(scroll);
    this.add(toolbar);
    closeButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    System.out.println("parent name "+getParent().getName()) ;
    if(getParent().getName().equals("displaySearchresultPanel")) {
    getParent().setVisible(false);
    I set the name of the container as
    frame.getContentPane().setName("displaySearchresultPanel") and'
    if I do frame.setContent("Jpanel A obect") control doesnot go inside close button action method as getParent in JPanelA is insterpreted as an instance of LayeredPane instead of contentPane
    how ever If i do
    frame.getContentPane.add(("JpanelA obect") getParent in JpanelA class is interpreted as contentPane and i can get the button workng
    Any idea how can I make the button working with frame.setContentPane(JPanel AObject) and why container becomes layeredPane when assigned as frame.setContentPane(JPanel A object)

  • Problem in setting the printer

    Hi,
    I am new to swings and am trying to print my table using PrintJob class. In this I will get the printer name. So I have to set that as a printer to do the job.
    I am able to print by selecting the printer in printDialog but I want to give my printer and I dont want that printDialog box. Plz tell me solution.
    As from the docs, i came to know that if we remove printdialog(), it wont show you the dialog box, but its talking the default one, my case is it should take the user input.
    Here is my code and working fine.
    public void print(String printer){
    // In this I have to set printer as the printer to do the job by suppresing the print dialog.
    PrinterJob pj = PrinterJob.getPrinterJob();
    PageFormat pf = pj.defaultPage();
    pj.setPrintable(this, pf);
    if (pj.printDialog()) {
    try {
         pj.print();
    } catch (Exception e) {
    Thanks in advance..
    Raj.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import java.io.*;
    import java.util.*;
    import javax.print.*;
    import javax.swing.*;
    public class Print_Demo extends JFrame {
        public Print_Demo() {
            initComponents();
        private void initComponents() {
            toolBar = new JToolBar();
            printB = new JButton();
            printerField = new JTextField("Win32 Printer : HP DeskJet 610C");
            panel = new MyPanel();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Print Demo");
            toolBar.setFloatable(false);
            printB.setText("Print");
            printB.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    printBActionPerformed(evt);
            toolBar.add(printB);
            toolBar.add(printerField);
            getContentPane().add(toolBar, BorderLayout.NORTH);
            getContentPane().add(panel, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-500)/2, (screenSize.height-500)/2, 500, 500);
        private void printBActionPerformed(ActionEvent evt) {
            PrinterJob pj=PrinterJob.getPrinterJob();
            pj.setPrintable((Printable)panel);
            PrintService[] services = pj.lookupPrintServices();
            boolean ok = false;
            for( int i=0; i < services.length; i++ ){
                System.out.println("Available PrintService: '"+services[i]+"'");
                if(services.toString().equalsIgnoreCase( printerField.getText() ) ){
    try{
    pj.setPrintService(services[i]);
    ok=true;
    }catch(PrinterException ex){
    System.out.println(ex.getMessage());
    if(ok){
    try{
    pj.print();
    }catch (PrinterException ex) {
    ex.printStackTrace();
    }else{
    JOptionPane.showMessageDialog(this,"Printer not available");
    public static void main(String args[]) {
    new Print_Demo().setVisible(true);
    private JButton printB;
    private JToolBar toolBar;
    private JPanel panel;
    private JTextField printerField;
    class MyPanel extends JPanel implements Printable{
    public void paint(Graphics g) {
    g.drawRect(100,100, 100,100);
    public int print(Graphics g, PageFormat pageFormat,
    int pageIndex) throws PrinterException {
    if(pageIndex>0) {
    return NO_SUCH_PAGE;
    paint(g);
    return Printable.PAGE_EXISTS;

Maybe you are looking for

  • Looking for some advice dealing with Kernel Panics

    Hi there! I'm looking for some help regarding constant kernel panics I've been getting on my machine. It has been happening pretty regularly for the last month or so, occuring sometimes three times in one day and other times none. I've been looking t

  • CS4 - Bring back old way of masking PLEASE!!!!! (or at least a toggle/pref)

    Please, please, please add a preference or toggle to allow CS4 to mask objects in the old way. Whilst I can see the benefits to CS4s new way of masking it also has some big disadvantages for many reasons. It would be handy if there was a toggle or pr

  • How to install Nokia suite on android tablett?

    I want to install the Nokia suite or something similar to my new android tablett PC so that I can use the Nokia E90 mobile phone as modem to go into the internet. I copied the .exe file onto the tablett but the tablett PC does not start the nokia exe

  • Border became thicker after converting to pdf

    Hi, I am using Adobe Acrobat 6.0 Professional. I converted an excel sheet which consist of text, number, colored border (thin border). After converting to pdf, I have found that all the borders in the pdf file which i just created become thicker. I w

  • Snow Leopard Prores 4444 Gamma Shift Nightmare

    I've run into a nightmare with significant gamma shifts wrecking a lot of work we're trying to export using the Prores codec and After Effects CS3 (and CS4). I found this supposed fix, but it has not solved my problems: http://blogs.adobe.com/toddkop