Vertical JButton

Hi!
I'm new here and I have a problem with creating vertical button with vertical text. Basically what I want to do is to rotate JButton (including text and icon) by 90 degrees. |'ve already found some solutions on this and other forums over the Internet but none of them satisfy my needs. Some of the implementations don't support differrent UI themes. I already tried overriding paintComponent from JButton and I tried to rotate it, but it only works if width and height is the same (because of the paint region). I also tried to code my custom ButtonUI, but I can't paint background gradient for Metal L&F. Can anyone post a good solution? What I would like to achieve is the same look of vertical buttons as those from NetBeans pannels (gui editor doesn't support drawing such buttons). Thanks in advance.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
* @author Michal
public class VerticalButton extends JButton implements Cloneable {
    //<editor-fold defaultstate="collapsed" desc="Clockwise">
    private boolean clockwise = false;
    /** Po směru hodinových ručiček? */
    public void setClockwise(boolean clockwise) {
        this.clockwise = clockwise;
    /** Po směru hodinových ručiček? */
    public boolean getClockwise() {
        return clockwise;
    /** Po směru hodinových ručiček? */
    public boolean isClockwise() {
        return clockwise;
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="Constructors">
    public VerticalButton() {
    public VerticalButton(Action a) {
        super(a);
    public VerticalButton(Icon icon) {
        super(icon);
    public VerticalButton(String text) {
        super(text);
    public VerticalButton(String text, Icon icon) {
        super(text, icon);
    public VerticalButton(String text, boolean clockwise) {
        this(text);
        this.clockwise = clockwise;
    //</editor-fold>
    @Override
    public Dimension getPreferredSize() {
        return rotate(super.getPreferredSize());
    private Dimension rotate(Dimension d) {
        return new Dimension(d.height, d.width);
    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g.create();
        VerticalButton clone = clone();
        clone.setSize(rotate(this.getSize()));
        if (clockwise) {
            g2.rotate(Math.PI / 2.0);
            g2.translate(0, -getSize().width);
        } else {
            g2.translate(0, getSize().height);
            g2.rotate(-Math.PI / 2.0);
        clone.paintSuperComponent(g2);
        g2.dispose();
    public void paintSuperComponent(Graphics g) {
        super.paintComponent(g);
    @Override
    protected VerticalButton clone() {
        try {
            return (VerticalButton) super.clone();
        } catch (CloneNotSupportedException cloneNotSupportedException) {
            return null;

Similar Messages

  • Update vertices of a model during runtime

    Hello,
    I’m writing a program using Java3D in which I read a model (composed of one 3d surface) from an obj file, I display the model correctly. Then I would like to modify the position of the vertices “live” of this model. This operation can be done many times. I did several attempts based on some examples, but it still doesn’t work. The first errors where related to the capabilities (I guess I fixed that) and then, I don’t have errors, but nothing happens on the screen (the model is still the same). I’m suspecting that there is no link between the geometry (vertices) and the scene, but I don’t know how to connect them.
    Do you know why it doesn’t work in the solution that I tried? Does anyone know how to do this in a better way? I’m a beginner with java3d, am I missing something?
    Thank you for your help in advance.
    Slim.
    //  Loading the model correctly
        // using ncsa Portfolio loader packages
         Scene s = null;
           ModelLoader modelLoader = new ModelLoader();
         try {
           s = modelLoader.load(fnm);   // handles many types of file
         catch (Exception e) {
           System.err.println(e);
           System.exit(1);
        sceneGroup = s.getSceneGroup();
        // I added the attribute (Shape3D shape) to have a reference on the model.
        shape = (Shape3D) sceneGroup.getChild(0);
    // I added all the capabilities (may be some are unneeded but, to avoid any error related to this)
        shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ);
        shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE);
        shape.setCapability(Shape3D.ALLOW_GEOMETRY_READ);
        shape.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE);
        shape.setCapability(GeometryArray.ALLOW_COLOR_READ);
        shape.setCapability(GeometryArray.ALLOW_FORMAT_READ);
        shape.setCapability(GeometryArray.ALLOW_COUNT_READ);
        shape.setCapability(GeometryArray.ALLOW_COORDINATE_READ);
        shape.setCapability(IndexedGeometryArray.ALLOW_COORDINATE_INDEX_READ);
    // this part of code is to get the geometry
    // vertices is an attribute (array of Point3f)
    // ga is an attribute (GeometryArray)
         ga = (GeometryArray)shape.getGeometry();
         verticesNum = ga.getVertexCount();
         GeometryInfo gi = new GeometryInfo(ga);
         vertices = gi.getCoordinates();
      // create a transform group for the object's bounding sphere
        TransformGroup objBoundsTG = new TransformGroup();
        sceneGroup.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
        sceneGroup.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
        sceneGroup.setCapability(GeometryArray.ALLOW_COUNT_READ);
        objBoundsTG.addChild( sceneGroup );
    // Other code regarding the Transformation ..
    // At this level I have some data in the array vertices.And this the code I use to update the vertices of the model:
    public void updateGeometry(){
    ga.updateData(new GeometryUpdater(){
            public void updateData(Geometry geometry){
              updateVertices();
    shape.setGeometry(ga);
      private void updateVertices() {
    // Modify the values of the vertices ..
            vertices[i ].x += XX ;
            vertices[i ].y += YY;
            vertices[i ].z += ZZ;
    }

    I'm putting a complete (and simplified though) runnable code, that might help to understand the problem. It is composed of 3 files.
    It needs an object file name to be modified in the main().
    Slim.
    File: VisObj.java
    // File: VisObj.java
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import com.sun.j3d.loaders.*;
    import com.sun.j3d.utils.geometry.*;
    import com.sun.j3d.loaders.objectfile.ObjectFile;
    public class VisObj
      private TransformGroup moveTG, rotTG, scaleTG;
      public Shape3D shape;
      private int verticesNum = 4000;
      private Point3f [] vertices = new Point3f[verticesNum];
      private GeometryArray ga;
      private BranchGroup sceneGroup;
      public VisObj(String fileName)
         Scene s = null;
         try {
                ObjectFile loader = new ObjectFile ();
           s = loader.load(fileName);
         catch (Exception e) {
           System.err.println(e);
           System.exit(1);
        sceneGroup = s.getSceneGroup();
        shape = (Shape3D) sceneGroup.getChild(0);
        shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ);
        shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE);
        shape.setCapability(Shape3D.ALLOW_GEOMETRY_READ);
        shape.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE);
        shape.setCapability(GeometryArray.ALLOW_COLOR_READ);
        shape.setCapability(GeometryArray.ALLOW_FORMAT_READ);
        shape.setCapability(GeometryArray.ALLOW_COUNT_READ);
        shape.setCapability(GeometryArray.ALLOW_COORDINATE_READ);
        shape.setCapability(IndexedGeometryArray.ALLOW_COORDINATE_INDEX_READ);
         ga = (GeometryArray)shape.getGeometry();
                    verticesNum = ga.getVertexCount();
                    System.out.println("Number of verts is " + verticesNum);
                    GeometryInfo gi = new GeometryInfo(ga);
                    vertices = gi.getCoordinates();
                    ga.setCapability(GeometryArray.ALLOW_REF_DATA_WRITE);
                    ga.setCapability(GeometryArray.ALLOW_REF_DATA_READ);
        // create a transform group for the object's bounding sphere
        TransformGroup objBoundsTG = new TransformGroup();
        sceneGroup.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
        sceneGroup.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
        sceneGroup.setCapability(GeometryArray.ALLOW_COUNT_READ);
        objBoundsTG.addChild( sceneGroup );
        BoundingSphere objBounds = (BoundingSphere) sceneGroup.getBounds();
        double radius = objBounds.getRadius();
        Transform3D objectTrans = new Transform3D();
        objBoundsTG.getTransform( objectTrans );
        Transform3D scaleTrans = new Transform3D();
        double scaleFactor = 1.0/radius;
        scaleTrans.setScale( scaleFactor );
        objectTrans.mul(scaleTrans);
        objBoundsTG.setTransform(objectTrans);
        // create a transform group for scaling the object
        scaleTG = new TransformGroup();
        scaleTG.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
        scaleTG.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        scaleTG.addChild( objBoundsTG );
        // create a transform group for rotating the object
        rotTG = new TransformGroup();
        rotTG.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
        rotTG.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        rotTG.addChild( scaleTG );
        // create a transform group for moving the object
        moveTG = new TransformGroup();
        moveTG.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
        moveTG.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        moveTG.addChild( rotTG );
    public void updateGeometry(){
          ga.updateData(new GeometryUpdater(){
            public void updateData(Geometry geometry){
              updateVertices();
          shape.setGeometry(ga);
      private void updateVertices() {
          for (int i = 0; i < verticesNum; i ++) {
            vertices[i ].x +=5 ;
            vertices[i ].y +=10;
            vertices[i ].z = 10;
      public TransformGroup getTG()  {  return moveTG; }
    }  File: VisPanel.java
    // File VisPanel.java
    import javax.swing.*;
    import java.awt.*;
    import com.sun.j3d.utils.universe.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    public class VisPanel extends JPanel
      private SimpleUniverse su;
      private BranchGroup sceneBG;
      private BoundingSphere bounds;
      private VisObj visobj;
      public VisPanel(String fileName)
        setLayout( new BorderLayout() );
        setOpaque( false );
        setPreferredSize( new Dimension(512, 512));
        visobj = new VisObj(fileName);
        GraphicsConfiguration config =
              SimpleUniverse.getPreferredConfiguration();
        Canvas3D canvas3D = new Canvas3D(config);
        add("Center", canvas3D);
        su = new SimpleUniverse(canvas3D);
        createSceneGraph();
        su.addBranchGraph( sceneBG );
      private void createSceneGraph()
        sceneBG = new BranchGroup();
        bounds = new BoundingSphere(new Point3d(0,0,0), 100);
        lightScene();     
        sceneBG.addChild( visobj.getTG() );
        sceneBG.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
        sceneBG.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
        sceneBG.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
        sceneBG.setCapability(BranchGroup.ALLOW_DETACH);
        sceneBG.compile();
      private void lightScene()
        Color3f white = new Color3f(1.0f, 1.0f, 1.0f);
        AmbientLight ambientLightNode = new AmbientLight(white);
        ambientLightNode.setInfluencingBounds(bounds);
        sceneBG.addChild(ambientLightNode);
        Vector3f light1Direction  = new Vector3f(-1.0f, -1.0f, -1.0f);
        DirectionalLight light =  new DirectionalLight(white, light1Direction);
        light.setInfluencingBounds(bounds);
        sceneBG.addChild(light);
      public void modifyObject()
      {    visobj.updateGeometry();   }
    } File: VisPlayer.java
    // File: VisPlayer.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class VisPlayer extends JFrame
      private VisPanel vp;   
      private JButton modifyobj;
      public VisPlayer(String fileName)
        super("VisPlayer");
        vp = new VisPanel(fileName);
         Container c = getContentPane();
        c.setLayout( new BorderLayout() );
        c.add(vp, BorderLayout.CENTER);
        JPanel p=new JPanel();
        modifyobj=new JButton("Ok");
        modifyobj.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
            vp.modifyObject();
        p.add(modifyobj,BorderLayout.CENTER);
        c.add(p,BorderLayout.NORTH);
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        pack();
        setResizable(false);
        setVisible(true);
      public static void main(String[] args)
      { new VisPlayer("hand1.obj"); }
    }

  • Blotching of JButtons

    I am not sure if its a bug but this really seems like one. When i add a JPanel to a JFrame and add a JToolbar in vertical orientation with the buttons having the bevel raised border in java 1.5, these wierd blotching occur on the edges of the buttons.
    Can anyone help me with this? its on java1.5.0_03
    here is the code
    * Album.java
    * Created on July 22, 2005, 3:15 PM
    package Album;
    import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
    import javax.swing.JFileChooser;
    import javax.swing.UIManager;
    * @author ccb3101
    public class Album extends javax.swing.JFrame {
    /** Creates new form Album */
    public Album() {
    try
    UIManager.setLookAndFeel (new WindowsLookAndFeel());
    catch(Exception e){e.printStackTrace ();}
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents()
    jPanel1 = new javax.swing.JPanel();
    jToolBar1 = new javax.swing.JToolBar();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    File = new javax.swing.JMenuBar();
    fileMenu = new javax.swing.JMenu();
    jMenuItem1 = new javax.swing.JMenuItem();
    jMenu1 = new javax.swing.JMenu();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jPanel1.setLayout(new java.awt.BorderLayout());
    jToolBar1.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
    jToolBar1.setFloatable(false);
    jToolBar1.setOrientation(1);
    jToolBar1.setVerifyInputWhenFocusTarget(false);
    jButton1.setText("jButton1");
    jButton1.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
    jButton1.setDoubleBuffered(true);
    jButton1.setMargin(new java.awt.Insets(2, 2, 2, 2));
    jToolBar1.add(jButton1);
    jButton2.setText("jButton2");
    jButton2.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
    jToolBar1.add(jButton2);
    jButton3.setText("jButton3");
    jButton3.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
    jToolBar1.add(jButton3);
    jButton4.setText("jButton4");
    jButton4.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
    jToolBar1.add(jButton4);
    jPanel1.add(jToolBar1, java.awt.BorderLayout.EAST);
    getContentPane().add(jPanel1, java.awt.BorderLayout.EAST);
    fileMenu.setText("File");
    fileMenu.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(java.awt.event.ActionEvent evt)
    fileMenuActionPerformed(evt);
    jMenuItem1.setText("Item");
    jMenuItem1.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(java.awt.event.ActionEvent evt)
    jMenuItem1ActionPerformed(evt);
    fileMenu.add(jMenuItem1);
    File.add(fileMenu);
    jMenu1.setText("Edit");
    File.add(jMenu1);
    setJMenuBar(File);
    pack();
    // </editor-fold>
    private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setVisible(true);
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Album().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JMenuBar File;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration
    }

    Oki.
    I thought that an array would be good. Easier to control the buttons then.
    After I clicked one of the buttons i get a new frame with new buttons and so forth and so on.
    If I don't have arrays I have to write almost the same thing for all the buttons...
    Do you have a better idea, I'm more than glad to hear!

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • Vertical text in JComponents... here is a solution!!

    Hi all,
    I saw a posting on the subject of vertical Strings in JComponent and a guy gave a so usefull solution that I could not keep it for me self...Thats from R2D2 on the forum question
    http://forum.java.sun.com/thread.jsp?forum=54&thread=137301&start=0&range=15#370918
    If you want to put vertical Strings inside a JComponent just format your text using HTML like this
    "<html>H<br>E<br>L<br>L<br>O"
    This can be put into Tooltip as well!
    JRG

    Yop, Swing version >= Swing 1.1.1 Beta 1
    has this feature, add HTML to JButton, JLabel, JToolTip ... etc
    And default JTree, JTable use JLabel renderer ==> so by default JTree, JTable also can use HTML too.
    And the furture of Swing will make Menu Item can set HTML text.
    :-)))

  • Vertical headers for columns in JTable

    Hi,
    I'm actually working on JTables and i'd like to set the headers of some columns to appear vertically instead of by default horizontal.
    I've found some tuts or examples to set the header on multiple lines but no one to set the header vertical...
    I want something like that :
    before :
    column1 | column2
    row1 |
    row2 |
    and after setting header columns vertical ( with column1 and column2 the column headers of my JTable )
    c | c
    o | o
    l | l
    u | u
    m | m
    n | n
    1 | 2
    ( and orientation of row headers not changed )
    Thanx for your reply
    Scottish

    Hi,
    Create you own colunm header renderer... it is actualy a cellRenderer. That cellRenderer should extends JLabel or JButton depending on what you want and you must put a paint method in it that draws the vertical text.
    JRG

  • Vertical scrollbar does not appear

    Hi all!
    Here is my problem.
    I have a JPanel on a JScrollPane (called: container).
    I have an other class which extends JPanel (called: component).
    I have a JButton which adds a new from component to container on every click. (container's layout is null, and I use the setBounds method on component).
    After every adding I've just set a new height to the container (setSize(container.getWidth(), container.getHeigth()+100)), but vertical scrollBars of JScrollPane does not appear.
    I tried to call the revalidate, repaint methods on the container but it did not work.
    Please help me!

    Which JScrollPane constructor are you using? If you're using one that does not specify scrollbar policy parameters, horizontal and vertical scrollbars only appear if the component's contents are larger than the view. You can of course set a JScrollPane's scollbar policies by calling the appropriate mutator methods: setVerticalScrollBarPolicy and setHorizontalScrollBarPolicy.

  • Simple layout issue: positioning text atop a JButton image

    (I apologize for the cross-post; I assumed that this forum was for relatively advanced Swing topics, and therefore initially posted this question in the "New to Java Technology" forum.)
    I've got a newbie Swing problem that I just can't seem to figure out. Basically, I'd like to place text for a JButton in a certain location within the image I'm using for the button. If I use the following code:
    String buttonText = MyStringFactory.getString();
    JButton myButton = new JButton(buttonText, new ImageIcon("myimage.png"));
    myButton.setHorizontalTextPosition(SwingConstants.CENTER);
    myButton.setVerticalTextPosition(SwingConstants.CENTER);The text will display within the button, but it will be exactly centered atop the image. What I'd like is to have the text displayed on top of the image, but to be left-aligned. So, instead of:
    |        Test        |
    ----------------------I want:
    | Test               |
    ----------------------Where the image behind the word "Test" is the image specified when I created the myButton JButton object. The string can be of varying length and must support various fonts (i.e., simply using a monospaced font and padding on the right-side of the string with spaces isn't an option). In more explicit terms, what I want is a way to center the text vertically with respect to the background image, and place it (the text) X pixels from the left-hand side of the background image.
    I've looked at using OverlayLayout to solve this problem, creating a JButton and a JLabel and placing them both within a JPanel. However, when I do this, the JLabel is always rendered behind the JButton, so I can't see it. Is there any way to specify the z-ordering of objects in a JPanel when using OverlayLayout?
    Or is there a much simpler solution to this (seemingly) simple problem?
    Thanks in advance for any assistance!

    hello guy,
    well, you seem to want your text to be in a very specific position since you mention x pixels.
    i don't think you can tell a JButton where exactly to draw the text and icon.
    if you want to do that, you'll have to create you own button.
    something like that:
    class CustomButton extends JButton {
    String text;
    ImageIcon icon;
    public CustomButton(String text, ImageIcon icon) {
    // only use the default constructor of the JButton
    // and save the text and icon separately
    super();
    this.text = text;
    this.icon = icon;
    // set some preferred size so that the layout
    // manager has some idea of how big your button will be
    this.setPreferredSize(new Dimension(
    icon.getIconWidth(),
    2*icon.getIconHeight()));
    // override paintComponent()
    public void paintComponent(Graphics g) {
    // first call this method in the super class
    // this will draw your button color, outline, borders..
    super.paintComponent(g);
    // now draw your icon whereever you want it on
    // your button
    g.drawImage(icon.getImage(),5,
    getHeight()/2-icon.getIconHeight()/2,null,this);
    // and draw your string.
    // using FontMetrics to get the dimensions of your
    // string will allow it to be independent of
    // font type and size
    g.drawString(text, icon.getIconWidth()+10,
    getHeight()/2+g.getFontMetrics().getAscent()/2);
    hope that helps a bit :)
    cheers, alex.

  • Initial vertical positioning in JFrame

    In my frame(using GridBagLayout) I have several components, out of which some are not visible in the beginning. The problem is that the components that are visible in the beginning are positioned in the center of the screen, and when the rest of the components become visible, those components change position according to the space taken by the "new" components. So I would like the components' position to be initially static.
    Hope this is clear enough...
    There is a short piece of code, which demonstrates the prob...
    j
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class PositionTest extends JFrame{
         JButton buttShow = new JButton("Show the other button...");
         JButton buttTheOtherButton = new JButton("This is the other button");
         public PositionTest() throws Exception {
                   initFrame();
         private void initFrame() throws Exception {
              this.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent event) {
                        System.exit(0);
              buttShow.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        buttShow_actionPerformed(event);
              buttTheOtherButton.setVisible(false);
              this.getContentPane().setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.gridx=1;
              c.gridy=1;
              this.getContentPane().add(buttShow,c);
              c.gridy++;
              this.getContentPane().add(buttTheOtherButton,c);
              this.setTitle("TestFrame");
              this.setResizable(false);       
              this.setSize(200, 90);
              this.setLocation(100, 100);
              this.setVisible(true);
         public void buttShow_actionPerformed(ActionEvent event) {
              buttTheOtherButton.setVisible(true);
         public static void main(String[] args) throws Exception {
              PositionTest pt = new PositionTest();
    }

    I changed your code a little bit. I added an empty JLabel which holds all extra space.
    regards
    Stas
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame{
            JButton buttShow = new JButton("Show the other button...");
            JButton buttTheOtherButton = new JButton("This is the other button");
            public Test() throws Exception {
                            initFrame();
            private void initFrame() throws Exception {
                    this.addWindowListener(new WindowAdapter() {
                            public void windowClosing(WindowEvent event) {
                                    System.exit(0);
                    buttShow.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent event) {
                                    buttShow_actionPerformed(event);
                    buttTheOtherButton.setVisible(false);
                    this.getContentPane().setLayout(new GridBagLayout());
                    GridBagConstraints c = new GridBagConstraints();
                    c.gridx=1;
                    c.gridy=1;
                    this.getContentPane().add(buttShow,c);
                    c.gridy++;
                    this.getContentPane().add(buttTheOtherButton,c);
                    c = new GridBagConstraints();
                    c.gridx=1;
                    c.gridy=100;
                    c.fill=GridBagConstraints.VERTICAL;
                    c.weighty=1;
                    this.getContentPane().add(new JLabel(""),c);
                    this.setTitle("TestFrame");
                    this.setResizable(false);
                    this.setSize(300, 290);
                    this.setLocation(100, 100);
                    this.setVisible(true);
            public void buttShow_actionPerformed(ActionEvent event) {
                    buttTheOtherButton.setVisible(true);
            public static void main(String[] args) throws Exception {
                    Test pt = new Test();

  • How do i spin an sphere in degrees horizontally or vertically?

    how do i spin an earth sphere 10 degrees horizontally or vertically when i click a button?
    I don't care how to carry out this process, just want to know how to make an unmoving sphere spin some degrees every time when i click a button.
    can anyone help me out?? thanks
    Regards,
    cat

    add your sphere to a transformGroup then use
    Transform3D transG = new Transform3D();
    yourTransformGroup.getTransform(transG);
    Transform3D temp = new Transform3D();
    temp.rotY(0.05);
    transG.mul(temp);
    yourTransformGroup.setTransform(transG);this will spin it when its called so whack this in a function and call it with a JButton.

  • JButton in a BoxLayout

    A JButton has not the same reaction like a JTextField in a BoxLayout.
    Why? I need something like this and don't know how:
    JLabel JButton
    JLabel JButton
    The JButtons don't have the same Text, but they must have the same size and the same Difference from the JLabel.
    Please send me an E-Mail:
    [email protected]
    Thanks!!!

    You want a 2x2 arrangement? That's not what BoxLayout does: "A layout manager that allows multiple components to be laid out either vertically or horizontally."
    Try a GridLayout and set the number of Rows/Cols. "The container is divided into equal-sized rectangles, and one component is placed in each rectangle." This results in equal size for all - JLabel same size as JButton.
    If this doesn't meet your needs, then there's GridBagLayout, which is real easy to setup if you have a WYSIWYG GUI editor, like Forte.
    Remember, you're encouraged to group stuff in JPanels to makes things easier. For instance, you might create 2 JPanels - one for JLabels and one for JButtons - give each one a GridLayout (col=1,rows=#rows) so all JLabels are same size and all JButtons are same size. Put the 2 JPanels side-by-side with a FlowLayout and you're golden.

  • Align JLabels and JTextFields vertically in different areas

    I like to have 3 TitledBorders for 3 different areas of my frame.
    Each area has its own components - JLabels, JTextField, etc.
    How to align JLabels and JTextFields vertically in different areas?
    e.g. for the following test program, how to configure label1, label2, label3 so that their right sides all align vertically and
    tf1, tf2, tf3 so that their left sides all align vertically?
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.TitledBorder;
    public class TitledBorderDemo extends JFrame {
      public TitledBorderDemo() {
        super("TitledBorderDemo");
        JTextField tf1 = new JTextField("hello", 6);
        JTextField tf2 = new JTextField("hello", 12);
        JTextField tf3 = new JTextField("test");
        JTextField tf4 = new JTextField("test2");
        JLabel label1 = new JLabel("1234567890ertyuiyup label");
        JLabel label2 = new JLabel("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz long label");
        JLabel label3 = new JLabel("short label");
        JLabel label4 = new JLabel("test");
        JPanel panel_tf = new JPanel(new GridBagLayout());
        JPanel panel_pf = new JPanel(new GridBagLayout());
        JPanel panel_ftf = new JPanel(new GridBagLayout());
        GridBagConstraints constraints = new GridBagConstraints(0, 0, 3, 3,
                0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0);
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_tf.add(label1, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_tf.add(tf1, constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_pf.add(label2, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_pf.add(tf2, constraints);
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.WEST;
        panel_ftf.add(label3, constraints);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel_ftf.add(tf3, constraints);
        constraints.gridx = 3;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.WEST;
        panel_ftf.add(label4, constraints);
        constraints.gridx = 4;
        constraints.anchor = GridBagConstraints.EAST;
        panel_ftf.add(tf4, constraints);
        panel_tf.setBorder(new TitledBorder("JTextField1"));
        panel_pf.setBorder(new TitledBorder("JTextField2"));
        panel_ftf.setBorder(new TitledBorder("JTextField3"));
        JPanel pan = new JPanel(new GridLayout(3, 1, 10, 10));
        pan.add(panel_tf);
        pan.add(panel_pf);
        pan.add(panel_ftf);
        this.add(pan);
      public static void main(String args[]) {
        JFrame frame = new TitledBorderDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 450);
        frame.setVisible(true);
    }

    Thank you! It works!
    I add some labels & components to your demo program.
    Most of the components align vertically.
    How to align the "Country", "Test2" & "Extension" labels on the right sides?
    How to align their corresponding components so that their left sides all align vertically?
    How to make the Cancel button stick to the Save button
    (i.e. eliminate the gap between the Cancel and the Save button)?
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TitledBorderDemoNew extends JFrame {
      public TitledBorderDemoNew() {
        super("TitledBorderDemoNew");
        JLabel nameLabel = new JLabel("Name");
        JTextField nameText = new JTextField(20);
        JLabel addressLabel = new JLabel("Address (City & State)");
        JTextField addressText = new JTextField(40);
        JLabel countryLabel = new JLabel("Country");
        JTextField countryText = new JTextField(30);
        JLabel testLabel = new JLabel("Test");
        JTextField testText = new JTextField(20);   
        JLabel test2Label = new JLabel("Test2");
        JTextField test2Text = new JTextField(20);   
        JLabel phoneLabel = new JLabel("Phone");
        JTextField phoneText = new JTextField(20);
        JLabel extensionLabel = new JLabel("Extension");
        JTextField extensionText = new JTextField(5);
        JLabel postalCodeLabel = new JLabel("Postal Code");
        JTextField postalCodeText = new JTextField(6);
        JButton saveButton = new JButton("Save");
        JButton cancelButton = new JButton("Cancel");
        JButton commentButton = new JButton("Comment");
        int longWidth = addressLabel.getPreferredSize().width;
        GridBagConstraints constraints = new GridBagConstraints();
        JPanel p1 = new JPanel(new GridBagLayout());
        p1.setBorder(createBorder("Name"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p1.add(nameLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p1.add(nameText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p1.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p1.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p2 = new JPanel(new GridBagLayout());
        p2.setBorder(createBorder("Address"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(addressLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p2.add(addressText, constraints);
        // extra label & component
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,36,4,6);
        p2.add(countryLabel, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(countryText, constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(testLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p2.add(testText, constraints);
        // extra label & component
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,36,4,6);
        p2.add(test2Label, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p2.add(test2Text, constraints);
        constraints.gridx = 4;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p2.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p2.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p3 = new JPanel(new GridBagLayout());
        p3.setBorder(createBorder("Phone"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p3.add(phoneLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p3.add(phoneText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p3.add(extensionLabel, constraints);
        constraints.gridx = 3;
        constraints.anchor = GridBagConstraints.WEST;
        p3.add(extensionText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p3.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p3.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p4 = new JPanel(new GridBagLayout());
        p4.setBorder(createBorder("Postal Code"));
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(4,6,4,6);
        p4.add(postalCodeLabel, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        p4.add(postalCodeText, constraints);
        constraints.gridx = 2;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p4.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.fill = GridBagConstraints.NONE;
        constraints.weightx = 0.0;
        p4.add(Box.createHorizontalStrut(longWidth), constraints);
        JPanel p5 = new JPanel(new GridBagLayout());
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(4,6,4,6);
        p5.add(commentButton, constraints);
        constraints.gridx = 1;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        p5.add(Box.createHorizontalGlue(), constraints);
        constraints.gridx = 2;
        constraints.gridwidth = GridBagConstraints.RELATIVE;
        constraints.fill = GridBagConstraints.NONE;
        constraints.anchor = GridBagConstraints.EAST;
        p5.add(cancelButton, constraints);
        constraints.gridx = 3;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.anchor = GridBagConstraints.EAST;
        p5.add(saveButton, constraints);
        JPanel panel = new JPanel(new GridBagLayout());
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        panel.add(p1, constraints);
        constraints.gridy = 1;
        panel.add(p2, constraints);
        constraints.gridy = 2;
        panel.add(p3, constraints);
        constraints.gridy = 3;
        panel.add(p4, constraints);
        constraints.gridy = 4;
        panel.add(p5, constraints);
        this.add(new JScrollPane(panel));
      private Border createBorder(String title)
        TitledBorder b = new TitledBorder(title);
        b.setTitleColor(Color.RED.darker());
        return b;
      public static void main(String args[]) {
        JFrame frame = new TitledBorderDemoNew();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }Edited by: 833768 on 26-Apr-2011 10:32 AM

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

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

  • Jscrollbar and events on jbuttons

    Hi
    I'm trying to add a listener to jbuttons of a jscrollbar
    I tried to add:
    jScrollBar1.addMouseListener(new MouseListener() {
    but only events on thumb or track are triggered.
    What's more, from addAdjustmentListener I cannot tell if it is a mouse event.
    thanks
    Massimo

    camickr wrote:
    Well, dragging the scrollbar or clicking on the buttons does not change the Caret position, it only move the viewport.It would be interesting to attach a listener to the viewport but its changeListener doesn't tell anything useful
    >
    I would think all you need to worry about is the change listener. When the scrollbar is at the bottom you enable automatic scrolling. When it is not at the bottom you disable automatic scrolling.ok, I've tried doing that on document changeListener, and it works for edit events, such as mouse click in the textarea, key press, etc
    However, it is not called on mouse clicks on vertical scroll bar
    [Text Area Scrolling|http://www.camick.com/java/blog.html?name=text-area-scrolling] shows how this can be done easily by using the caret update policy. I have only tried it on a text area, but I assume it should also work for a text pane.
    Thank you. Caret update policy was fine and simplified my code, but I am still stuck to the initial problem, how to detect mouse click on vertical scrollbar

Maybe you are looking for

  • IPod Nano Screen is blank and dosen't turn on or off.

    I leave my ipod nano on for 2 seconds. Screen turns blank and dosen't turn on or off. iTunes dosen't recognize it. Nothing I do works. Charging dosen't work. iPod, however seems to be on sleep mode.

  • Converting VARCHAR2 to a DATE type-then need month spelled out

    I have a field that should be a DATE type, but is instead a VARCHAR2(8). The data in the VARCHAR2(8) field is displayed as what looks like a date -- EX: 09/18/09. I need to be able to convert the VARCHAR2(8) field so that it brings back the spelled o

  • Press Ready Form

    Hi all - I have created a form in Acrobat 8 Pro. It is an order form that allows the end user to fill in their mailing address to customize a postcard. This is then sent directly to a printer for off set printing. The form itself is all set for print

  • Management Studio

    Hello everyone, First of all let me apologies about my English it's not so good, I'm new to oracle and its other stuffs, I want to know what is the best management studio that able to design diagrams just like SQL Server Management Studio ? I've not

  • Problem with DBMS_LOB.SUBSTR

    Hi, i want to encode a BLOB into BASE64_ENCODE. Here my PL/SQL function: FUNCTION encodeBlob2Base64(pBlobIn IN BLOB) RETURN BLOB IS vAmount PLS_INTEGER := 20000; vBase64Blob BLOB; vBlobIn BLOB; vOffset PLS_INTEGER := 1; BEGIN vBlobIn := pBlobIn; dbms