Funny Behaviour (scrollpane and jbutton tricking me)

Hi,
I'm close to freaking out. I'm building a GUI that acts as kind of data base editor. There is a combobox to select a table, a scrollpane for viewing and thre buttons to add/remov/edit rows. My test data comes from a Properties object and is transferred into a TableModel in order to create and display the table.
I pick a table from the comobox and the the table is displayed and the buttons are enabled. As soon as the mouse leaves the scrollpane and enters it or one of the buttons again the buttons become disabled and the table disappears. Picking the table again shows everything again, apart from leaving the add-Button disabled from time to time.
There is a method that is called when the user selects no table but the initial "Select a table" item in the combo box. This method is NOT called (there is debug output to indicate this). There is no MouseListener or MouseMotionListener added to any component.
What is this??? Why are sometimes only 2 buttons enabled instead of all three?
This is the event handling code
private void displayCategory(String category){
        // get category data
        Properties data = getTestProps();
        // create table
        ProfileTableModel ptm = new ProfileTableModel(data);
        ptm.addTableModelListener(this);
        // show table
        JTable table = new JTable(ptm);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting()) return;
                ListSelectionModel lsm =
                        (ListSelectionModel)e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.err.println("GUI no row selected");
                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    System.err.println("GUI row #" + selectedRow + " selected");
        profilePanel.displayTable(table, true);
    private void clearDisplay(){
        System.err.println("GUI DISPLAY NOTHING");
        profilePanel.displayNothing();
    public void itemStateChanged(ItemEvent e) {
        System.err.println("GUI ITEM STATE CHANGED " + e);
        if (e.getStateChange() == ItemEvent.SELECTED){
            if (e.getItem() instanceof BoxItem){
                final String cmd = ((BoxItem)e.getItem()).getCommand();
                (new Thread(new Runnable(){public void run(){displayCategory(cmd);}})).start();
            } else {
                clearDisplay();
    }This is the GUI code
    protected void displayTable(JTable table, boolean editable){
        addButton.setEnabled(editable);
        removeButton.setEnabled(editable);
        editButton.setEnabled(editable);
        table.setPreferredScrollableViewportSize(new Dimension(400, 330));
        scroll.setViewportView(table);
    protected void displayNothing(){
        System.err.println("GUI display nothing . . . . . . . . . . .");
        scroll.setViewportView(blank);
        addButton.setEnabled(false);
        removeButton.setEnabled(false);
        editButton.setEnabled(false);
    }Cheers,
Joachim

There is a method that is called when the user
selects no table but the initial "Select a table"
item in the combo box. This method is NOT called
But this method displayNothing() is the only place where buttons are
disabled (at least acording to the posted code fragments).
How can buttons be disabled when this method is not called?
You see, it's difficult to test your code because it is not a self-contained
compilable example.
A short self-contained compilable example often helps you and
others to discover an otherwise mysterious bug.

Similar Messages

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

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • My Ipad wont retrieve my new emails and if I try to check passwords in Settings, the settings window only stays open open for a second or two and the automatically closes. Any help on how to fix. I tried the turn off and on trick and that didn'

    My Ipad wont retrieve my new emails and if I try to check passwords in Settings, the settings window only stays open open for a second or two and the automatically closes. Any help on how to fix. I tried the turn off and on trick and that didn't work either. Thanks for any help.

    Try reset iPad
    Hold down the Sleep/Wake button and the Home button at the same time for at least ten seconds, until the Apple logo appears
    Note: Data will not be affected.

  • Resizing ScrollPane and Dimension dynamically

    I am currently making a scrollbar program using ScrollPane and Dimension. I have to use those classes.
    When I click "ok" button, that calls dc.enlarge(500,800) method. But it doesn't work.
    When it is clicked, Dimension object should be changed and the panel has to show Horizotal
    and Vertical scrollbar according to the width and height parameters.
    Of course, the size will be calculated by the String contents object's rows and width. But it does not work.
    How to resize the Dimension and How to display the Horizontal, Vertical scrollbar accoring to dc.enlarge's parameters?
    Plz... help me...
    -------------- ScrollerTest.java -----------------------------------------------
    import java.awt.*;
    import java.applet.Applet;
    public class ScrollerTest extends Applet {
       public Scroller sc = null;
        public void init() {
            sc = new Scroller(700,250);
            sc.setVisible(true);
         add(sc);         
    }-------------- Scroller.java -----------------------------------------------
    import java.awt.*;
    import java.awt.Window;
    import java.applet.Applet;
    import java.awt.event.*;
    public class Scroller extends Panel implements  ActionListener {
        private Button btOk;   
        private int width = 0;
        private int height = 0;   
        private DrawCanvas dc;   
        public Scroller(int width, int height){   
            this.width = width;
            this.height = height;   
            dc = new DrawCanvas(width, height);
            setNewsContents();                           
        private void setNewsContents() {
            setLayout(new BorderLayout());
            ScrollPane scroller = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);       
            scroller.add(dc);
            Adjustable vadjust = scroller.getVAdjustable();
            Adjustable hadjust = scroller.getHAdjustable();
            hadjust.setUnitIncrement(10);
            vadjust.setUnitIncrement(10);
            scroller.setSize(615     , 272);
            btOk = new Button("ok");
            btOk.addActionListener(this);
            add("Center", scroller);
            add("South", btOk);       
        public void actionPerformed(ActionEvent event) {
            if(event.getSource()==btOk) {
                dc.enlarge(500,800);
                dc.validate();
    }    -------------- DrawCanvas.java -----------------------------------------------
    import java.awt.*;
    class DrawCanvas extends Component {
        private int width = 0;
        private int height = 0;
        private Dimension d;
        public DrawCanvas(int width, int height) {
            this.width = width;
            this.height = height;
       Dimension theSize = new Dimension(300, 200);   
       public Dimension getPreferredSize() {
            return new Dimension(width,height);               
       public void enlarge(int width, int height) {       
            theSize.width =  width;
            theSize.height = height;
            setSize(theSize);       
        public void update(Graphics g) {
            paint(g);
        public void paint(Graphics g) {       
            Rectangle r = getBounds();       
            String contents[] = {
            "addition to its usual stable of Clydesdale horses, the company will also enlist help this year ",
            "from racing star Dale Earnhardt Jr., some beer-thieving crabs and a scary hitchhiker.",       
            "The Super Bowl represents an enormous commitment for Budweiser. Bob Lachky, chief creative" ,
            "officer of Anheuser-Busch, said the St. Louis-based brewer has been advertising on the game since 1976 and has been the exclusive alcoholic beverage sponsor since 1989",
            "since 1976 and has been the exclusive alcoholic beverage sponsor since 1989, an arrangement that runs through 2012.",
            "It's important to us because it kicks off our selling season, it's the best platform",
            "possible to launch new ideas or to sustain existing campaigns, and it's absolutely the most efficient way to reach the most  it's absolutely the most efficient way to reach the most",
            "adult consumers in one sitting,",
            "Despite the rise of cable, the Internet other media to compete with broadcast television iewers and enticing a huge array of marketers ",
            ", the Super Bowl remains the most-viewed media event all year, drawing in some 90 million ",
            "viewers and enticing a huge array of marketers to pony up the big bucks for an ad",
            ", the price of which is running as high as $2.6 million for this year's broadcast",
            "on CBS Corp.'s CBS network, up slightly from about a top price of about $2.5 million last year.",
            "Comedian Carlos Mencia, of the Comedy Central show  gets ",
            "a big break with a spot set in a classroom. Lachky predicts that Mencia will get an enormous boost Lachky predicts that Mencia will get an enormous boost ",
            "following the appearance, which similarly did wonders for Cedric the Entertainer.",
            "And what would Budweiser Super Bowl ads be without some animated critters? This year, a ga",
            "ng of mischievous red crabs turn up on a beach to carry off a cooler full of beers. As in past years, Bud is keeping many ",
            g.setColor(new Color(226,250,255));
            g.fillRect(0, 0, r.width, r.height);
            g.setColor(new Color(233,231,224));            
            int line = 35;
            int line_1 = 39;
            for (int i = 0; i < contents.length; i++) {       
                 g.setColor(Color.BLACK);
                 g.drawString(contents, 5,line);
         g.setColor(new Color(233,231,224));
         g.drawLine(0,line_1,605,line_1);
         line += 20;
         line_1 += 20;

    I am currently making a scrollbar program using ScrollPane and Dimension. I have to use those classes.
    When I click "ok" button, that calls dc.enlarge(500,800) method. But it doesn't work.
    When it is clicked, Dimension object should be changed and the panel has to show Horizotal
    and Vertical scrollbar according to the width and height parameters.
    Of course, the size will be calculated by the String contents object's rows and width. But it does not work.
    How to resize the Dimension and How to display the Horizontal, Vertical scrollbar accoring to dc.enlarge's parameters?
    Plz... help me...
    -------------- ScrollerTest.java -----------------------------------------------
    import java.awt.*;
    import java.applet.Applet;
    public class ScrollerTest extends Applet {
       public Scroller sc = null;
        public void init() {
            sc = new Scroller(700,250);
            sc.setVisible(true);
         add(sc);         
    }-------------- Scroller.java -----------------------------------------------
    import java.awt.*;
    import java.awt.Window;
    import java.applet.Applet;
    import java.awt.event.*;
    public class Scroller extends Panel implements  ActionListener {
        private Button btOk;   
        private int width = 0;
        private int height = 0;   
        private DrawCanvas dc;   
        public Scroller(int width, int height){   
            this.width = width;
            this.height = height;   
            dc = new DrawCanvas(width, height);
            setNewsContents();                           
        private void setNewsContents() {
            setLayout(new BorderLayout());
            ScrollPane scroller = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);       
            scroller.add(dc);
            Adjustable vadjust = scroller.getVAdjustable();
            Adjustable hadjust = scroller.getHAdjustable();
            hadjust.setUnitIncrement(10);
            vadjust.setUnitIncrement(10);
            scroller.setSize(615     , 272);
            btOk = new Button("ok");
            btOk.addActionListener(this);
            add("Center", scroller);
            add("South", btOk);       
        public void actionPerformed(ActionEvent event) {
            if(event.getSource()==btOk) {
                dc.enlarge(500,800);
                dc.validate();
    }    -------------- DrawCanvas.java -----------------------------------------------
    import java.awt.*;
    class DrawCanvas extends Component {
        private int width = 0;
        private int height = 0;
        private Dimension d;
        public DrawCanvas(int width, int height) {
            this.width = width;
            this.height = height;
       Dimension theSize = new Dimension(300, 200);   
       public Dimension getPreferredSize() {
            return new Dimension(width,height);               
       public void enlarge(int width, int height) {       
            theSize.width =  width;
            theSize.height = height;
            setSize(theSize);       
        public void update(Graphics g) {
            paint(g);
        public void paint(Graphics g) {       
            Rectangle r = getBounds();       
            String contents[] = {
            "addition to its usual stable of Clydesdale horses, the company will also enlist help this year ",
            "from racing star Dale Earnhardt Jr., some beer-thieving crabs and a scary hitchhiker.",       
            "The Super Bowl represents an enormous commitment for Budweiser. Bob Lachky, chief creative" ,
            "officer of Anheuser-Busch, said the St. Louis-based brewer has been advertising on the game since 1976 and has been the exclusive alcoholic beverage sponsor since 1989",
            "since 1976 and has been the exclusive alcoholic beverage sponsor since 1989, an arrangement that runs through 2012.",
            "It's important to us because it kicks off our selling season, it's the best platform",
            "possible to launch new ideas or to sustain existing campaigns, and it's absolutely the most efficient way to reach the most  it's absolutely the most efficient way to reach the most",
            "adult consumers in one sitting,",
            "Despite the rise of cable, the Internet other media to compete with broadcast television iewers and enticing a huge array of marketers ",
            ", the Super Bowl remains the most-viewed media event all year, drawing in some 90 million ",
            "viewers and enticing a huge array of marketers to pony up the big bucks for an ad",
            ", the price of which is running as high as $2.6 million for this year's broadcast",
            "on CBS Corp.'s CBS network, up slightly from about a top price of about $2.5 million last year.",
            "Comedian Carlos Mencia, of the Comedy Central show  gets ",
            "a big break with a spot set in a classroom. Lachky predicts that Mencia will get an enormous boost Lachky predicts that Mencia will get an enormous boost ",
            "following the appearance, which similarly did wonders for Cedric the Entertainer.",
            "And what would Budweiser Super Bowl ads be without some animated critters? This year, a ga",
            "ng of mischievous red crabs turn up on a beach to carry off a cooler full of beers. As in past years, Bud is keeping many ",
            g.setColor(new Color(226,250,255));
            g.fillRect(0, 0, r.width, r.height);
            g.setColor(new Color(233,231,224));            
            int line = 35;
            int line_1 = 39;
            for (int i = 0; i < contents.length; i++) {       
                 g.setColor(Color.BLACK);
                 g.drawString(contents, 5,line);
         g.setColor(new Color(233,231,224));
         g.drawLine(0,line_1,605,line_1);
         line += 20;
         line_1 += 20;

  • Resizing ScrollPane and Dimension

    I am currently making a scrollbar program using ScrollPane and Dimension. I have to use those classes.
    When I click "ok" button, that calls dc.enlarge(500,800) method. But it doesn't work.
    When it is clicked, Dimension object should be changed and the panel has to show Horizotal
    and Vertical scrollbar according to the width and height parameters.
    Of course, the size will be calculated by the String contents object's rows and width. But it does not work.
    How to resize the Dimension and How to display the Horizontal, Vertical scrollbar accoring to dc.enlarge's parameters?
    Plz... help me...
    -------------- ScrollerTest.java -----------------------------------------------
    import java.awt.*;
    import java.applet.Applet;
    public class ScrollerTest extends Applet {
       public Scroller sc = null;
        public void init() {
            sc = new Scroller(700,250);
            sc.setVisible(true);
         add(sc);         
    }-------------- Scroller.java -----------------------------------------------
    import java.awt.*;
    import java.awt.Window;
    import java.applet.Applet;
    import java.awt.event.*;
    public class Scroller extends Panel implements  ActionListener {
        private Button btOk;   
        private int width = 0;
        private int height = 0;   
        private DrawCanvas dc;   
        public Scroller(int width, int height){   
            this.width = width;
            this.height = height;   
            dc = new DrawCanvas(width, height);
            setNewsContents();                           
        private void setNewsContents() {
            setLayout(new BorderLayout());
            ScrollPane scroller = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);       
            scroller.add(dc);
            Adjustable vadjust = scroller.getVAdjustable();
            Adjustable hadjust = scroller.getHAdjustable();
            hadjust.setUnitIncrement(10);
            vadjust.setUnitIncrement(10);
            scroller.setSize(615     , 272);
            btOk = new Button("ok");
            btOk.addActionListener(this);
            add("Center", scroller);
            add("South", btOk);       
        public void actionPerformed(ActionEvent event) {
            if(event.getSource()==btOk) {
                dc.enlarge(500,800);
                dc.validate();
    }    -------------- DrawCanvas.java -----------------------------------------------
    import java.awt.*;
    class DrawCanvas extends Component {
        private int width = 0;
        private int height = 0;
        private Dimension d;
        public DrawCanvas(int width, int height) {
            this.width = width;
            this.height = height;
       Dimension theSize = new Dimension(300, 200);   
       public Dimension getPreferredSize() {
            return new Dimension(width,height);               
       public void enlarge(int width, int height) {       
            theSize.width =  width;
            theSize.height = height;
            setSize(theSize);       
        public void update(Graphics g) {
            paint(g);
        public void paint(Graphics g) {       
            Rectangle r = getBounds();       
            String contents[] = {
            "addition to its usual stable of Clydesdale horses, the company will also enlist help this year ",
            "from racing star Dale Earnhardt Jr., some beer-thieving crabs and a scary hitchhiker.",       
            "The Super Bowl represents an enormous commitment for Budweiser. Bob Lachky, chief creative" ,
            "officer of Anheuser-Busch, said the St. Louis-based brewer has been advertising on the game since 1976 and has been the exclusive alcoholic beverage sponsor since 1989",
            "since 1976 and has been the exclusive alcoholic beverage sponsor since 1989, an arrangement that runs through 2012.",
            "It's important to us because it kicks off our selling season, it's the best platform",
            "possible to launch new ideas or to sustain existing campaigns, and it's absolutely the most efficient way to reach the most  it's absolutely the most efficient way to reach the most",
            "adult consumers in one sitting,",
            "Despite the rise of cable, the Internet other media to compete with broadcast television iewers and enticing a huge array of marketers ",
            ", the Super Bowl remains the most-viewed media event all year, drawing in some 90 million ",
            "viewers and enticing a huge array of marketers to pony up the big bucks for an ad",
            ", the price of which is running as high as $2.6 million for this year's broadcast",
            "on CBS Corp.'s CBS network, up slightly from about a top price of about $2.5 million last year.",
            "Comedian Carlos Mencia, of the Comedy Central show  gets ",
            "a big break with a spot set in a classroom. Lachky predicts that Mencia will get an enormous boost Lachky predicts that Mencia will get an enormous boost ",
            "following the appearance, which similarly did wonders for Cedric the Entertainer.",
            "And what would Budweiser Super Bowl ads be without some animated critters? This year, a ga",
            "ng of mischievous red crabs turn up on a beach to carry off a cooler full of beers. As in past years, Bud is keeping many ",
            g.setColor(new Color(226,250,255));
            g.fillRect(0, 0, r.width, r.height);
            g.setColor(new Color(233,231,224));            
            int line = 35;
            int line_1 = 39;
            for (int i = 0; i < contents.length; i++) {       
                 g.setColor(Color.BLACK);
                 g.drawString(contents, 5,line);
         g.setColor(new Color(233,231,224));
         g.drawLine(0,line_1,605,line_1);
         line += 20;
         line_1 += 20;

    The class names have been changed so you can run this as-is without name-clashing.
    //  <applet code="ST" width="720" height="300"></applet>
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    public class ST extends Applet {
        public ScrollerRx sc;
        public void init() {
            sc = new ScrollerRx(700,250);
            add(sc);
    class ScrollerRx extends Panel implements ActionListener {
        private Button btOk;
        private DrawCanvasRx dc;
        public ScrollerRx(int width, int height) {
            dc = new DrawCanvasRx(width, height);
            setNewsContents();
        private void setNewsContents() {
            setLayout(new BorderLayout());
            ScrollPane scroller = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
            scroller.add(dc);
            Adjustable vadjust = scroller.getVAdjustable();
            Adjustable hadjust = scroller.getHAdjustable();
            hadjust.setUnitIncrement(10);
            vadjust.setUnitIncrement(10);
            scroller.setSize(615, 272);
            btOk = new Button("ok");
            btOk.addActionListener(this);
            add("Center", scroller);
            add("South", btOk);
        public void actionPerformed(ActionEvent event) {
            if(event.getSource()==btOk) {
                dc.enlarge(500,800);
                // validate is a Container method.
                validate();
    class DrawCanvasRx extends Component {
        Dimension theSize = new Dimension(300, 200);
        String[] contents = {
            "addition to its usual stable of Clydesdale horses, the company will " +
            "also enlist help this year ",
            "from racing star Dale Earnhardt Jr., some beer-thieving crabs and a " +
            "scary hitchhiker.",       
            "The Super Bowl represents an enormous commitment for Budweiser. Bob " +
            "Lachky, chief creative" ,
            "officer of Anheuser-Busch, said the St. Louis-based brewer has been " +
            "advertising on the game since 1976 and has been the exclusive alcoholic " +
            "beverage sponsor since 1989",
            "since 1976 and has been the exclusive alcoholic beverage sponsor since " +
            "1989, an arrangement that runs through 2012.",
            "It's important to us because it kicks off our selling season, it's the " +
            "best platform",
            "possible to launch new ideas or to sustain existing campaigns, and it's " +
            "absolutely the most efficient way to reach the most  it's absolutely " +
            "the most efficient way to reach the most",
            "adult consumers in one sitting,",
            "Despite the rise of cable, the Internet other media to compete with " +
            "broadcast television iewers and enticing a huge array of marketers ",
            ", the Super Bowl remains the most-viewed media event all year, drawing " +
            "in some 90 million ",
            "viewers and enticing a huge array of marketers to pony up the big bucks " +
            "for an ad",
            ", the price of which is running as high as $2.6 million for this year's " +
            "broadcast",
            "on CBS Corp.'s CBS network, up slightly from about a top price of about " +
            "$2.5 million last year.",
            "Comedian Carlos Mencia, of the Comedy Central show  gets ",
            "a big break with a spot set in a classroom. Lachky predicts that Mencia " +
            "will get an enormous boost Lachky predicts that Mencia will get an " +
            "enormous boost ",
            "following the appearance, which similarly did wonders for Cedric the " +
            "Entertainer.",
            "And what would Budweiser Super Bowl ads be without some animated " +
            "critters? This year, a ga",
            "ng of mischievous red crabs turn up on a beach to carry off a cooler " +
            "full of beers. As in past years, Bud is keeping many ",
        public DrawCanvasRx(int width, int height) {
            theSize.setSize(width, height);
        public Dimension getPreferredSize() {
            System.out.printf("theSize = [%d, %d]%n", theSize.width, theSize.height);
            return theSize;
        public void enlarge(int width, int height) {
            theSize.width  = width;
            theSize.height = height;
            // Mark this component as needing a new layout.
            invalidate();
        public void update(Graphics g) {
            paint(g);
        public void paint(Graphics g) {
            Rectangle r = getBounds();
            g.setColor(new Color(226,250,255));
            g.fillRect(0, 0, r.width, r.height);
            g.setColor(new Color(233,231,224));
            int line = 35;
            int line_1 = 39;
            for (int i = 0; i < contents.length; i++) {
                g.setColor(Color.BLACK);
                 g.drawString(contents, 5, line);
         g.setColor(new Color(233,231,224));
         g.drawLine(0, line_1, 605, line_1);
         line += 20;
         line_1 += 20;

  • How do I chance the place of JLabel and JButton in JPanel.

    I'm using DefaultLayout and I want to give the user the ability to change the place of JLabel and JButton. I managed the DnD part, but when "dropped" the control returns to it's original position.
    I tried using setX() and setY().

    You need to use a null Layout, also known as [url http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]Absolute Positioning

  • Color of JLabel and JButton text

    Hi,
    Could someone tell me how to set the color of JLabels and JButton text.
    Thanks

    for JButton text
    myButton.setForeground(Color.yellow);
    for JLabel
    myLabel.setForeground(Color.green);

  • Using clone() with JLabel and JButtons

    I need to find a way of making a duplicate copy of objects that extend JLabel and JButton. Do I need to implement the clone() methord manually, or is there a simpler way of doing this?

    Use a BorderLayout as the main layout. Add the two tables to the WEST and EAST.
    Create another panel using a different layout, maybe a vertical BoxLayout. Add the two buttons and then add this panel to the CENTER of the main panel.
    The secret is to nest different panels with different layout managers to achieve your desired layout.

  • Just updated to new iOS 6 on iPhone 3G. Get 'can't connect to iTunes' message. Tried the setting date and time trick but still no success. Any suggestions for 3G iPhone?

    Just updated to new iOS 6 on iPhone 3G. Get 'can't connect to iTunes' message. Tried the setting date and time trick but still no success. Any suggestions for 3G iPhone?

    also must mention i have never had trouble that i couldn't fix on itunes but all of this has started since i have been using icloud for basic backups hope this helps solve problem

  • HT1363 hi, my ipod classic is making funny clicking noises and is telling me to contact apple support, any help wo uhh ld be appreciated many thanks.            mark connolly

    Hi my ipod classic has started making funny clicking noises and is telling me to go to apple support, any help would be appreciated
    Many thanks
    Mark connolly

    The hard drive in it has failed and will need to be replaced.

  • Left- and right-justifying with dot leaders in JLabel and JButton

    Hi,
    I am developing checklists using JLabel and JButton components and want to finish up with the text in each component looking something like the following (each line is a separate button/label):
    ACTION No1............................RESPONSE No1
    ACTION No2............................RESPONSE No2
    ACTION No3............................RESPONSE No3
    The idea is to have the �Action� text left-justified and the �Response� text right-justified with dot-leaders as shown.
    Each text line will be put into its own fixed length label or button.
    I plan to construct a string from text blocks �ACTION No1� and �RESPONSE No1� and add the calculated, exact no of dots in between to fill the space.
    The text font can be fixed (e.g. Courier) or proportional (e.g. Arial).
    My question is how to calculate the number of dots to add to fill the space for different fonts and font sizes.
    I think that using FontMetrics could provide some help but am not sure how this would work.
    Can anyone help.
    Many tks
    John

    Hi,
    I've developed your suggested code further to enable selected JLabels to be toggled visible(true/false) by pressing a JButton.
    I'd like however that when a label is made invisible that the rest of the labels/buttons move up to fill the space left by the now invisible label and vice versa.
    How do I do this, can you enlighten me on a solution?
    Modified code included below. Not very elegant but serves to illustrate the point in question and only makes the label invisible.
    Many tks
    John
    package componentwierd;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ComponentWierd extends JFrame implements ComponentListener, ActionListener {
        boolean isVisible = true;
        JLabel label2 = new JLabel();
        public ComponentWierd() {
            getContentPane().setLayout( new GridLayout(0, 1) );
            // Using my original suggestion
            JLabel label = new JLabel();
            label.setLayout(new BorderLayout());
            label.add(createWierdComponent());
            getContentPane().add(label);
            JButton button = new JButton();
            button.setLayout(new BorderLayout());
            button.add(createWierdComponent());
            button.addActionListener(this);
            getContentPane().add(button);
            // Using Font Metrics
            // JLabel label2 = new JLabel("Label2 West...Label2 East");
            label2.setText("Label2 West...Label2 East");
            label2.addComponentListener( this );
            getContentPane().add(label2);
            JButton button2 = new JButton("Button2 West...Button2 East");
            System.out.println(button2.getIconTextGap());
            button2.addComponentListener( this );
            button2.setVisible(true);
            getContentPane().add(button2);
        public void actionPerformed(ActionEvent e) {
            if (isVisible == true) {
                isVisible = false;
                label2.setVisible(false);
            } else if (isVisible == false) {
                isVisible = true;
                label2.setVisible(true);
        private JComponent createWierdComponent() {
            JPanel panel = new JPanel(new BorderLayout());
            panel.setOpaque( false );
            panel.add(new JLabel("Label WEST"), BorderLayout.WEST);
            panel.add(new JLabel("..............................................."));
            panel.add(new JLabel("Label EAST"), BorderLayout.EAST);
            return panel;
        public void componentResized(ComponentEvent e) {
            if (e.getComponent() instanceof JLabel) {
                JLabel component = (JLabel)e.getComponent();
                String text = component.getText();
                String fitText = fitText(component, text);
                component.setText( fitText );
            if (e.getComponent() instanceof JButton) {
                JButton component = (JButton)e.getComponent();
                String text = component.getText();
                String fitText = fitText(component, text);
                component.setText( fitText );
        private String fitText(JComponent component, String text) {
            // Calculate the total width for painting the text
            // (Not sure why I need the -8)
            Insets insets = component.getInsets();
            int availableWidth = getWidth() - insets.left - insets.right - 8;
            // Calculate the minimum width our text will take
            String start = text.substring(0, text.indexOf("."));
            String middle = "...";
            String end = text.substring(text.lastIndexOf(".") + 1);
            FontMetrics fm = getFontMetrics( component.getFont() );
            int startWidth = fm.stringWidth( start );
            int middleWidth = fm.stringWidth( middle );
            int endWidth = fm.stringWidth( end );
            int minimumWidth = startWidth + middleWidth + endWidth;
            // Add dots to fill out the extra space
            StringBuffer buffer = new StringBuffer(start);
            buffer.append(middle);
            if (minimumWidth < availableWidth) {
                String dot = ".";
                int dotWidth = fm.stringWidth( dot );
                int dots = (availableWidth - minimumWidth) / dotWidth;
                for (int i = 0; i < dots; i++) {
                    buffer.append( dot );
            buffer.append(end);
            String result = buffer.toString();
            return result;
        public void componentHidden(ComponentEvent e) {}
        public void componentMoved(ComponentEvent e) {}
        public void componentShown(ComponentEvent e) {}
        public static void main(String[] args) {
            ComponentWierd frame = new ComponentWierd();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.setSize(200, 200);
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • I was surfing the web and got tricked into downloading MacProtector.  It says my system is infected!!  Of course they want almost $80 to register the copy that is on my laptop.  Is this a good product??  Should I get something else, like Norton antivirus?

    I was surfing the web and got tricked into downloading MacProtector.  It says my system is infected!  Of course they want almost $80 to register the program so I can then use it to clean up my machine.  Is this a good program??  Should I get something like Norton antivirus instead??

    Yes, turning off Javascript works, but turning it on and off is a pain if one has to make a trip to the preferences.
    Why many recommend the NoScript Add-on as one can drag a "allow" button to Firefox's toolbar and turn on scripts on a site per site, case per case basis.
    NoScript also protects against other web nasties, like Clear click jacking and zillions of other web based trickery.
    http://noscript.net/changelog
    Apple Support Forums works fine without Javascript running, I do it all the time, it also supports HTTPS encrpytion too.
    It might be that I'm not seeing a lot with Javascript and other things turned off, but the post box functions etc. work just fine.
    Maybe Apple is heading towards no scripts running on all their products?
    First Flash gets the axe, then Java is coming next and perhaps finally Javascript? hmmmm?
    Smart move possibly.
    Nope it's the same with it on or off.

  • Transparent taskbar and other funny behaviour

    Since I made a fresh install of SL my taskbar has been acting all funny. Sometimes my logged in user name is only "half" displayed. That is the name is cut right in the middle. These last days my taskbar takes forever to load upon boot and when it does it is transparent.
    Any cache files or something I can delete?
    Regards

    I have a similar issue - using the included Vista Business-version that came with my T61.
    Sometimes, it seems that the welcome/login-window is showing before the finger-print reader is ready to accept the finger, and hence logging in. Sometimes it doesn't work at all, and I have to log in by typing my password.
    This is not consistent either - sometimes it just works right off, sometimes I have to try 4-5-6 times, and sometimes it just plainly refuses to accept the scan (and not as in it's not recognizing it - just doesn't do anything when scanning).
    So, you're not alone
    IT-technician, running my own company in Bergen, Norway
    Thinkpad T61, 8895CTO C2D 2Ghz/4GB/120GB SSD/1400x1050

  • Tomcat and Mozilla funny behaviour

    Hi,
    I have a funny situation going on involving tomcat, mozilla, and internet explorer.
    I am using tomcat 3.3 to serve my pages.
    When viewed through Internet Explorer, everything is fine, and the pages format quite nicely.
    When I view the same pages through Mozilla, it doesn't seem to find the linked stylesheets, and doesn't attempt any formatting at all?!?!
    When I view the same pages through apache, both IE and Mozilla format correctly.
    So, any ideas why Mozilla wouldn't like Tomcat?

    I hate these kind of issues. It happened to me when changing .css contents and then trying to refresh. Mostly due to the unability to refresh contents on pages redirecting to other pages... no time to press the refresh button.
    I know it's a bad solution, but might be a good test and will finally discard a caching issue:
    Copy res.css to rescopy.css and change the link for that page in question.
    I hope it helps!

Maybe you are looking for