JList with JLabels

I'm a final year university student working on a major project for my degree and I'm really struggling with the GUI for the application. I'd really appreciate it if someone could help me out here.
I'm trying to make a JList of JLabels. I don't know whether this is possible but heres the jist of my code :
Vector listContents = new Vector();
JList list = new JList(listContents);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane listScrollPane = new JScrollPane(list);
ImageIcon icon = new ImageIcon(fyp.MainFrame.class.getResource("image.png"));
ImageIcon icon2 = new ImageIcon(fyp.MainFrame.class.getResource("image.png"));
JLabel lab = new JLabel("Test");
lab.setIcon(icon);
JLabel lab2 = new JLabel("Test 2");
lab2.setIcon(icon2);
listContents.add(lab);
listContents.add(lab2);If I use strings instead of labels it works fine. However, I want to have icons next to each string in the list.
Can anyone help with this? If this won't work at all, is there another way I should make a list of strings with an icon to the left of each entry?

I'm afraid I can't seem to use this information to
help me, the examples go into too much detail with
custom data models and whatever which really isn't
what I want to do.That may not be what you want to do, but it's what you have to do.
I simply want to display an icon next to the string of
the list entry.
I'd be really greatful if you guys could give me a
straightforward way of doing this - I'm terrible with
Swing and its pretty difficult for me to understand
these previous examples :(Those examples ARE the straightforward way of doing it. Go to the API documentation for JList and hit the page-down key three times. There's the example you need. It's got setIcon() in it, what else do you need?

Similar Messages

  • Resizing a JList with variable row heights, not updating the "picture"

    Firstly I would like to apologize for posting this Swing question here, but I was unable to find the Swing category, if someone could direct me to that I would be most grateful.
    Ok, so in abstract what I am trying to do is have a JList with resizable rows to act as a row header for a JTable (exactly like the row headers in OO Calc or MS Excel).
    What I have is a RowHeaderRenderer:
    public class RowHeaderRenderer extends JLabel implements ListCellRendererand it has a private member:
    private Vector<Integer>        _rowHeights            = new Vector<Integer>();which contains a list of all the variable row heights.
    Then there is my getListCellRendererComponent method:
        public Component getListCellRendererComponent(    JList         list,
                                                          Object        value,
                                                          int           index,
                                                          boolean       isSelected,
                                                          boolean       cellHasFocus)
            // Make sure the value is not null
            if(value == null)
                this.setText("");
            else
                this.setText(value.toString());
            // This is where height of the row is actually changed
            // This method is fed values from the _rowHeights vector
            this.setPreferredSize(new Dimension(this.getPreferredSize().width, _rowHeights.elementAt(index)));
            return this;
        }And then I have a row header:
    public class RowHeader extends JList implements TableModelListener, MouseListener, MouseMotionListenerand you may be interested in its constructor:
        public RowHeader(JTable table)
            _table = table;
            _rowHeaderRenderer = new RowHeaderRenderer(_table);
            this.setFixedCellWidth                        (50);
            this.setCellRenderer                        (_rowHeaderRenderer);
            // TODO: grab this value from the parent view table
            JScrollPane panel = new JScrollPane();
            this.setBackground(panel.getBackground());
            this.addMouseMotionListener                    (this);
            this.addMouseListener                        (this);
            this.setModel                                (new DefaultListModel());
            table.getModel().addTableModelListener        (this);
            this.tableChanged                            (new TableModelEvent(_table.getModel()));
        }and as you can see from my mouse dragged event:
        public void mouseDragged(MouseEvent e)
            if(_resizing == true)
                int resizingRowHeight = _rowHeaderRenderer.getRowHeight(_resizingRow);
                _rowHeaderRenderer.setRowHeight(_resizingRow, resizingRowHeight + (e.getPoint().y - _cursorPreviousY));
                _cursorPreviousY = e.getPoint().y;  
        }all I am doing is passing the rowHeaderRenderer the values the currently resizing row should be, which works fine. The values are being changed and are accurate.
    The issue I am having is that while this dragging is going on the row does not appear to be resizing. In other words the "picture" of the row remains unchanged even though I change the values in the renderer. I tried calling:
    this.validate();and
    this.repaint();at the end of that mousedDragged method, but to no avail, neither of them worked.
    Again, I verified that I am passing the correct data in the RowHeaderRenderer.
    So, anyone have any ideas how I should get the image of the RowHeader (JList) to update after calling my MouseDragged event?
    Thank you for your time,
    Brandon

    I was able to fix this some time ago. Here is the solution:
         public void mouseDragged(MouseEvent e)
              if(_resizing == true)
                   int newHeight = _previousHeight + (e.getPoint().y - _cursorPreviousY);
                   if(newHeight < _minRowHeight)
                        newHeight = _minRowHeight;
                   _rowHeaderRenderer.setRowHeight(_resizingRow, newHeight);
                   _table.setRowHeight(_resizingRow, newHeight);
              this.updateUI();
         }

  • Jlist with database?

    I have to get a few members out of a database and put them in a list.
    Then the admin can select the member he wants and alter his information.
    Now i was thinking of putting those members into a Jlist but I have a few problems with that.
    I want it in the list like this
    Membernumber1 membername1 memberadres1 .....
    Membernumber2 membername2 memberadres2 .....
    this gives me a problem, since i will know wich listindex is selected but i won't know what's the membernumber of the one that's selected so I won't really be able to change it in the database. Also not every name is the same length so the information in the list will look scrambled since \t tabs seem not to be working in listmodels.
    Is a list the right choice here, do I have to choose something different or can I solve these problems in some way.
    Tnx in advance.

    All you need to do is to store the data retrieved in a temporary object (say DbData) and this can give you the data for each member.
    Then create your own renderer for you JList that takes your object and uses a JPanel with JLabels to display your data. Alternatively, the DbData object can be the JPanel itself and this can passed directly to the JList renderer.
    eg
    class DbData extends JPanel {
       JLabel number, name;
      public DbData(String number, String name) {
         super();
         setDbData(number, name);
    public void setDbData(String number, String name) {
        // create and initialize JLabels with text
    public String[] getDbData() {
        // return number and name as string[]
    class DbDataRenderer extends DefaultListCellRenderer {
       public Component getListCellRendererComponent(JList list, Ojbect value, int index,
                           boolean isSelected, boolean hasFocus) {
            if(value instanceof DbData) {
                 return (DbData)value;
            return this;
    }However, if the data your retrieving to display is more than three items, then it might be better to use a JTable to display the items
    ICE

  • JList with aligned pictures

    What would be the best way to make a JList with a picture for each item?
    I have all the pictures loaded as ImageIcons btw.

    Write a custom list renderer, see http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/ListCellRenderer.html
    Then, to get the text aligned, you'll need to use the setIconTextGap method of JLabel. If the maximum icon width is 16 and your current icon is 13 pixels wide, then just set the icon-text-gab to 3.
    Something like this:
    import java.awt.*;
    import javax.swing.*;
    public class Dummy
         public static void main(String [] args)
              JList list = new JList(new Object[]{
                   new JLabel("small", new ImageIcon("d:/java/resources/java logo 16x16.png"), JLabel.LEFT),
                   new JLabel("large", new ImageIcon("d:/java/resources/java logo 32x32.png"), JLabel.LEFT)
              list.setCellRenderer(new MyCellRenderer());
              JFrame f = new JFrame();
              f.getContentPane().add(list);
              f.setSize(400,400);
              f.setVisible(true);
         static class MyCellRenderer extends JLabel implements ListCellRenderer
              public MyCellRenderer()
                   setOpaque(true);
              public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   JLabel label = (JLabel)value;
                   setText(label.getText());
                   setIconTextGap(4 + 32 - label.getIcon().getIconWidth());
                   setIcon(label.getIcon());
                   setBackground(isSelected ? Color.red : Color.white);
                   setForeground(isSelected ? Color.white : Color.black);
                   return this;

  • JList with Checkboxes

    For my application, I require a JList with each row containing a text label, and two check boxes which can be checked or unchecked in the list. I have written the code below to render list elements in this way, however the checkboxes cannot be checked in the list. Is there something else that I have to do to enable this?
    Code:
    public class NodeListCellRenderer implements ListCellRenderer {
          * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList,
          *      java.lang.Object, int, boolean, boolean)
         public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                   boolean cellHasFocus) {
              //Convert Value to node
              final Node n=(Node)value;
              //Create JPanel object to hold list element
              JPanel listElement=new JPanel();
              listElement.setLayout(new GridLayout(1,3));
              //Create Label to hold node name
              JLabel nodeName=new JLabel(n.toString());
              //Create checkbox to control trace
              final JCheckBox traceBox=new JCheckBox("Trace",n.isTraceEnabled());
              //Add Event Listener
              traceBox.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        n.setTrace(traceBox.isSelected());
              //Create Checkbox to control
              final JCheckBox failedBox=new JCheckBox("Failed",n.hasFailed());
              //Add Event Listener
              failedBox.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        n.setFailed(failedBox.isSelected());
              //Colour All Components Grey if Selected
              if (isSelected) {
                   nodeName.setBackground(Color.LIGHT_GRAY);
                   failedBox.setBackground(Color.LIGHT_GRAY);
                   traceBox.setBackground(Color.LIGHT_GRAY);
                   listElement.setBackground(Color.LIGHT_GRAY);
              //Build List Element
              listElement.add(nodeName);
              listElement.add(traceBox);
              listElement.add(failedBox);
              return listElement;
    }

    Thanks for the pointer to that. I have created a mouse listener for my list, which in a very crude way is able to set the checkbox values on a list click, by changing the underlying objects that are stored in the list.
    The problem that I'm having now is that if I click a checkbox in the currently selected list element, the value in the underlying object is set immediately, but the Checkbox does not update until i select another element in the list.
    This seems to indicate that the getListCellRendererComponent method is not called when you click on the currently selected list element. Is there any way round this?
    Here's my current mouse listener code:
    list.addMouseListener(new MouseAdapter() {
                   public void mousePressed(MouseEvent e) {
                        //get index of element clicked
                        int index=list.locationToIndex(e.getPoint());
                        //Get Element at Index
                        Node n=(Node)list.getModel().getElementAt(index);
                        /*Work out X position, if 33-66% of width, "trace" checkbox clicked
                        otherwise if >66% of width, "failed" checkbox clicked*/
                        if (e.getX()>(list.getWidth()*0.33) && (e.getX()<list.getWidth()*0.66)) {
                             n.setTrace(!n.isTraceEnabled());
                             list.revalidate();
                        } else if (e.getX()>(list.getWidth()*0.33)) {
                             n.setFailed(!n.hasFailed());
                             list.revalidate();
              });

  • JList with ImageIcon

    Hello,
    Can I have JList with an ImageIcon beside it?e.g
    "imageicon" "sometext"
    code snippet would be helpful.
    Thanks

    Hello,
    little improvement-update, custom ListCellRenderer now checks whether object is a String only or a JLabel with an ImageImage. You can use it for both versions of JLists.
    import javax.swing.*;
    import java.awt.*;
    public class ImageTextList extends JFrame
         private static String[]text = new String[10];
         private static JLabel[]labels = new JLabel[text.length];
         private static ImageIcon[] icons = new ImageIcon[labels.length];
         static
              for(int i=0; i<text.length; i++)
                   text[i]   = "Images " + (i+1);
                   icons[i]  = new ImageIcon(     "../testproject/img/" + (i+1) + ".jpg");
                   labels[i] = new JLabel(text, icons[i], JLabel.CENTER);
         public static void main(String[] args)
              new ImageTextList();
         public ImageTextList()
              super("Image+Text in a JList");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //test with labels and text
              JList list = new JList(labels);
              list.setCellRenderer(new MyCellRenderer());
              getContentPane().add(new JScrollPane(list));
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         class MyCellRenderer extends JLabel implements ListCellRenderer
              private JLabel label = null;
              // This is the only method defined by ListCellRenderer.
              // We just reconfigure the JLabel each time we're called.
              public Component getListCellRendererComponent(
                   JList list,
                   Object value,
              // value to display
              int index, // cell index
              boolean isSelected, // is the cell selected
              boolean cellHasFocus) // the list and the cell have the focus
                   String s = value.toString();
                   ImageIcon icon = null;
                   //checks whether the source is a label or another object(String only)
                   if(value instanceof JLabel)
                   {System.out.println("label");
                        label = (JLabel)value;
                        icon = (ImageIcon)label.getIcon();
                        s = label.getText();
                   setText(s);
                   setIcon(icon);
                   if (isSelected)
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                   } else
                        setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   setEnabled(list.isEnabled());
                   setFont(list.getFont());
                   setOpaque(true);
                   return this;
    regards
    Tim

  • Populating JList with a single database column

    Hi all,
    I have the following code and i'm trying to popluate the JList with a particular colum from my MySQL Database..
    how do i go about doing it??
    Can some one please help
    import java.awt.*; import java.awt.event.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.*; public class RemoveD extends JDialog {     private JList list;     private JButton removeButton;     private JScrollPane scrollPane;     private Connection conn = null;     private Statement stat = null;         public RemoveD(Frame parent, boolean modal) {         super(parent, modal);         initComponents();     }     private void initComponents() {         scrollPane = new JScrollPane();         list = new JList();         removeButton = new JButton();         setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);         getContentPane().setLayout(new GridLayout(2, 0));         scrollPane.setViewportView(list);         getContentPane().add(scrollPane);         removeButton.setText("Remove");         removeButton.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent evt) {                 removeButtonActionPerformed(evt);             }         });         getContentPane().add(removeButton);         pack();         try {             Class.forName("com.mysql.jdbc.Driver");                    } catch (ClassNotFoundException ex) {             ex.printStackTrace();                    }         try {             String userID = "";             String psw = "";             String url;             url = "jdbc:mysql://localhost:3306/names";             conn = DriverManager.getConnection(url, userID, psw);             stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,                     ResultSet.CONCUR_READ_ONLY);             stat.close();             conn.close();         } catch (SQLException ex) {             ex.printStackTrace();         }     }     private void removeButtonActionPerformed(ActionEvent evt) {     }     public static void main(String args[]) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 RemoveD dialog = new RemoveD(new JFrame(), true);                 dialog.addWindowListener(new WindowAdapter() {                     public void windowClosing(WindowEvent e) {                         System.exit(0);                     }                 });                 dialog.setVisible(true);             }         });     } }

    I figured out how to do it

  • JTable/jlist with word wrapping cells?

    Hello all,
    I got a simple looking problem but i can't seem to find any working solution for it:
    A jtable or jlist with cells that wordwrap text (cells differ in height).
    I found many examples on groups.google and this forum but they all seem to suffer a 100% processor load when 2 or more cells differ in height.
    Can anyone point me to a working example?
    Kind regards,
    Twan

    Thanks! That's a real live saver.
    I had been looking for a solution for several days, strange google did not yet found the mentioned page, cause it contains usefull information.
    I've just implemented the multiline table and it works without any problems and most important without 100% cpu usage.
    The bucks are comming your way ;-)

  • Populatin a JList with elements from a DB (access here)

    last year i was able to populate a JList with data from a database
    however this year something doesnt work
    this is last year
    public String[] getOnderwerpen()
    System.out.println(theConnection==null?" connection null ":" connection niet null ");
    String []locaties = new String[30];
    ArrayList returnLijst;
    returnLijst = new ArrayList();
    ArrayList arraylist;
    arraylist = new ArrayList();
              String[] deLocaties = null;
    try{
    String onderwerpQuery = "SELECT OnderwerpID FROM Onderwerp order by OnderwerpID";
    Statement statement = theConnection.createStatement();
    System.out.println(statement==null?" statement null ":" statement niet null ");
    statement.execute(onderwerpQuery);
    ResultSet result = statement.getResultSet();
    System.out.println(result==null?" ResultSet null ":" ResultSet niet null ");
    int i = 0;
                   while(result.next())
              //          locaties[i] = result.getString("OnderwerpID");
    locaties[i] = result.getString("OnderwerpID");
                                            i++;
    deLocaties = new String;
              for (int j=0;j<deLocaties.length;j++)
                   deLocaties[j] = locaties[j];
              sorteerStringArray(deLocaties);
    }//end-try
    catch (Exception e) {
    e.printStackTrace();
    return deLocaties;
    & this is what i did this year
    public String[] getbedrijfNaam()
              String[] bedrijfsNamen = new String[Constanten.aantalBedrijven];
              String[] deBedrijfsNamen = null;
         System.out.println(theConnection==null?" connection null ":" connection niet null ");
         System.out.println("test this");
         try{
         String onderwerpQuery = "SELECT naam FROM organisatie";
         Statement statement = theConnection.createStatement();
         System.out.println(statement==null?" statement null ":" statement niet null ");
         statement.execute(onderwerpQuery);
         ResultSet result = statement.getResultSet();
         int i = 0;
                        while(result.next())
                             bedrijfsNamen[i] = result.getString();
                                                 i++;
                        deBedrijfsNamen = new String[i];
                   for (int j=0;j<deBedrijfsNamen.length;j++)
                        deBedrijfsNamen[j] = bedrijfsNamen[j];
                   sorteerStringArray(deBedrijfsNamen);
                   statement.close();
                   //theConnection.close();
         }//end-try
         catch (Exception e) {
         e.printStackTrace();
         return deBedrijfsNamen;
    is there something here thats not right
    or does this no longer work because of the changes made in 1.5

    last year i was able to populate a JList with data from a database
    however this year something doesnt work
    this is last year
    public String[] getOnderwerpen()
    System.out.println(theConnection==null?" connection null ":" connection niet null ");
    String []locaties = new String[30];
    ArrayList returnLijst;
    returnLijst = new ArrayList();
    ArrayList arraylist;
    arraylist = new ArrayList();
              String[] deLocaties = null;
    try{
    String onderwerpQuery = "SELECT OnderwerpID FROM Onderwerp order by OnderwerpID";
    Statement statement = theConnection.createStatement();
    System.out.println(statement==null?" statement null ":" statement niet null ");
    statement.execute(onderwerpQuery);
    ResultSet result = statement.getResultSet();
    System.out.println(result==null?" ResultSet null ":" ResultSet niet null ");
    int i = 0;
                   while(result.next())
              //          locaties[i] = result.getString("OnderwerpID");
    locaties[i] = result.getString("OnderwerpID");
                                            i++;
    deLocaties = new String;
              for (int j=0;j<deLocaties.length;j++)
                   deLocaties[j] = locaties[j];
              sorteerStringArray(deLocaties);
    }//end-try
    catch (Exception e) {
    e.printStackTrace();
    return deLocaties;
    & this is what i did this year
    public String[] getbedrijfNaam()
              String[] bedrijfsNamen = new String[Constanten.aantalBedrijven];
              String[] deBedrijfsNamen = null;
         System.out.println(theConnection==null?" connection null ":" connection niet null ");
         System.out.println("test this");
         try{
         String onderwerpQuery = "SELECT naam FROM organisatie";
         Statement statement = theConnection.createStatement();
         System.out.println(statement==null?" statement null ":" statement niet null ");
         statement.execute(onderwerpQuery);
         ResultSet result = statement.getResultSet();
         int i = 0;
                        while(result.next())
                             bedrijfsNamen[i] = result.getString();
                                                 i++;
                        deBedrijfsNamen = new String[i];
                   for (int j=0;j<deBedrijfsNamen.length;j++)
                        deBedrijfsNamen[j] = bedrijfsNamen[j];
                   sorteerStringArray(deBedrijfsNamen);
                   statement.close();
                   //theConnection.close();
         }//end-try
         catch (Exception e) {
         e.printStackTrace();
         return deBedrijfsNamen;
    is there something here thats not right
    or does this no longer work because of the changes made in 1.5

  • Synchronize JList with JScrollPane

    hi all,
    I want to automatically move the scroll in the JScrollPane when I change the selected position in the JList with setSelectedIndex, right now the list is correctly selected, but the scroll remains on the top, how could I move it to position the list to see the selected item?
    thanks!
    mykro

    JComponent has a scrollRectToVisible method you could use along with JList's getCellBounds method. Maybe register a ListSelectionListener with the list, then in valueChanged get the newly selected cell's bounds from getCellBounds and call scrollRectToVisible on the JList with the cell bounds.

  • Traversing JList with arrow keys

    I've got a small problem when i try to traverse a JList with the arrow keys. When I'm at the first index of the list and press the UP arrow, I want to select the last index of the list.
    switch (keyCode){
            case VK_UP:
                    if(list.isSelectedIndex(list.getFirstVisibleIndex()))
                        list.setSelectedIndex(list.getLastVisibleIndex());
                    break;
    }When I use this code, the program selects the second last index (not the last). How can I fix this problem?
    Any suggestions will be appreciated.

    I found this thread useful but ultimately solved this another way using key binds. Maybe someone will find this useful.
    public MyDialogConstructor() {
        bindKeys();
    private void bindKeys() {
              InputMap inputMap = getJList().getInputMap(JComponent.WHEN_FOCUSED);
              KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
              inputMap.put(key, "jlist:UP");
              getJList().getActionMap().put("jlist:UP", new AbstractAction() {
                   private static final long serialVersionUID = 1L;
                   public void actionPerformed(ActionEvent e) {
                        if (getJList().isSelectedIndex(getJList().getFirstVisibleIndex())) {
                             getJList().setSelectedIndex(getJList().getLastVisibleIndex());
                        } else {
                             getJList().setSelectedIndex(getJList().getSelectedIndex() - 1);
              key = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
              inputMap.put(key, "jlist:DOWN");
              getJList().getActionMap().put("jlist:DOWN", new AbstractAction() {
                   private static final long serialVersionUID = 1L;
                   public void actionPerformed(ActionEvent e) {
                        if (getJList().isSelectedIndex(getJList().getLastVisibleIndex())) {
                             getJList().setSelectedIndex(getJList().getFirstVisibleIndex());
                        } else {
                             getJList().setSelectedIndex(getJList().getSelectedIndex() + 1);
         }

  • Help with JLabels and JTextFields

    I'm experimenting with JLabels and JTextFields in a basic JFrame. What I am trying to accomplish (without success) is to align a JLabel above and centered on a JTextField. The tutorials are confusing me. Any help would be greatly appreciated. a Sample of code is ...
    JLabel  myTextLabel = new JLabel("Who's text Field?");
    JTextField myTextField = new JTextField("My Text Field");...after reading the tutorial I thought that I needed to assign L&F variables to the JLabel ... i.e.
    JLabel myTextLabel = new JLabel("Who's text field?:", JLabel.CENTER, JLabel.TOP); but this results in an error when compiling. (cannot find symbol), so I thought I need to assign the JLabel to the JTextField. i.e.
    myTextLabel.setLabelFor(myTextField);Then I get "identifier" expected. So now being completely confused I am here asking "How do I?" :)
    Thanks in advance!

    Most likely, you need to think a little more about using a layout manager to hlp you along the way. If memory serves, the default layout manager for a JPanel is FlowLayout and that will simply place the components you add to the panel one after another and allow each to adopt it's preferred size.
    One way to ensure that the two compoenets were sized equally, would be to use the GridLayout layout manager and create either one row with two columns, or two rows with one column on each. Then add the compoennets to each of the 'cells' so to speak and that should ensure that they are both the same size.
    As to making the text centered in each, both the JLabel and JtextField classes have amethod called setHorizontalAlignment(); it can be used to aligh the text as you require.
    Simply create an instance of the class;
    JLabel aLabel = new JLabel("Some Text");
    // Then set the alignment
    aLabel.setHorizontalAlignment(SwingConstants.CENTER);Or, do the whole operation i one step
    JLabel aLabel = new JLabel("Sone Text", SwingConstants.CENTER);and then add the componenet to the panel once you have set the layout manager.
    Remember that the label.textfield will have to be wide enought to make it obvious that the text is centered!

  • Help with JLabel

    Hello all. I am fairly new to Java and having a problem setting the text in a JLabel. I am trying to create a calculator program and when the user clicks a button I want that number to appear in a JLabel at the top. I used output.setText("7"); but when I compiled it said <identifier> expected. I will paste the full code below and would appreciate any help. Also, is there a getText function with JLabel, because I need to get what is currently in the output field and concatenate it with the number pressed.
    Thanks in advance for your help,
    Jeremy
    * Write a description of class calculator here.
    * @author (Jeremy Kruer)
    * @version (11/19/02)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class calculator extends JFrame
    private JButton one, two, three, four, five, six, seven, eight, nine, zero, dec, eq, plus, minus, mult, div;
    private JLabel output;
    private Container container;
    //set up GUI
    public calculator()
    //Create Title
    super("Calculator");
    //Set size and make visible
    setSize( 400, 400 );
    setVisible( true );
    container = getContentPane();
    container.setLayout( new FlowLayout() );
    //set up output
    output = new JLabel();
    container.add( output );
    //set up seven and register its event handler
    seven = new JButton( " 7 " );
    seven.addActionListener(
    //anonymouse inner class
    new ActionListener()
    //add a seven to the output diplay when clicked
    output.setText( "7" );
    }//end anonymouse inner class
    ); //end call to addActionListener
    container.add( seven );
    //set up eight
    eight = new JButton( " 8 " );
    container.add( eight );
    //set up nine
    nine = new JButton( " 9 " );
    container.add( nine );
    //set up div
    div = new JButton( " / " );
    container.add( div );
    //set up four
    four = new JButton( " 4 " );
    container.add( four );
    //set up five
    five = new JButton( " 5 " );
    container.add( five );
    //set up six
    six = new JButton( " 6 " );
    container.add( six );
    //set up mult
    mult = new JButton( " * " );
    container.add( mult );
    //set up one
    one = new JButton( " 1 " );
    container.add( one );
    //set up two
    two = new JButton( " 2 " );
    container.add( two );
    //set up three
    three = new JButton( " 3 " );
    container.add( three );
    //set up minus
    minus = new JButton( " - " );
    container.add( minus );
    //set up zero
    zero = new JButton( " 0 " );
    container.add( zero );
    //set up dec
    dec = new JButton( " . " );
    container.add( dec );
    //set up eq
    eq = new JButton( " = " );
    container.add( eq );
    //set up plus
    plus = new JButton( " +" );
    container.add( plus );
    //Set size and make visible
    setSize( 220, 250 );
    setVisible( true );
    //execute application
    public static void main( String args[] )
    calculator application = new calculator();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    I played with the lauout a bit and added the actionListener:
    you will see what you click on !!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class calcu extends JFrame implements ActionListener
         private JButton  one, two, three, four, five, six, seven, eight, nine, zero, dec, eq, plus, minus, mult, div;
         private JLabel   output;
    public calcu()
         super("Calculator");
         JPanel container = new JPanel();
         container.setLayout(new FlowLayout(FlowLayout.LEFT));
         output = new JLabel("");
         output.setBorder(new MatteBorder(2,2,2,2,Color.gray));
         output.setPreferredSize(new Dimension(1,26));
         getContentPane().setBackground(Color.white);
         getContentPane().add("North",output);
         getContentPane().add("Center",container);
    //set up seven and register its event handler
         seven = new JButton(" 7 ");
         container.add(seven);
         seven.addActionListener(this);
    //set up eight
         eight = new JButton(" 8 ");
         container.add(eight);
         eight.addActionListener(this);
    //set up nine
         nine = new JButton( " 9 " );
         container.add( nine );
         nine.addActionListener(this);
    //set up div
         div = new JButton( " / " );
         container.add( div );
         div.addActionListener(this);
    //set up four
         four = new JButton( " 4 " );
         container.add( four );
         four.addActionListener(this);
    //set up five
         five = new JButton( " 5 " );
         container.add( five );
         five.addActionListener(this);
    //set up six
         six = new JButton( " 6 " );
         container.add( six );
         six.addActionListener(this);
    //set up mult
         mult = new JButton( " * " );
         container.add( mult );
         mult.addActionListener(this);
    //set up one
         one = new JButton( " 1 " );
         container.add( one );
         one.addActionListener(this);
    //set up two
         two = new JButton( " 2 " );
         container.add( two );
         two.addActionListener(this);
    //set up three
         three = new JButton( " 3 " );
         container.add( three );
         three.addActionListener(this);
    //set up minus
         minus = new JButton( " - " );
         container.add( minus );
         minus.addActionListener(this);
    //set up zero
         zero = new JButton( " 0 " );
         container.add( zero );
         zero.addActionListener(this);
    //set up dec
         dec = new JButton( " .  " );
         container.add( dec );
         dec.addActionListener(this);
    //set up eq
         eq = new JButton( " = " );
         container.add( eq );
         eq.addActionListener(this);
    //set up plus
         plus = new JButton( " +" );
         container.add( plus );
         plus.addActionListener(this);
    //Set size and make visible
         setSize(220,250);
         setResizable(false);
         setVisible( true );
    public void actionPerformed(ActionEvent ae)
         JButton but = (JButton)ae.getSource();
         output.setText(but.getText());
    //execute application
    public static void main( String args[] )
         calcu application = new calcu();
         application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    } Noah

  • New lines with JLabel

    I am having problems getting my strings into new lines with jlabels. I know i can do it with <html>...<br>...</html> but the string in the label changes. What is the best way of getting the strings on to mulitaple lines without spliting up words.

    You can do whatever you want to the text area to make it look like a label:
    setBackground(...);
    setForeground(...);
    setBorder(...);
    setEditable(...);
    Its all there in the API.

  • Usinig pictures with jlabel and file browsing

    ok, i was just told how to use a picture with jlabel, but, how do i place it in the gui? how do i change the picture?
    what about error protection if the picture cant be found?
    still not sure about file browsing, how do i save the filename/directory to a string when i the user selects the file through the file browser?

    Hi,
    label.setIcon(new Icon("blabal.gif"));

Maybe you are looking for

  • Westell USB 802.11g adapter with an Imac?

    I just switched to a new DSL provider who sold me a wireless router and a USB adapter. They are both made by Westell. I have my laptop running wireless no problem as well as anohter machine runing ethernet fine. But I have an Imac running 10.3.2 that

  • Consignment fill-up - Output Printing Problem - Z customizing problem

    Dear Gurus, I have customized and copied the following 2 sales documents types: - OR - KB into ZSTA and ZKB When I create a Sales Order using VA01 and ZSTA, and chose 1 material + 1 service, the printed invoice clearly shows 2 items for each one of t

  • How to handle double click in a table control?

    Hi, Can any one let me how to handle double click event in a table control in dialog programming? here i need to navigate to another screen when user double click on the table contols (emp number column). thanks in advance, PrasadBabu.

  • TreeCellRendering problem in linux... works fine in windows

    Hi, Can somebody point out what I am doing wrong here? I have a JTree with to which I add DefaultMutableTreeNodes nodes as below: DefaultMutableTreeNode dnNode = new DefaultMutableTreeNode(new NodeRecord()); In order to customize the look of the JTre

  • Picture was yellow when using flash - iPhone 5

    Hi , Since a while ago, all pictures taken by my iPhone 5 with Flash on are yellow and nothing in it. But pictures taken with natural light are OK. I feel this is some issues in the hardware in my phone but am not sure about it. Note, the IOS on my p