Replacing a JLabel

Hello
I�ve got a problem with replacing a JLabel.
I know it�s unusual to replace a JLabel, but I�ve got a class interpreting internal Error-Codes into �userfriendly messages�.
And not only the Text is changing but also the background- and foreground-color. Sometimes even the font style.
Short: it is like a Renderer for a single JLabel.
My Class GuiController (that keeps the instance of my GUI) sets the new JLabel at the predefined place in my GUI.
I don�t see it change but when I ask the Text of the Label (myLabel.getText( );) I get the new Text.
There must be something simple I have not found yet. Or is it such a big no-no that I should solve it in a totally different way?
Maybe it would be better to actually write a JLabel-Renderer (?)
(But I would need 5 of them, because there are 5 Labels with different intepretations and Layouts...)
here is a short demonstration program:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class ReplaceJLabelTest {
  public ReplaceJLabelTest(){
    final TestGui l_oGui = new TestGui();
    try {
      Thread.sleep(1000);
    } catch (Exception e) {
      e.printStackTrace();
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        l_oGui.setLabel(new JLabel("it is the new label"));
        l_oGui.getContentPane().validate();
        l_oGui.repaint();
        System.out.println(l_oGui.getLabel().getText()); // <-- returns "it is the new label" but I still see the old text.
  public static void main(String[] args) {
    new ReplaceJLabelTest();
  private class TestGui extends JFrame {
    JFrame m_oFrame = new JFrame();
    JLabel m_oLabel = new JLabel("this is the old label");
    public TestGui() {
      m_oFrame.getContentPane().add(m_oLabel);
      m_oFrame.pack();
      m_oFrame.setVisible(true);
    public void setLabel(JLabel p_strLabel) {
      m_oLabel = p_strLabel;
    public JLabel getLabel() {
      return m_oLabel;
}I tried solutions given in older topics.
Like http://forum.java.sun.com/thread.jspa?forumID=257&threadID=415307
or
l_oGui.pack();
l_oGui.invalidate();
l_oGui.repaint();
l_oGui.getLabel().repaint();It did not really work for me...
Thanks for taking the time to read this :)
Greetings
Sophia

You can use the setUI function for installing a new UI.
You can create a custom UI class by extending BasicLabelUI:
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/basic/BasicLabelUI.html
Override protected void installDefaults(JLabel c) and set the foreground, background and font for c.

Similar Messages

  • Replace JLabel with a string in JTextPane

    Hi all,
    anyone knows if there is a way to replace a JLabel with a string in a JTextPane?
    The string is contained within the label.
    My problem is that when the user is viewing the textpane, he sees a mixed text with strings and labels...but when i save the text, i want to convert the labels in their respective IDs.
    Tnx!

    First you say
    "I need to replace JLabel with a JButton"
    Then you say
    "but i have to change the label of the button as it is being clicked."
    So what are you trying to do, just change the text of the button or replace a JLabel with a JButton. We can't give you any help unless you ask a clear question.

  • 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

  • JLabel + Animated GIF: replacing the image

    Hi, folks.
    I've run into what looks like an interesting glitch, not necessarily functionality-wise but purely cosmetic.
    I have a JLabel which needs to be switched between a static image and an animated image at different times of execution. I'm doing this more or less like this:
        private JLabel label = new JLabel();
        private ImageIcon inactiveIcon;
        private ImageIcon activeIcon;
        public MyClass()
            inactiveIcon = Utils.loadIcon(...);
            activeIcon = Utils.loadIcon(...);
            setActive(false);
        public void setActive(boolean active)
            label.setIcon(active ? activeIcon : inactiveIcon);
        }It starts up fine and shows the inactive image, which is not animated.
    However, calling setActive(true) seems to cause a flash of grey before showing any animation. The interesting thing is at this point, the image should be completely loaded, so nothing should be blank for any period of time. The other interesting thing is that calling setActive(false) does not cause the flash of grey.
    I've checked the image to make sure all the frames are present and that none are blank.
    I've tried doing this a number of different ways, by Icon.setImage(Image), also by using two labels and setVisible(boolean).
    Has anyone else seen this before? The particular thing which worries me is there isn't a grey flash going the other way. Otherwise I wouldn't think a workaround existed. :-)

    Update. I changed the code to this:
    label = new JLabel() {
    public void update(Graphics g) {
    paint(g);
    public void paint(Graphics g) {
    paintComponent(g);
    protected void paintComponent(Graphics g) {
    ImageIcon icon = (ImageIcon) getIcon();
    icon.paintIcon(this, g, 0, 0);
    };It still greys out. :-/
    I tried label.setUI(new LabelUI() { ... }) with a
    custom paint method also, and it didn't draw anything
    at all, for either label.I'm not sure if you accounted for this but the paint method in the UI is different then the 'public void paintComponent(Graphics g)' method and paint (Graphics g) method in components. The method is 'public void paint(Graphics g, JComponent c)'. Overwriting 'public void paint (Graphics g)' in a UI, is like defining a new method alltogether.
    Did you also make sure to avoid calling 'super.paintComponent()' when overwriting your 'paintComponent(...)' methods? If you did call it, you aren't preventing drawing of previous shapes. This worked for me when I had to do something similar.
    You could also try to draw your icon in your UI, if you haven't done so already.
    Regards,
    Devyn

  • How can i replace some string  in a JTextaArea/JTex at current time!

    Hey guys, this problem is driving me crazy... i want to do a keyboard event.. like the emoticons in msn,
    so, i want that when i type /land ("latex comand"), a character appears replacing the command in the JTextArea. I did it, but when i type
    /happy, the character doesn�t appear! Just when i type space in keyboard...:/
    Can anybody help me?
    public class TelaParametro extends JDialog {
         private GerenciadorExterno gerInterface;
         private TelaLeis telaLeis;
         private int parametro;
         private Argument argumento;
         private String codigo;
         private String path = "images/";
         private TecladoVirtual tecl;
         private boolean DigitandoLatex;
         private String latex;
         /* atributo que serve para dizer se o usuario apertou no Ok ou no Cancel */
         private int flagModal;
           JPanel panel1 = new JPanel();
           JButton btnOK = new JButton();
           JButton btnCancel = new JButton();
           JTextArea tfEspec = new JTextArea();
           JScrollPane rolagem;
           JLabel labelEntrada = new JLabel();
           JButton btnDigitacao = new JButton();
           JButton btnTecladoVirtual = new JButton();
         JPanel panel2 = new JPanel();
         BorderLayout borderLayout1 = new BorderLayout();
         BorderLayout borderLayout2 = new BorderLayout();
         JPanel panel3 = new JPanel();
         GridLayout gridLayout1 = new GridLayout();
         JPanel panel4 = new JPanel();
         BorderLayout borderLayout3 = new BorderLayout();
         JPanel panel5 = new JPanel();
         JPanel panel6 = new JPanel();
         JPanel panel7 = new JPanel();
         JPanel panel8 = new JPanel();
    public TelaParametro(TelaLeis telaLeis, GerenciadorExterno gerInterface) {
              super(telaLeis);
              try  {
                   this.telaLeis = telaLeis;
                   this.gerInterface = gerInterface;
                   this.tecl = new TecladoVirtual(this);
                   flagModal = 0;
                   DigitandoLatex = false;
                   jbInit();
              catch (Exception e) {
                     e.printStackTrace();
    private void jbInit() throws Exception {
                 this.setLocation(240,220);
    //             this.setLocation((gerInterface.getTamanhoHorizontal()/2) - 160,(gerInterface.getTamanhoVertical()/2) - 80);
                 this.setSize(320, 160);
                 this.setTitle("Parametro");
                 tfEspec.setFont(new Font ("CZT", Font.PLAIN, 12));
                 tfEspec.setText("");
              rolagem = new JScrollPane(tfEspec);
              this.setModal( true );
              tfEspec.addKeyListener(new java.awt.event.KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        tfEspec_keyPressed(e);
              btnOK.setForeground(Color.green);
              btnOK.setFont(new Font("Dialog", 1, 12));
              btnOK.setLabel(this.retornarMensagem("COD0072"));
              btnOK.addActionListener(new java.awt.event.ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                        btnOK_actionPerformed(e);
              btnDigitacao.setFont(new Font("Dialog", 1, 12));
              btnDigitacao.setText("D");
              btnDigitacao.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   btnTecladoVirtual_actionPerformed(e);
              ImageIcon teclicon = new ImageIcon(path + "teclado.gif");
              btnTecladoVirtual.setIcon(teclicon);
              btnTecladoVirtual.setToolTipText("TecladoVirtual");
              btnTecladoVirtual.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   btnTecladoVirtual_actionPerformed(e);
              btnCancel.setForeground(Color.red);
              btnCancel.setFont(new Font("Dialog", 1, 12));
              btnCancel.setLabel(this.retornarMensagem("COD0078"));
              btnCancel.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(ActionEvent e) {
                        btnCancel_actionPerformed(e);
              labelEntrada.setText("   Entre com tal parametro:");
              panel1.setLayout(borderLayout1);
              panel2.setLayout(borderLayout2);
              panel3.setLayout(gridLayout1);
              panel4.setLayout(borderLayout3);
              this.getContentPane().add(panel1, BorderLayout.CENTER);
              panel1.add(panel2, BorderLayout.CENTER);
              panel2.add(rolagem,  BorderLayout.CENTER);
              panel2.add(panel5, BorderLayout.WEST);
              panel2.add(panel6,  BorderLayout.SOUTH);
              panel2.add(panel7,  BorderLayout.EAST);
              panel2.add(panel8, BorderLayout.NORTH);
              panel1.add(panel3,  BorderLayout.SOUTH);
              panel3.add(btnOK, null);
              panel3.add(btnCancel, null);
              panel1.add(panel4, BorderLayout.NORTH);
              panel4.add(labelEntrada,  BorderLayout.CENTER);
              panel4.add(btnTecladoVirtual,  BorderLayout.EAST);
    private void tfEspec_keyPressed(KeyEvent e){
             String str = tfEspec.getText() ;
             System.out.println("char "  + e.getKeyChar());
             System.out.println("texto " + str);
             str = str.replace("\\land", ZString.AND);
             //System.out.println("strReplaced " + str);
             tfEspec.setText(str);
             tfEspec.repaint();
    }

    But there is no method "addDocumentListener" for JTextArea =/ [url http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html]How to Write a Document Listener.

  • Inserting an ImageIcon into a JLabel

    Hello.
    I'm trying to insert an ImageIcon into a JLabel
    component which includes text.
    I want this JLabel to be a cell in a JTable,
    so i'm trying to add the ImageIcon inside the method
    public Component getTableCellRendererComponent
    (JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column)
    of class
    public class ClientCellRenderer extends
    DefaultTableCellRenderer
    the code regarding the ImageIcon is:
    JLabel label = new JLabel((String)value, icon, CENTER);
    return label;
    this code resides inside getTableCellRendererComponent.
    for some reason i don't see the ImageIcon in the JTable,
    although i see the text (which is (String)value).
    i hope someone could help me.
    thanks,
    Topa.

    Assuming that your image icon is being loaded correctly, the following will solve your problem.
    Replace these lines:
    JLabel label = new JLabel((String)value, icon,
    CENTER);
    return label;with these:
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    setIcon(icon);
    return this;
    This works because DefaultTableCellRenderer extends JLabel, and returns itself as the renderer component.

  • How to define the position of a JLabel in a JPanel?

    Could anybody help me for my problem ?
    - I added two JLabel into a JPanle using the folowwing code, but the two labels are displayed over each other. JLabel.setBounds() doesn't help.
    questionL1 = new JLabel("question1");
    questionL1.setBounds(50, 200, 700, 50);
    questionL2 = new JLabel("question2");
    questionL2.setBounds(50, 250, 700, 50);
    graphicPanel = new JPanel();
    graphicPanel.setPreferredSize(new Dimension(850, 450));
    graphicPanel.setLayout(new BorderLayout());
    graphicPanel.setBackground(Color.white);
    graphicPanel.add(questionL1);
    graphicPanel.add(questionL2);
    Thanks in advance

    By default components get added to the 'center' of a BorderLayout, so questionL2 replaces questionL1 in the panel.
    Here is a link to the Swing tutorial on "Using Layout Managers":
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

  • Replacing a JPanel

    Hi
    In one of the dialogs of my application, I have a JPanel that describes some properties of one of my objects.
    The object's properties described by my JPanel can be "empty' (when I have no properties to describe, I put in the JPanel a JLabel saying "No properties inserted" and a JButton "insert properties) or a Box with the properties I want (A vertical Box filled with horizontal Box, the first horizontal Box are JLabels (name, value, limit...) and the second Box are "JTextField"s).
    When I have no properties and I press the button "insert properties", I replace the JPanel with a new JPanel with the new Layout.
    The problem is that, when I have the button pressed to replace the JPanel, my new JPanel is not painted correctly (everything seems to be painted in the same place, component over component). I've already tested only the new JPanel on a JFrame and it is fine, the problem happens only when I try to replace the panels.
    So, can you help me solve my problem?
    thanks in advance

    If you don't use a card layout, you need to either remove the old panel or make it invisible. Card layout of should work fine. Are you sure you're making the switch in the Event Dispatch Thread?

  • JLabel as cell of JTable

    Hi All,
    I am using JLabel as a cell of a JTable by overriding getTableCellRendererComponent method of the renderer.But I am not able to select/focus on any of the cell by clicking at cells.However If I use any other componenet like JTextArea, I can select any cell I want.
    I have to use JLabel because i want to put multiple color and fonts in a single cell.I dont't want to use JTextPane because it takes more memory as well as It has wraping problem
    Any help would be greatly appreciated

    It's not a good idea to create a NEW Component each and every time getXXXCellRenderer() is called. Object creation is VERY expensive!!!
    Remember, this Component is merely renderered (e.g. painted, or "rubber-stamped") into the Graphics Context of the JTable, after appropriate sizing to fit the cell, of course. So the SAME component can be used to render each and every cell, each and every time each cell needs to be rendered. (Unless different Component classes are used to render different cells, but still, one of each of these Components should be created in the Constructor, not each time a cell is rendered.)
    I have reworked your code to make it much more efficient, and to make it more readable:
    public class MyTableCellRenderer
        implements TableCellRenderer
        JLabel label = new JLabel();
        public MyTableCellRenderer()
            super();
            this.label.setOpaque(true);
        public Component getTableCellRendererComponent( JTable  table,
                                                        Object  value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int     row,
                                                        int     column )
            String st=null;
            st="<HTML><B><FONT Color=Red>" + value.toString() 
               + "</FONT></B></HTML>";
            this.label.setText(st);
            if (isSelected) {
                this.label.setBackground( table.getSelectionBackground());
            } else {
                this.label.setBackground(Color.yellow);
            return this.label;
    }You may find that using HTML as the text of JLabel is much too expensive, especially with a large table. I tried it once, with a table of only moderate size, and gave up. It's much faster to set the font, foreground color, etc., on the JLabel itself instead.
    I was trying to use HTML simply to get HTML Character Entities (like &amp;) to display correctly, and it just didn't work. I wrote my own class to parse strings for HTML Character Entities, replacing them with appropriate Unicode characters, and it worked much better.
    ---Mark

  • ImageIcons in a JLabel get their top-most row of pixels cut off

    Hello. I've added a "Loading..." screen to my application that basically consists of a JWindow with a background image. However, I've noticed something odd when adding an ImageIcon to a JLabel. It seems that any image I add gets its top row of pixels cut off. The small program below illustrates this.
    import javax.swing.*;
    import java.awt.*;
    public class JLabelTest {
       static final String WINDOW_IMAGE = "my_image.jpg";
        * Create and display the loading screen
       private static void displayLoadingScreen()
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                JWindow winLoadingScreen = new JWindow();
                ImageIcon loadingImg = new ImageIcon(WINDOW_IMAGE);
                JLabel lblImage = new JLabel(loadingImg);
                winLoadingScreen.getContentPane().add(lblImage);
                winLoadingScreen.pack();
                System.out.println("label dimensions:      " + lblImage.getSize().width + " x " + lblImage.getSize().height);
                System.out.println("image icon dimensions: " + loadingImg.getIconWidth() + " x " + loadingImg.getIconHeight());
                winLoadingScreen.setLocation(100, 100);
                winLoadingScreen.setVisible(true);
        * Entry point
        * @param args
       public static void main(String[] args)
          SwingUtilities.invokeLater(new Runnable() {
             public void run()
                displayLoadingScreen();
    }(Obviously, replace my_image.jpg with something else if you'd like to run the code on your own machine.)
    When I run the program with, say, an 800 x 600 resolution image, the output I get is:
    label dimensions:      800 x 599
    image icon dimensions: 800 x 600As you can see, the image gets "shortened" by one pixel when added to the JLabel. If you look at the image that is displayed, you can see that it's the top row that gets cut off. I've tried changing the layout of the JWindow that the JLabel is being added to, but that didn't change anything. I've tried using a number of different images in varying formats, and the same thing happens to all of them.
    Any ideas? Thanks in advance.

    Have you tried to set label's preferredSize manually?
    What happens when you add empty border t the label with some insets?
    regards,
    Stas

  • Button panel replaced by JTable result set

    Hi guys. Here's the problem. Below is my current working code.
    When run - a JOption pane opens, into which I type the database location (using /'s instead of \'s as it is a String input).
    The main UI opens. That indicates that the connection was successful. The UI consists of a JPanel (north) containg a number of buttons. Below that is a space for a JTable. Each button represents a diiferent query to the database and a different result set is displayed in the JTable beneath the buttons depending on which button is clicked.
    This all works fine.
    However I would like to now modify the code so that when the program runs the user is faced with the JPanel containing the Buttons only. And when a button is clicked the current panel is replaced with a full JTable containing the result set.
    So basically I want a JPanel with a number of buttons. Once clicked the result set JTable is displayed fully in the JFrame possibly with another button to bring the user back to the initial button panel.
    import java.io.*;
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.table.*;
    public class Test12 extends JFrame {
    // java.sql types needed for database processing
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    private ResultSetMetaData rsMetaData;
    // javax.swing types needed for GUI
    private JTable table;
    private JTextArea inputQuery;
    public Test12()
    super( "Johnny Project" );
    // The URL specifying the Books database to which
    // this program connects using JDBC to connect to a
    // Microsoft ODBC database.
    // Load the driver to allow connection to the database
    try {
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         String myFilename = JOptionPane.showInputDialog("Enter Database Location");
                   String myDatabase = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
                   myDatabase+= myFilename.trim() + ";DriverID=22;READONLY=true}";
                   connection = DriverManager.getConnection(myDatabase,"","");
    catch ( ClassNotFoundException cnfex ) {
    System.err.println(
    "Failed to load JDBC/ODBC driver." );
    cnfex.printStackTrace();
    System.exit( 1 ); // terminate program
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to connect" );
    sqlex.printStackTrace();
    System.exit( 1 ); // terminate program
              //If connection succeeds - build GUI
              buildMenu();
              buildGUI();
              setSize(800, 800);
              show();
    private void getTable(String recievedQuery)
    try {
    String query = recievedQuery;
    statement = connection.createStatement();
    resultSet = statement.executeQuery(query);
    displayResultSet(resultSet);
    catch (SQLException sqlex) {
    sqlex.printStackTrace();
    private void displayResultSet(ResultSet rs)
    throws SQLException
    // position to first record
    boolean moreRecords = rs.next();
    // If there are no records, display a message
    if (! moreRecords) {
    JOptionPane.showMessageDialog( this,
    "ResultSet contained no records" );
    setTitle( "No records to display" );
    return;
    Vector columnHeads = new Vector();
    Vector rows = new Vector();
    try {
    // get column heads
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    // get row data
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
    JScrollPane scroller = new JScrollPane( table );
    Container c = getContentPane();
    c.remove( 1 );
    c.add( scroller, BorderLayout.CENTER );
    c.validate();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    private Vector getNextRow( ResultSet rs, ResultSetMetaData rsmd )
    throws SQLException
    Vector currentRow = new Vector();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    switch( rsmd.getColumnType( i ) ) {
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    currentRow.addElement( rs.getString( i ) );
    break;
    case Types.INTEGER:
    currentRow.addElement(
    new Long( rs.getLong( i ) ) );
    break;
    default:
    System.out.println( "Type was: " +
    rsmd.getColumnTypeName( i ) );
    return currentRow;
    public void shutDown()
    try {
    connection.close();
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to disconnect" );
    sqlex.printStackTrace();
    private void buildGUI()
              inputQuery = new JTextArea(4, 30);
              Icon people = new ImageIcon("people.gif");
              JButton searchAll = new JButton("All", people);
              searchAll.setToolTipText("Search All People");
              searchAll.setBorder(null);
              searchAll.addActionListener(
         new ActionListener() {
    public void actionPerformed(ActionEvent e)
              String searchAllString = new String("Select * from 0001_per_year");
         getTable(searchAllString);
              JButton searchPathway = new JButton("Pathway", people);
              searchPathway.setToolTipText("Search Students by Pathway");     
              searchPathway.setBorder(null);
              searchPathway.addActionListener(
         new ActionListener() {
    public void actionPerformed(ActionEvent e)
              String searchPathwayString = new String("Select Student_Number, Pathway from 0001_per_year");
         getTable(searchPathwayString);
              JButton searchPeriod = new JButton("Study", people);
              searchPeriod.setToolTipText("Search Students by Period");     
              searchPeriod.setBorder(null);
              searchPeriod.addActionListener(
         new ActionListener() {
    public void actionPerformed(ActionEvent e)
              String searchPeriodString = new String("Select Student_Number, Period_of_Study from 0001_per_year");
         getTable(searchPeriodString);
              JButton searchAttendance = new JButton("Attendance", people);
              searchAttendance.setToolTipText("Search Students by Attendance");     
              searchAttendance.setBorder(null);
              searchAttendance.addActionListener(
         new ActionListener() {
    public void actionPerformed(ActionEvent e)
              String searchAttendanceString = new String("Select Student_Number, Attendance_Status from 0001_per_year");
         getTable(searchAttendanceString);
              JLabel j1 = new JLabel ();     
              JLabel j2 = new JLabel ();
              JLabel j3 = new JLabel ();
              JLabel j4 = new JLabel ();
              JLabel j5 = new JLabel ();
              JLabel j6 = new JLabel ();
              JLabel j7 = new JLabel ();
              JLabel j8 = new JLabel ();
              JLabel j9 = new JLabel ();
              JLabel j10 = new JLabel ();
              JLabel j11 =new JLabel ();
              JLabel j12 = new JLabel ();
              GridLayout grid;
              grid = new GridLayout(4,4);
                   JPanel topPanel = new JPanel();
              topPanel.setLayout(grid);
              topPanel.add(j1);
              topPanel.add(j2);
              topPanel.add(j3);
              topPanel.add(j4);
              topPanel.add(j5);
              topPanel.add(searchAll);
              topPanel.add(searchPathway);
              topPanel.add(j6);
              topPanel.add(j7);
                   topPanel.add(searchPeriod);
                   topPanel.add(searchAttendance);
                   topPanel.add(j8);
                   topPanel.add(j9);
                   topPanel.add(j10);
                   topPanel.add(j11);
                   topPanel.add(j12);
                   table = new JTable();
              Container c = getContentPane();
              c.setLayout( new BorderLayout() );
              c.add( topPanel, BorderLayout.NORTH );
              c.add( table, BorderLayout.CENTER );
              show();
    private void buildMenu()
    JMenuBar myMenuBar = new JMenuBar();
    JMenu myFileMenu = new JMenu("File");
    JMenuItem myExitItem = new JMenuItem("Exit");
    //Exit item closes the application
    myExitItem.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    System.exit(0);
    myFileMenu.add(myExitItem);
    myMenuBar.add(myFileMenu);
    setJMenuBar(myMenuBar);
    public static void main( String args[] )
    final Test12 app = new Test12();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    app.shutDown();
    System.exit( 0 );

    Your welcome. I don't really compete for Duke's, but I'm glad the issue is resolved.
    - Saish
    "My karma ran over your dogma." - Anon

  • Re: Problems loading an ImageIcon into a JLabel in a JApplet

    This applet refuses to load images whose names it reads from a file in the makeList() method below. It will read the same image in if I hardcode in the file name
    Well, have you checked to see that what is being read is the same as what you were hardcoding?

    Assuming that your image icon is being loaded correctly, the following will solve your problem.
    Replace these lines:
    JLabel label = new JLabel((String)value, icon,
    CENTER);
    return label;with these:
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    setIcon(icon);
    return this;
    This works because DefaultTableCellRenderer extends JLabel, and returns itself as the renderer component.

  • JLable replace "\r\n" with a box, how do i remove box

    Hi I have a string where it has multiple lines sepearted by "\r\n" but when I print it in JLable it replaces it with little box at the end of each line. How do I remove that box.
    I am printing in a JLabel because that page which ha JLabels needs to printed as formal report on printer.
    If I use JTextArea it has border apeared around those lines which I dont want in printed report.
    Please HELP.
    THANKS.
    java lover

    and for that printer thing using JLabel is not a answer (i mean standard way)
    what u can do is use the graphic object from textPane and format it according to the way u want.

  • Changing a JLabel text moves everything around -- and it shouldn't

    I have this problem where whenever I call setText() for this one JLabel, it moves everything around. It doesn't have anything to do with the length of the text, because if I replace it with the same exact string, it still moves stuff around.
    I understand it's really hard to troubleshoot these things w/o source code, but I was wondering if this is a problem someone has seen before?
    I'm not going to post my code just because it's too long and I won't ask anyone to go through it for me.
    Basically it is a JFrame with 2 JPanels laid out w/ GridBagLayout, and each JPanel has it's own GridBagLayout
    Thanks

    well, Ironically, while I was creating that code sample thing I figured out what was going on myself. I was confused because of some misdirection--- the issue was not with the JLabel, that was just where the symptoms showed.
    thanks anyway, and sorry for the delayed response -- i only work part time...

  • Replacement of a JComboBox by another

    i have 2 jcomboboxes on a jpanel,on a jframe
    the selection from the first combobox is used to create the second
    when the selection on the first changes, a new second jcombobox is created (is indeed created - i watched it while debugging), but i haven't so far managed to replace the original second jcombobox with the newly created one
    i tried
    panel.validate();
    panel,repaint();
    also tried 2ndcombobox.validate(); ...
    and jframe.validate(); but still nothing
    anyone any ideas?

    see if this helps. And, dukes, oh ...no thanks please! ;)
    += KRR
    /* simple combobox program
    * @author: K R Rajesh
    public class ComboBoxDemo extends JFrame 
         JComboBox comboBox1, comboBox2;
         JLabel lbl = null;
        public ComboBoxDemo()
             String[] values1 = {"combo1", "combo2", "combo3"};
            comboBox1 = new JComboBox(values1);
            String[] values2 = {"bacon & cheese", "no cheese", "no bacon", "include all junks"};   
            comboBox2 = new JComboBox(values2);
            comboBox1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JComboBox c = (JComboBox) e.getSource();
                    System.out.println("" + c.getSelectedItem());
                    showDetails();
            JPanel panel = new JPanel();
            panel.add(new JLabel("Select ur combo:"));
            panel.add(comboBox1);
            lbl = new JLabel("Select ur preference:");
            panel.add(lbl);
            panel.add(comboBox2);
            lbl.setVisible(false);
            comboBox2.setVisible(false);
            Container contentPane = getContentPane();
            contentPane.add(panel);
        public void showDetails()
               lbl.setVisible(true);
            comboBox2.setVisible(true);
        public static void main(String[] args)
             ComboBoxDemo frame = new ComboBoxDemo();
            frame.setTitle("Burger Queen Menu!!");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(200, 200);
            frame.setVisible(true);
    }

Maybe you are looking for

  • Multiple iPods on One Vista Computer

    I just got a new 3rd generation nano and I'm trying to use both my 2nd and 3rd generation nano on my Vista computer. I want to have different music on each iPod but can't figure out how to do this. Any suggestions? Thanks...

  • Transitions are not rendering.  Help?

    I have used iMovie many times, but for some reason my transitions are not rendering now. I place them in and they do not render. I am also having a hard time gettin transition in because after I do one then it shows up as an error and asks me to clos

  • Hi! gurus can i get links to download mm module training material

    Hi! gurus I am madhu persuing MM module. Can u post me some links to find Training material for MM module

  • Depb entries

    hi friends, i don't know it comes comes in which module ( i think in SD ) but still if anybody knows where should we put the entries of DEPB ( Duty Entitlement Pass Book Scheme ) or in which table these entries are. with regards,

  • Scanning for web

    I am scanning back issues of a club magazine to archive on disc as well as publish or upload to the web. Files need to be searchable, but not editable. Issues average 50 pages and include text, color, and black and white photos. How do I streamline t