JButton base problem

Hi All,
I have a primitive /as I known/ problem with the JButton.
I create one, and set the text with this 'Show'. I set the font /eg. Arial/ and it's size to 9.
If I set the required size of the button the text is not shown. /shown only .../
When show the text correctly the width of button is very large for me.
How can I make a button which hase a same width such as the text in it.?
thx.

Once you've set the font and text for a button, you can find out its preferred size using getPreferredSize.
Typically buttons will add on padding between the text and the border. This is known as the "margin" and can be changed using setMargin.
You can set the margin for all buttons using UIManager's Button.margin property.
Hope this helps.

Similar Messages

  • Quesion on fragile base problem

    Hi,
    I like to know how JAVA addesses the fragile base problem. I understand fragile base problem occurs when you want to add a new feature to a base programs, it requires the modification of all the children class to also inherit the new feature. This takes a lot of effort and it's error prone. I kind of know that polymorphism concept is the feature Java added to address the problem but I don't have a solid picture of how it handles the problem. Can anyone provide some info on this. Thanks.

    Sorry, I probably did not mean adding new features. I
    think what I am trying to say is supposedly we change
    a method in the parent class to return a String,
    previously a Integer. If we don't retrofit the
    children class, it will cause the program to fail
    compiling. If the program uses deep inheritance, just
    one single change might require a lot of work to
    retrofit. So, how would a developer design the
    application to avoid this problem? Unless you are overriding or extending the method this isn't the case. Really it's not so much a parent - child problem as it is a general application problem. Everywhere you are calling this method will no longer compile.
    One solution that always works is to make the change and let the compiler tell you what other code needs to be fixed. Java doesn't have any answers for this problem though some IDEs do as the previous poster mentioned.
    The best way to avoid something like this is to have a good design. I can't think of any good examples of when this could happen. Usually deeply inherited classes should be almost completely stable. If not, maybe that method should't be part of the base class at all. Changing a method to return a String instead of an Integer is a huge change. Really you are talking about changing its purpose. Maybe if you gave a better example I could understand a little better.

  • JButton.setBackground() Problem

    Hi All,
    When i apply the setBackground() Method to a JButton to set its Background, i face i Problem :
    Under Mac Os : The JButton DOSE NOT change its color,
    when i take my code to my other computer under Windows : OK, the JButton change...
    i am wondering ....
    1) Why under my Mac OS i face this problem...
    2) and Why i get two different results from a same code ??? Java is not Portable?? and independant of the OS?? or it is the swing that makes the problem???
    My code is so simple :
    MyJButton.setBackground(new Color(255,100,100));
    Thanks to any help...

    ellias2007 wrote:
    Sorry because it is the first time for me in this forum....
    thanks for any help...
    Sorry againMost of us don't like disjointed discussions or repeating effort for a problem that has already been solved elsewhere. Thanks for your reply. A link to one discussion: [http://www.java-forums.org/awt-swing/25986-jbutton-setbackground-problem.html]
    If you have cross-posts elsewhere, please post links in all of them to each other or to one central location.

  • JButton imageIcon problem

    hello ,
    i am facing a problem in changing the imageicon of jbutton in my application.
    i want to change imageicon for few seconds and than again change it to original imageicon....
    is it possible?????????????i have tried but after initializing button with one imageicon we are not able to change that icon again..
    so what should i do...it is compulsory to change take two image for button.....
    please help

    Set up a Timer. You use the setIcon(...) method to change the icon. Then you start a Timer to fire in a few seconds and use the setIcon(...) method to change the image back to its original value.

  • JButton dispatchEvent problem

    Hi,
    I've got JButtons in a JTable which means I have to capture the mouse events and forward them to the button.
    I do this with a mouse listener on the table, and the lines:
    buttonEvent = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button);
    button.dispatchEvent(buttonEvent);
    System.out.println(buttonEvent);
    table.repaint();where 'e' is the original mouse event. This produces, for example:
    java.awt.event.MouseEvent[MOUSE_CLICKED,(145,167),button=1,modifiers=Button1,clickCount=1]
    on
    javax.swing.JButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5 <snip> text=Delete,defaultCapable=true]but yet nothing happens to the button. Is this a coordinate problem, or am I missing something else, as I don't really know what I'm doing?
    Cheers,
    Rob

    MOUSE_CLICKED,(145,167),Well I'm guessing that you can't just convert the table coordinates and use them as the button coordinates because the button isn't that big.
    An alternative approach might be to use the doClick() method of the button.
    In case that doesn't work, here's something I've been playing with that may help:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableButton3 extends JFrame
         public TableButton3()
              String[] columnNames = {"Date", "String", "Integer", "Decimal", ""};
              Object[][] data =
                   {new Date(), "A", new Integer(1), new Double(5.1), "Delete1"},
                   {new Date(), "B", new Integer(2), new Double(6.2), "Delete2"},
                   {new Date(), "C", new Integer(3), new Double(7.3), "Delete3"},
                   {new Date(), "D", new Integer(4), new Double(8.4), "Delete4"}
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              //  Create button column
              ButtonColumn buttonColumn = new ButtonColumn(table, 4);
         public static void main(String[] args)
              TableButton3 frame = new TableButton3();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
         class ButtonColumn extends AbstractCellEditor
              implements TableCellRenderer, TableCellEditor, ActionListener
              JTable table;
              JButton renderButton;
              JButton editButton;
              String text;
              public ButtonColumn(JTable table, int column)
                   super();
                   this.table = table;
                   renderButton = new JButton();
                   editButton = new JButton();
                   editButton.setFocusPainted( false );
                   editButton.addActionListener( this );
                   TableColumnModel columnModel = table.getColumnModel();
                   columnModel.getColumn(column).setCellRenderer( this );
                   columnModel.getColumn(column).setCellEditor( this );
              public Component getTableCellRendererComponent(
                   JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                   if (hasFocus)
                        renderButton.setForeground(table.getForeground());
                         renderButton.setBackground(Color.WHITE);
                   else if (isSelected)
                        renderButton.setForeground(table.getSelectionForeground());
                         renderButton.setBackground(table.getSelectionBackground());
                   else
                        renderButton.setForeground(table.getForeground());
                        renderButton.setBackground(UIManager.getColor("Button.background"));
                   renderButton.setText( (value == null) ? "" : value.toString() );
                   return renderButton;
              public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   text = (value == null) ? "" : value.toString();
                   editButton.setText( text );
                   return editButton;
              public Object getCellEditorValue()
                   return text;
              public void actionPerformed(ActionEvent e)
                   fireEditingStopped();
                   System.out.println( "Action: " + e.getActionCommand() );
    }

  • Family Base Problem

    Hi!  I'm very new to Verizon and just installed Family Base on my daughter's phone.  Problem is, it won't unlock.  I logged on here and the app on my phone, and it's saying the phone is unlocked.  I can assure you it is not.  Currently as I'm typing, I'm on hold with tech.  Hoping to get an answer.  Has anyone else had this trouble?

        Mandiski78, sorry to hear about the trouble you've had with family base. Were you able to get that fixed? What are you trying to unlock? What model phone does she have? We're happy to help.
    BrianP_VZW
    Follow Us on Twitter @VZWSupport

  • JButton display problem

    I would have thought the following would bring up two identical MainWindows, but in fact the buttons in the second one look slightly different.
    public class Main {
         public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                     setUpApp();
         private static void setUpApp() {
              MainWindow mainWindow = new MainWindow();
              MainWindow mainWindow2 = new MainWindow();
    }This is what the two windows look like after display: (How do URLs work?)
    I'm not really sure what code to paste other than this because I would think the code is identical for both.

    Slow day, and I actually created an SSCCE:
    import javax.swing.*;
    import java.awt.*;
    public class MainWindow {
       private JFrame topLevelContainer;
       public MainWindow() {
          topLevelContainer = new JFrame();
          topLevelContainer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          topLevelContainer.setPreferredSize(new Dimension(400, 400));
          Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
          topLevelContainer.setTitle("ChatApp");
          topLevelContainer.setVisible(true);
          JPanel contentPane = new JPanel(new BorderLayout(2, 2));
          contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
          contentPane.setBackground(Color.BLUE);
          topLevelContainer.setContentPane(contentPane);
          JPanel sendingTo = new JPanel();
          sendingTo.setOpaque(false);
          sendingTo.setBorder(BorderFactory.createTitledBorder("Sending To"));
          contentPane.add(sendingTo, BorderLayout.PAGE_START);
          JPanel messageLog = new JPanel();
          messageLog.setOpaque(false);
          messageLog.setBorder(BorderFactory.createTitledBorder("Message Log"));
          contentPane.add(messageLog, BorderLayout.CENTER);
          JPanel sendPanel = new JPanel(new BorderLayout(2, 0));
          sendPanel.setBackground(Color.BLUE);
          JTextArea sendMessageArea = new JTextArea("Send Message Area", 5, 30);
          sendMessageArea.setOpaque(false);
          sendPanel.add(sendMessageArea, BorderLayout.CENTER);
          JButton _sendMessage = new JButton("Send Message");
          sendPanel.add(_sendMessage, BorderLayout.LINE_END);
          contentPane.add(sendPanel, BorderLayout.PAGE_END);
          try {
             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
          } catch (ClassNotFoundException e) {
             e.printStackTrace();
          } catch (InstantiationException e) {
             e.printStackTrace();
          } catch (IllegalAccessException e) {
             e.printStackTrace();
          } catch (UnsupportedLookAndFeelException e) {
             e.printStackTrace();
          topLevelContainer.pack();
       private static void createAndShowUI() {
          new MainWindow();
          new MainWindow();
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
    }And in it, I notice that you're setting your GUI visible before adding components and your setting the look and feel after you've created and added components, and this seems a bit backwards. The look and feel issue is what is causing the problem that you are noticing.

  • JButton Adding Problem

    Hi everyone,
    First, like to say I appreciate all your help. I have come here for help before and I always get my questions answered. Thanks.
    Here is my problem:
    I've created a JPanel and added this panel to a JFrame. The JPanel has a MouseListener and a MouseMotionListener. I am tryin to add JButtons to the JPanel at positions passed from the MouseMotionListener, but everytime I attempt this, the JButton pops to the top left corner of the screen. I don't know if I should use a layout manager on the JPanel and if I do, I don't know which one to use. I've tried using the SpringLayout, but was unsuccessful at deploying it.
    Appreciate any help.
    Thanks again.

    Null layout is not recommended, see my earlier post. Here is a simple SpringLayout that does the same thing.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestSpring extends JFrame
         Container cp;
         int mpx, mpy;
         int MINX= 80;
         int MINY=20;
         JLabel txt = new JLabel("use mouse to position buttons, drag to set size");
         SpringLayout slay = new SpringLayout();
         MouseInputAdapter mia = new MouseInputAdapter()
              public void mousePressed(MouseEvent evt){mousePress(evt);}
              public void mouseReleased(MouseEvent evt){mouseRelease(evt);}
         TestSpring()
              super("TestSpring");
              cp = getContentPane();
              addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent evt){System.exit(0);}});
              cp.addMouseListener(mia);
              cp.setLayout(slay);
              cp.add(txt);
              setBounds(0,0,700,400);
         void mousePress(MouseEvent evt)
              mpx = evt.getX();
              mpy = evt.getY();
         void mouseRelease(MouseEvent evt)
              int x,y,dx,dy;
              x = evt.getX();
              y=evt.getY();
              dx = x-mpx;
              dy = y-mpy;
              if(dx < 0){dx = -dx; mpx = x;}
              if(dy < 0){dy = -dy; mpy = y;}
              JButton jb = new JButton(mpx+","+mpy);
              cp.add(jb);
              setCPosition(jb,mpx,mpy);
              if(dx < MINX)dx = MINX;
              if(dy < MINY)dy = MINY;
              setCSize(jb, dx, dy);
              cp.validate();
         void setCPosition(Component c, int x, int y)
              slay.getConstraints(c).setX(Spring.constant(x));
              slay.getConstraints(c).setY(Spring.constant(y));
         void setCSize(Component c, int w, int h)
              slay.getConstraints(c).setWidth(Spring.constant(w));
              slay.getConstraints(c).setHeight(Spring.constant(h));
         // the main startup function
         public static void main(String[] args)
              new TestSpring().show();
    }

  • JButton clicked problem?

    I have a Jbutton and on button clicked, action is performed.
    Now if mouse is just clicked but moved only one pixel(means focus is still on the button) , action will not occur. It works only if the button is clicked and mouse does not move at all. I want action if the button is clicked and does not leave the button forground area until it is released.
    thnx

    Sounds like there is a problem in your code. Only can make wild guesses based on the lack of info. (If you post code, please spare us the pain of looking at all of it, just create a simple example).

  • Withholding tax calculation with formula base problem

    Dear all,
    I maintained some formula depend on client requirement. for example:
    up to 200,000.00  no withholding tax                                                     
    2 lax to500,000.00  <1.00 %> tax                                                   
    5 lax to 1,500,000.00 <2.50%> tax 1.00 % Reduce on 500,000.00 base amount                    
    15 lax to 2,500,000.00 < 3.50 % > tax 2.50 % Reduce on 1,500,000.00 base amount                         
    25 lax to 3,000,000.00 < 4.00 % > tax 3.50 % Reduce on 2,500,000.00 base amount                         
    30 lax to 99,999,999,999.00     <5.00 %> tax 4.00 % Reduce on 3,000,000.00 base amount          
    Like this i maintained slabs in formulas for calculating withholding tax. depend on this formula up to 2 lax their is no tax. after crossing 2 lax up to 5 lax 1% tax
    in this case tax will calculate based on total vendor invoices. But hear it is calculated on present invoice based only. for example i posted 2 invoices with amount 2 lax. it means i reached 1st slab up to 2 lax no Tax. system also calculated like that only. but when i try to post another invoice with amount 3 lax system is calculated 1% tax on 3 lax amount only. but already i posted 2 lax invoice in vendor account. system not considered this amount.
    *but actually in this case i want to calculate 3+2= 5 lax * 1% tax . but hear my system is not consider previous invoices .*
    Please do need full help.....
    Regards,
    Krishna Valeti
    Edited by: chaituvaleti on Sep 9, 2011 8:51 AM
    Edited by: chaituvaleti on Sep 9, 2011 8:54 AM
    Edited by: chaituvaleti on Sep 9, 2011 9:02 AM

    Can you please share the information to us,  it will be a great information to us , thanks in advance.........

  • JButton NullPointerException problem

    Hi
    I was wondering if you guys can help me out on this one. I'm been prompted with a NullPointerException whenever I click on either of the 2 buttons.
    Thanks guys
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Alarm extends JPanel implements ActionListener{
        private JTextArea messageField;
        private JButton alarmOn, alarmOff;
        private JLabel alarmLED;
        public Alarm(){
            super.setPreferredSize(new Dimension(200,300));
            //configuring components;
            JButton alarmOn = new JButton("On");
            alarmOn.addActionListener(this);
            JButton alarmOff = new JButton("OFF");
            alarmOff.addActionListener(this);
            JLabel alarmLED = new JLabel("Alarm OFF");
            alarmLED.setOpaque(true);
            alarmLED.setBackground(Color.GREEN);
            messageField = new JTextArea(2,20);
            messageField.setEditable(false);
            messageField.setPreferredSize(new Dimension(200, 200));
            this.add(messageField, BorderLayout.PAGE_START);
            alarmOn.setPreferredSize(new Dimension(80, 20));
            this.add(alarmOn, BorderLayout.LINE_START);
            alarmOff.setPreferredSize(new Dimension(80, 20));
            this.add(alarmOff, BorderLayout.CENTER);
            alarmLED.setPreferredSize(new Dimension(65, 30));
            this.add(alarmLED, BorderLayout.LINE_END);
         public void actionPerformed(ActionEvent event){
            if(event.getSource()==this.alarmOn){
                this.alarmLED.setBackground(Color.RED);
                this.alarmLED.setText("Alarm ON");
            }else{
                this.alarmLED.setBackground(Color.GREEN);
                this.alarmLED.setText("Alarm OFF");
    }//end of class;

    I figured it out...I think i declared the button twice.
    Funny...it seems easier to spot it in this forums comparing it on BlueJ
    Will someone recommend me a better java client then BLueJ?
    Preferably user friendly kinds
    Thanks

  • Data base problem-new user need help

    im new user and trying to insert data base to my page using
    "asp.net c",i get connetction to my data base but when i try to
    build a form ,and then preview him i get ,the following message
    Server Error in '/' Application.
    Parser Error
    Description: An error occurred during the parsing of a
    resource required to service this request. Please review the
    following specific parse error details and modify your source file
    appropriately.
    Parser Error Message: File or assembly name DreamweaverCtrls,
    or one of its dependencies, was not found.
    Source Error:
    Line 1: <%@ Page Language="C#" ContentType="text/html"
    ResponseEncoding="iso-8859-1" %>
    Line 2: <%@ Register TagPrefix="MM"
    Namespace="DreamweaverCtrls"
    Assembly="DreamweaverCtrls,version=1.0.0.0,publicKeyToken=836f606ede05d46a,culture=neutra l"
    %>
    Line 3: <MM
    ataSet
    Line 4: id="DataSet1"
    Source File: e:\inetpub\wwwroot\Untitled-1.aspx Line: 2
    Assembly Load Trace: The following information can be helpful
    to determine why the assembly 'DreamweaverCtrls' could not be
    loaded.
    === Pre-bind state information ===
    LOG: DisplayName = DreamweaverCtrls, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=836f606ede05d46a
    (Fully-specified)
    LOG: Appbase = file:///e:/inetpub/wwwroot
    LOG: Initial PrivatePath = bin
    Calling assembly : (Unknown).
    ===
    LOG: Publisher policy file is not found.
    LOG: No redirect found in host configuration file
    (E:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet.config).
    LOG: Using machine configuration file from
    E:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\config\machine.config.
    LOG: Post-policy reference: DreamweaverCtrls,
    Version=1.0.0.0, Culture=neutral, PublicKeyToken=836f606ede05d46a
    LOG: Attempting download of new URL
    file:///E:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/Temporary
    ASP.NET Files/root/804ee9b4/26f0df32/DreamweaverCtrls.DLL.
    LOG: Attempting download of new URL
    file:///E:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/Temporary
    ASP.NET
    Files/root/804ee9b4/26f0df32/DreamweaverCtrls/DreamweaverCtrls.DLL.
    LOG: Attempting download of new URL
    file:///e:/inetpub/wwwroot/bin/DreamweaverCtrls.DLL.
    LOG: Attempting download of new URL
    file:///e:/inetpub/wwwroot/bin/DreamweaverCtrls/DreamweaverCtrls.DLL.
    LOG: Attempting download of new URL
    file:///E:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/Temporary
    ASP.NET Files/root/804ee9b4/26f0df32/DreamweaverCtrls.EXE.
    LOG: Attempting download of new URL
    file:///E:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/Temporary
    ASP.NET
    Files/root/804ee9b4/26f0df32/DreamweaverCtrls/DreamweaverCtrls.EXE.
    LOG: Attempting download of new URL
    file:///e:/inetpub/wwwroot/bin/DreamweaverCtrls.EXE.
    LOG: Attempting download of new URL
    file:///e:/inetpub/wwwroot/bin/DreamweaverCtrls/DreamweaverCtrls.EXE.
    Version Information: Microsoft .NET Framework
    Version:1.1.4322.573; ASP.NET Version:1.1.4322.573
    I know its probably something stupid ,so u can lauph,but i
    realy cant fix it.
    need help
    tnx for advance

    anyone? please help

  • BW BASIS Problem

    Hi Guys
    THis is more of a basis question.
    I have BI7 ides installed on my machine.
    I start up the BW instance in the console. There is 2 servers listed and the database.
    One server turns red because one the services isnt working.
    service name 'JMX Adaptor'
    description '501>500 last reported value above threshold'
    Any ideas
    Regards
    Abu Sarah

    Hello
    Please familiarise yourself with the forum Rules of Engagement - https://wiki.sdn.sap.com/wiki/display/HOME/RulesofEngagement
    Please do not cross post. This thread will be locked.
    Regards
    XI/PI Moderator

  • [bc4j] Urgent jbutton binding problem

    Hi,
    I have a working application with a few panels, and a few viewobjects, viewlinks, etc. I can use the navigator to navigate through the records, etc, everything works fine.
    But when I add a jbutton to the panel, with an action binding for the view object ('insert new record' or 'next'), then when starting up the application, the view object begins to spill, all records seem to be loaded and spilled to the spill-table.
    If I remove the model form the jbutton and re-run, everything works fine again. What could cause this? All other binded controls (navigationbar, several jtextfields, and even a jtree) work fine, but the jbutton causes spills.
    And not even when I click it, but during startup of the app!
    Any idea?
    Greetings,
    Ivo

    Bug#2772798 filed after reproducing using your testcase. Thanks.
    Shailesh got back to me with this analysis:
    No bindings should force a range size of -1 by default except for Lov Bindings on Combo and List Boxes where all the data is needed on the client side control.
    ButtonlActionBinding's create method is setting the rangesize of the iterator to -1 leading to all rows being fetched. The workaround is to set the range size on the iterator in setPanelBinding() method after jbInit() to a desired size.
    Here's a line I added to Ivo's setPanelBinding() method of his PanelFootballView1.java class...
    jbInit();
    panelBinding.findIterBinding("FootballViewIter1").getRowSetIterator().setRangeSize(1);

  • XI and BASIS problem

    Hi all,
    Yesterday, I encountered a SYSFAIL in smq2 (queues). The error was 'SQL error in the database when accessing a table'. I contacted our basis guy and he increase the table space. After that, the queues were running again. But we asked ourselves, why did this happen? Will this error occur again after a few weeks? How come XI is taking up a lot of space since its only job is to act as a gateway. Why is it storing data? How can we prevent this kind of SYSFAIL from happening again?
    Thanks.
    Regards,
    IX

    the data i guess is usually stores the information reg the message. So if you need to track back and and view the log or status of a old message these tables come to be of help.
    I guess you can have the table contents cleared or archive XI messages on a time basis perhaps to ensure the issue doesnt come up again
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/402fae48-0601-0010-3088-85c46a236f50

Maybe you are looking for