A JLabel in 2 lines

Hi I want to have a label that will be across two lines.
Something like this.
Remaining
Characters
instead of "Remaning Characters" which becomes long. How to do this?
I tried a "\n" in between like
JLabel lCount = new JLabel("Remaining\nCharacters");
BUT IT IS NOT WORKING?
Can someone tell me how to achieve this?

I am not sure, but maybe you can use <br>.
Take a look at: http://java.sun.com/docs/books/tutorial/uiswing/components/label.html

Similar Messages

  • Line in a JLabel that disappear when adding to a new frame

    Hi,
    I have the main frame (SampleFrame), where I put a JPanel with CardLayout, I want when I click on a button, a new JPanel (SamplePanel) is shown.
    The problem is this new JPanel shows a picture (a line in a JLabel), the poblem is the picture does not appear...
    The code is the following:
    package sample;
    //Main Class
    public class Main {
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new SampleFrame().setVisible(true);
    //SampleFrame
    package sample;
    import  javax.swing.JPanel;
    import javax.swing.*;
    import java.awt.*;
    public class SampleFrame extends javax.swing.JFrame {
        private SamplePanel samplePanel;
        private boolean flag;
         /** Creates new form SampleFrame */
        public SampleFrame() {
            initComponents();
            flag=false;
            samplePanel = new SamplePanel();
            jPanel1.add(samplePanel,"sample");
        /** 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();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jPanel1.setLayout(new java.awt.CardLayout());
            jButton1.setText("OK");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .addContainerGap()
                            .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 189, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(layout.createSequentialGroup()
                            .add(81, 81, 81)
                            .add(jButton1)))
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 182, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 19, Short.MAX_VALUE)
                    .add(jButton1)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
            CardLayout cl = (CardLayout)(jPanel1.getLayout());
            cl.show(jPanel1, "sample");
            flag=true;
          /*  this.setVisible(false);
            this.setVisible(true);*/
         public void paint(Graphics g)
            super.paint(g);
            if(flag)samplePanel.ReDraw();
        public void printAll(Graphics g)
            super.printAll( g);
            if(flag)samplePanel.ReDraw();
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration                  
    //SamplePanel
    package sample;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class SamplePanel extends javax.swing.JPanel {
        /** Creates new form SamplePanel */
        public SamplePanel() {
            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() {
            jLabel1 = new javax.swing.JLabel();
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 150, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 150, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        }// </editor-fold>                       
         public void paint(Graphics g)
            super.paint(g);
            ReDraw();
        public void printAll(Graphics g)
            super.printAll( g);
            ReDraw();
        public void ReDraw()
            Graphics g = jLabel1.getGraphics();
            g.drawLine(0,0,100,100);
        // Variables declaration - do not modify                    
        private javax.swing.JLabel jLabel1;
        // End of variables declaration                  
    }I have discovered that with the comment lines in SampleFrame (method jButton1ActionPerformed):
    /*  this.setVisible(false);
    this.setVisible(true);*/works properly, but I dont like this way...
    Can anyone helps me? Thanks ;)

    Hi again crwood!!
    Okay, you're taking the content pane, a Container, from a top�level container (you mentioned a frame, "oldFrame"). And this container contains some JLabels which have lines drawn in them. You want to add this container to a card in a Cardlayout. Okay, so far so good.
    That�s exactly what I want ;).
    So (using your code):
    I have the panel:
    class SP extends JPanel {
        private int x1;
        private int y1;
        private int x2;
        private int y2;
        private Color color;
         private JLabel label;
        public SP(int x1, int y1, int x2, int y2, Color c) {
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
            color = c;
            setLayout(new BorderLayout());
            label =new JLabel();
            add(label);
        protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
              label.getGraphics().setColor(color);
              label.getGraphics().drawLine(x1, y1, x2, y2);
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
    }And the main frame:
    public class SF extends JFrame {
        private JPanel jPanel1;
        public SF() {
            // Initialize components.
            jPanel1 = new JPanel(new CardLayout());
            jPanel1.add(new SP(10,10,100,100,Color.red), "sample 1");
            jPanel1.add(new SP(50,150,200,50,Color.blue), "sample 2");
            JButton jButton1 = new JButton("OK");
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CardLayout cl = (CardLayout)(jPanel1.getLayout());
                    cl.next(jPanel1);
            JPanel south = new JPanel();
            south.add(jButton1);
            // Configuration and assemble JFrame.
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            add(jPanel1);   // Default center section.
            add(south, "Last");
            pack();
            setLocation(200,200);
            setVisible(true);
        public static void main(String[] args) {
            new SF();
    }The problem is I cant see the black line...
    (I am able to see it by moving the window until hide part of it)

  • Problem in drawing a line in Java Application Program

    Hi,
    I am trying to draw a line after a message is displayed on the screen. But the line is not at all coming on the screen while running. but I can see a red line is appearing on the screen first and and it is getting overridden.
    There is something wrong in the concept what I understood about graphics.Can anybody help to
    understand where the problem is ?
    Here is the part of the code which used to draw line.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import java.util.Date.*;
    import java.text.*;
    import java.lang.*;
    import MyPack.*;
    class chalan_pay extends JFrame
    JTextField jt1,jt2,jt3,jt4,jt5;
    JLabel jlh,jl1,jl2,jl3,jl4,jl5,jl10;
    JButton bt1,bt2,bt3;
    Choice ch1,ch2,ch3,ch4;
    Connection con = null;
    int i1no,i2no,i3no,i4no,itno;
    String idate;
    public chalan_pay()
    getContentPane().setLayout(null);
    jt1= new JTextField(5);
    jt1.setBounds(110,150,50,20);
    jt2= new JTextField(10);
    jt2.setBounds(400,150,100,20);
    jt3= new JTextField(3);
    jt3.setBounds(590,150,30,20);
    jt4= new JTextField(2);
    jt4.setBounds(750,150,30,20);
    jlh= new JLabel();
    jlh.setText("CHALLAN DETAILS");
    jlh.setBounds(300,50,200,20);
    jl1= new JLabel();
    jl1.setText("IGM No. ");
    jl1.setBounds(50,150,100,20);
    jl2= new JLabel();
    jl2.setText("IGM Date ");
    jl2.setBounds(340,150,100,20);
    jl3= new JLabel();
    jl3.setText("Line No. ");
    jl3.setBounds(530,150,100,20);
    jl4= new JLabel();
    jl4.setText("Subline No. ");
    jl4.setBounds(680,150,100,20);
    jl10= new JLabel();
    jl10.setBounds(100,200,300,20);
    ch1= new Choice();
    ch1.setBounds(170,150,150,20);
    getContentPane().add(ch1);
    ch1.addItemListener(new Opt1());
    bt1= new JButton("Exit");
    bt1.setBounds(200,600,100,20);
    getContentPane().add(bt1);
    bt1.addActionListener(new Ex());
    try
    con=db_connect.getConnection();
    Statement st1 = con.createStatement();
    ResultSet rs1 = st1.executeQuery("select igm_no,to_char(igm_dt,'DD-MON-YY'),line_no,subline_no from "+
    "det_item order by igm_no");
    while(rs1.next())
    ch1.addItem(String.valueOf(rs1.getInt(1))+" "+rs1.getString(2)+" "+
    String.valueOf(rs1.getInt(3))+" "+String.valueOf(rs1.getInt(4)));
    rs1.close();
    st1.close();
    catch(Exception e){e.printStackTrace();}
    getContentPane().add(jlh);
    getContentPane().add(jl1);
    getContentPane().add(jt1);
    getContentPane().add(jl2);
    getContentPane().add(jt2);
    getContentPane().add(jl3);
    getContentPane().add(jt3);
    getContentPane().add(jl4);
    getContentPane().add(jt4);
    getContentPane().add(jl10);
    setSize(900,700);
    setVisible(true);
    show();
    public void paint(Graphics g)
    g.setColor(Color.red);
    g.drawLine(0,300,600,300);
    class Ex implements ActionListener
    public void actionPerformed(ActionEvent evt)
    if(evt.getSource() == bt1)
    dispose();
    return;
    This code is incomplete. The program is compiled and Ran. I am unable to see the Line.
    Is it because , I am using contentPane ?. Please help me to cake it clear.
    mjava

    I have no idea what JTutor is, but if it tells you to override paint() in Swing, it's not worth its disk space.
    [http://java.sun.com/docs/books/tutorial/uiswing/painting/closer.html] clearly says that for all practical purposes paintComponent will be the only method that you will ever need to override.

  • Compare two string in different line in textarea

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextCounterPanel extends JPanel {
    private JTextArea textInput;
    private JLabel lineCountLabel;
                        public TextCounterPanel() {
                        setBackground(Color.DARK_GRAY);
                        textInput = new JTextArea();
                        textInput.setBackground(Color.WHITE);
                        JPanel south = new JPanel();
                        south.setBackground(Color.DARK_GRAY);
                        south.setLayout( new GridLayout(4,1,2,2) );
                             JButton countButton = new JButton("Process the Text");
                             countButton.addActionListener( new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       processInput();
                             south.add(countButton);
                        lineCountLabel = new JLabel(" Number of lines:");
                        lineCountLabel.setBackground(Color.WHITE);
                        lineCountLabel.setForeground(Color.BLUE);
                        lineCountLabel.setOpaque(true);
                        south.add(lineCountLabel);
                        setLayout( new BorderLayout(2,2) );
                        setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
                        JScrollPane scroller = new JScrollPane( textInput );
                        add(scroller, BorderLayout.CENTER);
                        add(south, BorderLayout.SOUTH);
    public void processInput() {
    String text,vin; // The user's input from the text area.
    text = textInput.getText();
    vin =text.substring(25,42);
    lineCountLabel.setText(" vin: " + vin);
    } // end class TextCounterPanel
    How can I compare two string in different line in text area

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextCounterPanel extends JPanel {
    private JTextArea textInput;
    private JLabel lineCountLabel;
    public TextCounterPanel() {
    setBackground(Color.DARK_GRAY);
    textInput = new JTextArea();
    textInput.setBackground(Color.WHITE);
    JPanel south = new JPanel();
    south.setBackground(Color.DARK_GRAY);
    south.setLayout( new GridLayout(4,1,2,2) );
    JButton countButton = new JButton("Process the Text");
    countButton.addActionListener( new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    processInput();
    south.add(countButton);
    lineCountLabel = new JLabel(" Number of lines:");
    lineCountLabel.setBackground(Color.WHITE);
    lineCountLabel.setForeground(Color.BLUE);
    lineCountLabel.setOpaque(true);
    south.add(lineCountLabel);
    setLayout( new BorderLayout(2,2) );
    setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
    JScrollPane scroller = new JScrollPane( textInput );
    add(scroller, BorderLayout.CENTER);
    add(south, BorderLayout.SOUTH);
    public void processInput() {
    String text,vin; // The user's input from the text area.
    text = textInput.getText();
    vin =text.substring(25,42);
    lineCountLabel.setText(" vin: " + vin);
    } // end class TextCounterPanel

  • Updating a JLabel Too Fast Crashes Program

    I have a recursive method that runs for 80 seconds (in a thread
    outside the GUI). The recursive method is probably being called
    20,000 times in this 80 seconds.
    I am calling myJlabel.setText("" + someVariable) every call to this recursive method.
    About half the time I run this program it crashes with the following error.
    Does anybody know why this is happening?
    I believe it has something to do with the speed of the calls because
    when I slow the method considerably (10x) I never get the error.
    I dont just want to wrap the call in try/catch without knowing the cause.
    Thanks!
    Exception in thread "Thread-2" java.lang.NullPointerException
            at javax.swing.text.View.setParent(View.java:322)
            at javax.swing.text.CompositeView.setParent(CompositeView.java:119)
            at javax.swing.text.View.setParent(View.java:325)
            at javax.swing.text.CompositeView.setParent(CompositeView.java:119)
            at javax.swing.text.FlowView.setParent(FlowView.java:272)
            at javax.swing.text.html.ParagraphView.setParent(ParagraphView.java:58)
            at javax.swing.text.View.setParent(View.java:325)
            at javax.swing.text.CompositeView.setParent(CompositeView.java:119)
            at javax.swing.text.html.BlockView.setParent(BlockView.java:55)
            at javax.swing.text.html.HTMLEditorKit$HTMLFactory$BodyBlockView.setParent(HTMLEditorKit.java:1277)
            at javax.swing.text.View.setParent(View.java:325)
            at javax.swing.text.CompositeView.setParent(CompositeView.java:119)
            at javax.swing.text.html.BlockView.setParent(BlockView.java:55)
            at javax.swing.plaf.basic.BasicHTML.updateRenderer(BasicHTML.java:194)
            at javax.swing.plaf.basic.BasicLabelUI.propertyChange(BasicLabelUI.java:409)
            at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:339)
            at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:276)
            at java.awt.Component.firePropertyChange(Component.java:7865)
            at javax.swing.JLabel.setText(JLabel.java:311)
            at LoadFrame.setInfo(LoadFrame.java:44)
            at LoadHandler.update(LoadHandler.java:67)
            at FilesLoader.recurseProcess(FilesLoader.java:69)
            at FilesLoader.recurseProcess(FilesLoader.java:93)
            at FilesLoader.run(FilesLoader.java:42)
            at java.lang.Thread.run(Thread.java:619)

    Are you updating the label in the Event Dispatch
    Thread (EDT)?I dont believe so. I spawn off a new thread to do the
    recursive file loading and that calls the JLabel.setText(...)
    The loading takes 80 secs and I can still use the GUI so I
    wouldnt think anything is happening in the EDT.
    Another bizarre glitch is that my JLabel has 4 lines of text like this:
    bold: plain
    bold: plain
    bold: plain
    And the bold and plain text are randomly glitching out.
    Sometimes a whole line will be bold, all not bold, all bold, plain
    ones bold, vice versa. Just random-ness.
    This is the code for setting the text:
    public void setText(String path, long folderCount, long fileCount, long ms){
    String time = (ms / 1000) + " seconds";
    infoLabel.setText("<html><b>Current Folder:</b> " + path +
    "<br><b>Folders:</b> " + folderCount +
    "<br><b>Files:</b> " + fileCount +
    "<br><b>Time:</b> " + time + "</html>");
    }

  • Line wrapping and scrolling in JPanel

    Hello,
    I've got an empty JPanel to which I want to add an (unknown) number of JLabels. Each JLabel has a text which is just one word. When my program is adding JLabels to the JPanel, I want it to have the same behaviour as a normal text editor: when a line is full, the next line gets filled (line wrapping).
    If I just keep adding JLabels to a JPanel of a fixed size with .add(), there's no line wrapping. I tried it by giving the JPanel a fixed size, flowLayout and nesting it within a JScrollPane, but it keeps filling one long line, instead of jumping to the next one.
    Any obvious solutions??
    Thanks
    Mark

    well this depends on how your layout is build, you should post some code so we can see what your trying to do.
    For example if your JPanel is the Frame's main panel, fixing a MaximumSize or PreferredSize wont have any effect, it will grow as big as you defined the JFrame size.
    If you have only a JPanel with a max size of 200,300 in a JFrame with a size of 800,600, it will grow to 800,600.
    You could create a BoxLayout with X axis, then insert an HorizontalStruts, insert your JPanel and another Horizontal Struts(Box.createHorizontalStrut(int width) ) to force the JPanel to be smaller than the JFrame.
    I did not test this a lot, but it seams to work
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
      public static MyFrame frame ;
      public static void main(String[] args) {
        frame = new MyFrame();
        frame.show(true);
        frame.pack();
      public static class MyFrame extends JFrame {
        JLabel a, b, c, d, e, f, g, h, i, j, k ;
        public MyFrame(){
          super();
          JPanel sizeLimiter = (JPanel)this.getContentPane();
          sizeLimiter.setLayout(new BoxLayout(sizeLimiter, BoxLayout.X_AXIS));
         // sizeLimiter.setPreferredSize(new Dimension(800,600));
          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new FlowLayout());
          mainPanel.setPreferredSize(new Dimension(400,300));
          mainPanel.setMinimumSize(new Dimension(400,300));
          a = new JLabel("this is sample test ");
          b = new JLabel("to demonstrate an example ");
          c = new JLabel("of simple a flow layout ");
          d = new JLabel("which is wrapping ");
          e = new JLabel("when it reaches the end ");
          f = new JLabel("of a line. ");
          g = new JLabel("Set the maximum size of the panel ");
          h = new JLabel("And it should work ");
          i = new JLabel("If it doesnt post your code so we can");
          j = new JLabel("check it out to see whats wrong ");
          k = new JLabel("sincerly yours, Jf Beaulac ");
          mainPanel.add(a);
          mainPanel.add(b);
          mainPanel.add(c);
          mainPanel.add(d);
          mainPanel.add(e);
          mainPanel.add(f);
          mainPanel.add(g);
          mainPanel.add(h);
          mainPanel.add(i);
          mainPanel.add(j);
          mainPanel.add(k);
          // Fix some "margins"
          sizeLimiter.add(Box.createHorizontalStrut(200));
          // Squeeze the panel
          sizeLimiter.add(mainPanel);
          sizeLimiter.add(Box.createHorizontalStrut(200));
        protected void processWindowEvent(WindowEvent e) {
          super.processWindowEvent(e);
          if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            this.dispose();
    }Regards,
    Jf Beaulac

  • How to disable html view in JLabel

    "As of Swing 1.1.1 Beta 1, JLabel supports multiple lines, multiple fonts, and a whole lot more because you can specify a label's text using HTML. "
    does any one know how to disable this feature, so that if HTML code is entered, it wont be parsed andwhat ever was entered will be displayed, as is, on the JLabel????

    I dont really have control of what is being entered.Whose program is it, then, that contains the setText() method for the JLabel? (Or creates a JLabel with some text?) If it's yours, then I don't see why you can't examine the text before you call that line of code and modify the text as suggested earlier.

  • JLabel should always be on top

    Hi,
    I have two JLabels and I am drawing line between them. I am taking the points as centers of the JLabels. When I draw the line, the line on the Label is shown. How can we display the JLabel on the line in the JLabel area?
    Regards
    Kishore.

    Hi,
    If you are using JLayeredPane put the JLabels in a higher layer.
    JRG

  • How can I find components in a JTextPane

    I have created a JTextPane with Jlabels imbeded in line. How can I search the JTextPane and replace the Jlabels with text.
    Thank you in advance.

    Use the document from the pane.
    Cast it to StyledDocument and use getCharacterElement() method to get element from offset. After that you can check Element's attributes by StyleConstants.getComponent(elem.getAttributes());
    increase offset to the elem.getEndOffset() and get the next elem.
    Regards,
    Stas

  • Choice of Text Component

    Hi!
    I need the text component for image and text or only the text output. I also need scrolling, if it is needed, and auto line wrapping.
    In general, I need multiline JLabel with scrolling, line and word wrapping.

    HowdyTom.Sanders:
    where in the formatting help does it tell you how to embed links in the text rather than having to use the ugly URL?To see how it's done, click reply to camickr's post, then click quote original -- basically the format is:
    [ url link] whatever [ /url] (tag with no space).
    ;o)
    V.V.

  • Center aligned Text in image

    Hai,
    I urgently need help. I want to create a jpg image which is totally white in this white image i draw some multiple line text which i want to write in the center of image. I send the Text as string to my class through servlet file. The string has some newline charatcer also. So can anybody tell me how can i draw image with center aligend text.
    I use Graphics2D class for drawing and with fontMetrics to get the length of my message string. But it is not fitted in image and crossing the limit of my image.
    My white image size is not fix i m using different kind of size white image.
    Thanx in advance

    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TextPanel extends JPanel
         public TextPanel(String text)
              setBackground( Color.WHITE );
              setBorder( new EmptyBorder(5, 5, 5, 5) );
              setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              add( Box.createVerticalGlue() );
              StringTokenizer st = new StringTokenizer(text, "\r\n");
              while (st.hasMoreTokens())
                   JLabel line = new JLabel( st.nextToken() );
                   line.setFont( UIManager.getFont( "TextField.font" ) );
                   line.setAlignmentX(0.5f);
                   add( line );
              add( Box.createVerticalGlue() );
         public static void main(String[] args)
              String text =
                   "first line\n" +
                   "second line\n" +
                   "a line with more text\n" +
                   "another line";
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( new TextPanel( text ) );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Another GridBagLayout question

    I still don't get it. Why is it that the weightx is not working properly? The proportion between the label and textfield is greater than the insets I have specified which is 5. Could someone help please.
    JLabel l;
    JComponent comp;             
    JPanel panel = new JPanel();
    panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    comp = new JPanel(new GridBagLayout());
    comp.setBorder(BorderFactory.createTitledBorder(""));
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.WEST;
    gbc.fill = GridBagConstraints.NONE;
    gbc.insets = new Insets(5, 5, 5, 5);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weightx = .1;
    l = new JLabel("ID", JLabel.LEFT);  // This lines up correctly
    comp.add(l, gbc);
    gbc.gridx++;
    gbc.weightx = .9;
    supplierID = new JTextField(5); // This is too far from the label
    comp.add(supplierID, gbc);
    gbc.gridx = 0;
    gbc.gridy++;
    l = new JLabel("Supplier", JLabel.LEFT);
    comp.add(l, gbc);
    gbc.gridx++;
    supplierName = new JTextField("supplier name", 30);             
    comp.add(supplierName, gbc);          
    panel.add(comp);
    comp = new JPanel(new GridBagLayout());
    comp.setBorder(BorderFactory.createTitledBorder("Address"));
    gbc.gridx = 0;
    gbc.gridy = 0;
    l = new JLabel("Mail Addr", JLabel.LEFT);
    comp.add(l, gbc);
    gbc.gridx++;
    supplierAddress1 = new JTextField(20);
    comp.add(supplierAddress1, gbc);
    gbc.gridx++;
    l = new JLabel("Ship Addr", JLabel.LEFT);
    comp.add(l, gbc);
    gbc.gridx++;
    supplierAddress2 = new JTextField(20);
    comp.add(supplierAddress2, gbc);             
    panel.add(comp);            
    return panel;

    Hi allenvpn,
    The weights are used to figure out where to add the extra space to. When dealing with labels you should have their weights set to zero because there is no need to expand them.
    You just have to make the weightx zero for your labels: (ID, Supplier) and make the weightx one for your textfields.
    gbc.weigthx = 0;
    l = new JLabel("ID", JLabel.LEFT); // This lines up correctly
    comp.add(l, gbc);
    gbc.weightx = 1;
    supplierName = new JTextField("supplier name", 30);      
    comp.add(supplierName, gbc);
    gbc.weightx = 0;
    l = new JLabel("Supplier", JLabel.LEFT);
    comp.add(l, gbc);
    gbc.weightx = 1;
    supplierName = new JTextField("supplier name", 30);      
    comp.add(supplierName, gbc);
    This will allow your textfields to align on the left side just beyond the longest label.
    Regards,
    Manfred.

  • Paint component inside JPanel

    Hi guys,
    I will start with the original problem and get to the only option that seems possible before hardcoding everything.
    I need to draw something like a binary tree. Jtree doesn't fall into binary because it does not have the root in the center. <1;2;6;8;9>, where 6 is the root, and 1,2 are its left child's children and 8,9 are right child's children. Since I couldn't find any possible solution of customizing JTree to draw it in binary format, I am left with the following option that is a step towards hardcoding.
    Create a subclass of JPanel and paint inside it. The full hardcode method would be to draw everything right here, ie the lines and the boxes.
    But since I need to listen to box selections using mouse, I was hoping to draw the boxes using JPanel/JLabel and override their paint() method.
    So is there a way to paint components(JLabel/JPanel and lines) into a painted component (JPanel)? Note, the container JPanel is not using any layout. everything is being drawn using paint method.

    You are probably going to want to create smaller objects that handle their own painting. For example... Create an extension of JComponent that handles painting a single node. Then create the JPanel to add those to. You can even go as far as writing your own LayoutManager to handle laying the Components out in your binary layout. This is really the most effective way to do it, especially if you want to be able to detect clicks and what not. You can just add MouseListener's to the individual components than.
    Hope this helps,
    Josh Castagno
    http://www.jdc-software.com

  • Wrapping ints to Strings

    Hi,
    This is what I believe to be a simple problem but has me a bit stumped. Maybe I'm not concentrating due to lack of sleep...
    Here's my problem I am trying to make a label display the current time. As you know labels use Strings and time is a number / int and herein lies the problem.
    I have the following code: -
    Date todayDate = new Date();
    int hours = todayDate.getHours();
    time = new JLabel((String)(hours));
    Gives this compile error: inconvertible types
    As I said this is probably a simple error.
    Many thanks,
    Martin

    change this
    time = new JLabel((String)(hours)); line to
    time = new JLabel( Integer.toString(hours) );
    hope it helps
    vinod

  • JLabel - calculating the number of lines in HTML wrapped text

    Hi folks,
    I've run into a problem. I have a JTable with row and column headers embedded within a JScrollPane. I have this component sized just how I like it. What I want to do is add a label above it serving as a title to the chart. I want this title to respect the width of the table - in other words, if the text within it is too long, I want it to wrap rather than to enlarge the size of the Table to fit it.
    I found that wrapping the title in "<html><center></center></html>" tags takes care of the wrapping. And furthermore I found code to handle the "dimension" of said label.
         * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4348815
        class WrappableJLabel extends JLabel {
               private final int preferredWidth;
               public WrappableJLabel(final int preferredWidth)
                  this.preferredWidth=preferredWidth;
               @Override
               public Dimension getPreferredSize()
                  Dimension superPreferred=super.getPreferredSize();
                  return new Dimension
                      (int) Math.min(preferredWidth,superPreferred.getWidth()),
                      (int) superPreferred.getHeight()
        }The problem is that the height does not get calculated correctly for the label. If I knew how many lines the JLabel's text took up, then I could multiply the height returned by the getPreferredSize() method by that number and get the correct size. I need to do all of this at compile time (so calling getHeight() on label doesn't help) so that I can size the JPanel holding both my table and my label to be of the correct size.
    Does anyone have any clues on how to do this?
    Thank you

    Maybe you need to calculate it yourself. The Java Developers Almanac 1.4 contains an general example:
    [http://www.exampledepot.com/egs/java.awt/TextDim.html|http://www.exampledepot.com/egs/java.awt/TextDim.html]
    You can obtain the font with the getFont() method on any component.

Maybe you are looking for