JLabel and JButton

I got my clock hands issue figured out, now I am trying to get a JButton and JLabels and JTextboxes in. I think I have the code for the labels right, but nothing shows up....any suggestions or places for me to look for help?
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class clocky extends Frame {
     public static void main(String args[])
               Frame frame = new clocky();
               frame.addWindowListener(new WindowAdapter(){
               public void windowClosing(WindowEvent we){
                         System.exit(0);
               frame.setSize(300, 300);
               frame.setVisible(true);
     private void createButton()
          JButton button = new JButton("Show Time");
     private void labels()
     JLabel hourLabel = new JLabel("Hour: ", JLabel.LEFT);
     hourLabel.setVerticalAlignment(JLabel.TOP);
     JLabel minLabel = new JLabel("Minute: ", JLabel.LEFT);
     minLabel.setVerticalAlignment(JLabel.TOP);
     final int centerX = 150;
     final int centerY = 180;
     Shape circle = new Ellipse2D.Double(50, 80, 200, 200);
     public void paint(Graphics g)
          Graphics2D ga = (Graphics2D)g;
          ga.draw(circle);
          //mins hand 6
          //ga.drawLine(150, 90, centerX, centerY); //00     +90 -90
          ga.drawLine(240, 180, centerX, centerY); //15      +90 +90
          //ga.drawLine(150, 270, centerX, centerY); //30      -90 +90
          //ga.drawLine(60, 180, centerX, centerY); //45      -90 -90
     //hrs hand 2.66666666
          ga.drawLine(150, 140, centerX, centerY); //00          +40 -40
          //ga.drawLine(190, 180, centerX, centerY); //15           +40 +40
          //ga.drawLine(150, 220, centerX, centerY); //30           -40 +40
          //ga.drawLine(110, 180, centerX, centerY); //45           -40 -40
}

>
I got my clock hands issue figured out, now I am trying to get a JButton and JLabels and JTextboxes in. I think I have the code for the labels right, >You have methods to create buttons and labels, but nothing calls those methods, and even if hey were called, the created components are added to no container, and are lost at the end of the method.
>
..but nothing shows up....>Wrong, the clock face painted directly to the JFrame shows. And that brings me to the second point. If you added those components to a frame that overrides paint, they will disappear. Once you override paint, it is up to you to paint everything that needs painting.
This is why I would rethink your entire strategy. Override paintComponent(Graphics) in a ClockFace that extends JPanel. ClockFace should also set or override the preferred size. Then add the ClockFace object to another JPanel(s) (e.g. mainPanel) containing the JButton(s), JLabel(s) and ClockFace. Finally, add an EmptyBorder around mainPanel, and set it as the content pane of the JFrame.
And please remember to use the 'code' tags to keep code formatted. To achieve that, select the code and click the CODE button seen on the Plain Text tab of the message posting form.

Similar Messages

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • How do I chance the place of JLabel and JButton in JPanel.

    I'm using DefaultLayout and I want to give the user the ability to change the place of JLabel and JButton. I managed the DnD part, but when "dropped" the control returns to it's original position.
    I tried using setX() and setY().

    You need to use a null Layout, also known as [url http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]Absolute Positioning

  • Color of JLabel and JButton text

    Hi,
    Could someone tell me how to set the color of JLabels and JButton text.
    Thanks

    for JButton text
    myButton.setForeground(Color.yellow);
    for JLabel
    myLabel.setForeground(Color.green);

  • Using clone() with JLabel and JButtons

    I need to find a way of making a duplicate copy of objects that extend JLabel and JButton. Do I need to implement the clone() methord manually, or is there a simpler way of doing this?

    Use a BorderLayout as the main layout. Add the two tables to the WEST and EAST.
    Create another panel using a different layout, maybe a vertical BoxLayout. Add the two buttons and then add this panel to the CENTER of the main panel.
    The secret is to nest different panels with different layout managers to achieve your desired layout.

  • Left- and right-justifying with dot leaders in JLabel and JButton

    Hi,
    I am developing checklists using JLabel and JButton components and want to finish up with the text in each component looking something like the following (each line is a separate button/label):
    ACTION No1............................RESPONSE No1
    ACTION No2............................RESPONSE No2
    ACTION No3............................RESPONSE No3
    The idea is to have the �Action� text left-justified and the �Response� text right-justified with dot-leaders as shown.
    Each text line will be put into its own fixed length label or button.
    I plan to construct a string from text blocks �ACTION No1� and �RESPONSE No1� and add the calculated, exact no of dots in between to fill the space.
    The text font can be fixed (e.g. Courier) or proportional (e.g. Arial).
    My question is how to calculate the number of dots to add to fill the space for different fonts and font sizes.
    I think that using FontMetrics could provide some help but am not sure how this would work.
    Can anyone help.
    Many tks
    John

    Hi,
    I've developed your suggested code further to enable selected JLabels to be toggled visible(true/false) by pressing a JButton.
    I'd like however that when a label is made invisible that the rest of the labels/buttons move up to fill the space left by the now invisible label and vice versa.
    How do I do this, can you enlighten me on a solution?
    Modified code included below. Not very elegant but serves to illustrate the point in question and only makes the label invisible.
    Many tks
    John
    package componentwierd;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ComponentWierd extends JFrame implements ComponentListener, ActionListener {
        boolean isVisible = true;
        JLabel label2 = new JLabel();
        public ComponentWierd() {
            getContentPane().setLayout( new GridLayout(0, 1) );
            // Using my original suggestion
            JLabel label = new JLabel();
            label.setLayout(new BorderLayout());
            label.add(createWierdComponent());
            getContentPane().add(label);
            JButton button = new JButton();
            button.setLayout(new BorderLayout());
            button.add(createWierdComponent());
            button.addActionListener(this);
            getContentPane().add(button);
            // Using Font Metrics
            // JLabel label2 = new JLabel("Label2 West...Label2 East");
            label2.setText("Label2 West...Label2 East");
            label2.addComponentListener( this );
            getContentPane().add(label2);
            JButton button2 = new JButton("Button2 West...Button2 East");
            System.out.println(button2.getIconTextGap());
            button2.addComponentListener( this );
            button2.setVisible(true);
            getContentPane().add(button2);
        public void actionPerformed(ActionEvent e) {
            if (isVisible == true) {
                isVisible = false;
                label2.setVisible(false);
            } else if (isVisible == false) {
                isVisible = true;
                label2.setVisible(true);
        private JComponent createWierdComponent() {
            JPanel panel = new JPanel(new BorderLayout());
            panel.setOpaque( false );
            panel.add(new JLabel("Label WEST"), BorderLayout.WEST);
            panel.add(new JLabel("..............................................."));
            panel.add(new JLabel("Label EAST"), BorderLayout.EAST);
            return panel;
        public void componentResized(ComponentEvent e) {
            if (e.getComponent() instanceof JLabel) {
                JLabel component = (JLabel)e.getComponent();
                String text = component.getText();
                String fitText = fitText(component, text);
                component.setText( fitText );
            if (e.getComponent() instanceof JButton) {
                JButton component = (JButton)e.getComponent();
                String text = component.getText();
                String fitText = fitText(component, text);
                component.setText( fitText );
        private String fitText(JComponent component, String text) {
            // Calculate the total width for painting the text
            // (Not sure why I need the -8)
            Insets insets = component.getInsets();
            int availableWidth = getWidth() - insets.left - insets.right - 8;
            // Calculate the minimum width our text will take
            String start = text.substring(0, text.indexOf("."));
            String middle = "...";
            String end = text.substring(text.lastIndexOf(".") + 1);
            FontMetrics fm = getFontMetrics( component.getFont() );
            int startWidth = fm.stringWidth( start );
            int middleWidth = fm.stringWidth( middle );
            int endWidth = fm.stringWidth( end );
            int minimumWidth = startWidth + middleWidth + endWidth;
            // Add dots to fill out the extra space
            StringBuffer buffer = new StringBuffer(start);
            buffer.append(middle);
            if (minimumWidth < availableWidth) {
                String dot = ".";
                int dotWidth = fm.stringWidth( dot );
                int dots = (availableWidth - minimumWidth) / dotWidth;
                for (int i = 0; i < dots; i++) {
                    buffer.append( dot );
            buffer.append(end);
            String result = buffer.toString();
            return result;
        public void componentHidden(ComponentEvent e) {}
        public void componentMoved(ComponentEvent e) {}
        public void componentShown(ComponentEvent e) {}
        public static void main(String[] args) {
            ComponentWierd frame = new ComponentWierd();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.setSize(200, 200);
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • Creating a gridlayout of jlabels and jbuttons in a JPanel

    The assignment:
    "Create a JPanel that contains an 8x8 checkerboard. Make all of the red squares JButtons and be sure to add them to the JPanel. Make all of the black squares JLabels and add them to the JPanel. Don't forget, you must use the add method to attach the JPanel to the JApplet's contentPane but that there is no contentPane for a JPanel. Be sure to set up any interfaces to handle the JButtons. Use a GridLayout to position and size each of the components instead of absolute locations and sizes."
    This assignment introduces the JPanel to me for the first time, I have not seen what the JDialog and JFrame are.
    What I have:
    import java.awt.*;
    import javax.swing.*;
    * Class CheckerBoard - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class CheckerBoard extends JPanel
        JButton redSquare;
        JLabel blackSquare;
         * Called by the browser or applet viewer to inform this JApplet that it
         * has been loaded into the system. It is always called before the first
         * time that the start method is called.
        public void init()
            JPanel p = new JPanel();
            setLayout(new GridLayout(8,8));
            setSize(512,512);
            ImageIcon red = new ImageIcon("GUI-006-RedButton.png");
            ImageIcon black = new ImageIcon("GUI-006-BlackSquare.png");
            blackSquare = new JLabel(black);
            blackSquare.setSize(64,64);
            redSquare = new JButton(red);
            redSquare.setSize(64,64);
            for (int i = 0; i < 64; i++) {
                if ((i % 2) == 1)
                    add(blackSquare);
                else
                   add(redSquare);
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
    }After successfully compiling it when I try to run it there appears to be nothing to run. I've tried messing around with content panes but I'm not sure if I need to add one for this assignment at all.

    Some suggestions:
    1) First and foremost, read about JPanels, JApplets, and JFrames. None of the help you can get here will substitute for your applying yourself towards this, absolutely none, and judging by your code, you have your work cut out for you.
    2) Don't have your JPanel initialize with an init method, that's what Applets and JApplets do. Instead have it initialize with a proper constructor.
    3) I'm wondering if your "workaround" code belongs in the JApplet that contains the JPanel and not in the JPanel. It has nothing to do with the JPanel's mission. For instance, what if you later decide to place this panel into a JFrame?
    4) Avoid "setSize", and if at all possible, use "setPreferredSize" instead. You are working with LayoutManagers who do the size setting. You are best served by suggesting the size to them.
    5) Please ask specific questions. Just dumping your code without a question is considered quite rude here. We are all volunteers. If you want our free advice, you really should be considerate enough to make it easy for us to help you.
    Good luck.
    Edited by: Encephalopathic on Dec 21, 2007 6:14 PM

  • FlowLayout and Jlabels and Jbuttons,  Help!!!!!

    Ok, I have an Assignment using the FlowLayout only!!. I have been readin all the tutorials and documentation regarding the FlowLayout. Yet it seems I have a problem. Within my prrogram I am to position the buttons on the right and postion the text on the left.
    My question is: Is there a way to postion each component separtely using FlowLayout. Can yoo position the Jlabels to the left and the JButtons to the right?
    I know other layouts would be easier but our proffessor wants us to use the flowlayout for this assignment.
    Here is my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.FlowLayout;
    import java.awt.Font;
                   public class VideoStore extends JFrame {
                        JButton b1, b2, b3;
                        JLabel movie1,movie2,movie3,header;
                   public VideoStore (String title) {
                        super (title);
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        FlowLayout video = new FlowLayout(FlowLayout.LEFT);
                       setLayout(video);
                        header = new JLabel("CCAC VideoStore");
                        header.setFont(new Font("Times New Roman", Font.BOLD, 24));
                       add(header);
                       {movie1= new JLabel("Johnson Family Vacation");
                       movie1.setFont(new Font("Courier New", Font.BOLD, 14));
                        add(movie1);
                        b1= new JButton("Buy");
                        video.setAlignment(FlowLayout.RIGHT);
                        add(b1);}
                        movie2= new JLabel("PitchBlack");
                            movie2.setFont(new Font("Courier New", Font.BOLD, 14));
                       add(movie2);
                        b2 = new JButton ("Buy");
                        add(b2);
                        movie3= new JLabel ("Meet The Fockers");
                       movie3.setFont(new Font("Courier New", Font.BOLD, 14));
                       add(movie3);
                        b3 = new JButton ("Buy");
                        add(b3);
                   }Edited by: ConfusedNewb on Apr 20, 2010 8:10 AM

    ConfusedNewb wrote:
    Sorry.Requirements are: All of the "Buy" JButtons need aligned to the right and all of the JLabels need aligned to the left. There are 3 movie Jlabels and 3 jbuttons. I just cant get them to align without using the spacing trick. Everything has to fit in one window.This should be layed out with 2 JPanels, one for the Labels and one for the Buttons. Since FlowLayout will lay the 2 JPanels side by side, you will get the separation that you need. You just need to justify the Label and Button Panels appropriately and make the outer container and Panels appropriate widths to allow the layout to function as you need.

  • JLabel and JButton both disappear under Mac OS X

    Hello all,
    In my application I have two JButtons and a JLabel. When I compile and run the application the resulting window always shows the first button to begin with but doesn't show the second button until the window loses focus then gains it, or until I click where the second button was suppose to be. Regardless, the JLabel never appears. I've run this on both Windows and Linux now and everything appears as they should. Any thoughts?

    Sorry, I'm still new to these forums.
    import java.util.Locale;
    import java.util.ResourceBundle;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.io.*;
    import javax.swing.*;
    import com.apple.eawt.*;
    public class railsservermanager extends JFrame
         private Font font = new Font("calibri", Font.BOLD, 36);
         protected ResourceBundle resbundle;
         protected AboutBox aboutBox;
         protected PrefPane prefs;
         private Application fApplication = Application.getApplication();
         protected Action newAction, openAction, closeAction, saveAction, saveAsAction, undoAction, cutAction, copyAction, pasteAction, clearAction, selectAllAction;
         static final JMenuBar mainMenuBar = new JMenuBar();     
         protected JMenu fileMenu, editMenu;
         public railsservermanager()
              super("");
              resbundle = ResourceBundle.getBundle ("strings", Locale.getDefault());
              setTitle(resbundle.getString("frameConstructor"));
              Container primaryContainer = this.getContentPane();
              FlowLayout primaryLayout = new FlowLayout();
              primaryContainer.setLayout(primaryLayout);
              createActions();
              addMenus();
              //Collect User's Project Directory
              final String usersproject = JOptionPane.showInputDialog("Please enter your project directory");
              //Initialize My Objects
              final ScriptManager scriptM = new ScriptManager(usersproject);
              final RunCommand runC = new RunCommand();          
              Action startAction = new AbstractAction("Start Server")
                   public void actionPerformed(ActionEvent evt)
                        String startPath = scriptM.createStartScript();
                        int exitstatus = runC.command(startPath);
                        //scriptM.deleteFile(startPath);
                        String result;
                        if(exitstatus == 0)
                             result = "Server Started Successfully.";
                             JOptionPane.showMessageDialog(null, result, result, JOptionPane.INFORMATION_MESSAGE);
              Action stopAction = new AbstractAction("Stop Server")
                   public void actionPerformed(ActionEvent evt)
                        String stopPath = scriptM.createStopScript();
                        int exitstatus = runC.command(stopPath);
                        //scriptM.deleteFile(stopPath);
                        String result;
                        if(exitstatus == 0)
                             result = "Server Stopped Successfully.";
                             JOptionPane.showMessageDialog(null, result, result, JOptionPane.INFORMATION_MESSAGE);
              JButton startserver = new JButton(startAction);
              JButton stopserver = new JButton(stopAction);
              JLabel apptitle = new JLabel(resbundle.getString("frameConstructor"));
              primaryContainer.add(apptitle);
              primaryContainer.add(startserver);
              primaryContainer.add(stopserver);
              setSize(310, 150);
              setVisible(true);
         }I hope this helps a little more.

  • Getting values from JLabel[] with JButton[] help!

    Hello everyone!
    My problem is:
    I have created JPanel, i have an array of JButtons and array of JLabels, they are all placed on JPanel depending from record count in *.mdb table - JLabels have its own value selected from Access table.mdb! I need- each time i press some button,say 3rd button i get value showing from 3rd JLabel in some elsewere created textfield, if i have some 60 records and 60 buttons and 60 labels its very annoying to add for each button actionlistener and for each button ask for example jButton[1].addActionListener() ...{ jLabel[1].getText()......} and so on!
    Any suggestion will be appreciated! Thank you!

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        final int ROWS = 10;
        JPanel[] rows = new JPanel[ROWS];
        final JLabel[] labels = new JLabel[ROWS];
        JButton[] buttons = new JButton[ROWS];
        JPanel p = new JPanel(new GridLayout(ROWS,1));
        final JTextField tf = new JTextField(10);
        ActionListener listener = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tf.setText(labels[Integer.parseInt(((JButton)ae.getSource()).getName())].getText());
        for(int x = 0; x < ROWS; x++)
          labels[x] = new JLabel(""+(int)(Math.random()*10000));
          buttons[x] = new JButton("Button "+x);
          buttons[x].setName(""+x);
          buttons[x].addActionListener(listener);
          rows[x] = new JPanel(new GridLayout(1,2));
          rows[x].add(labels[x]);
          rows[x].add(buttons[x]);
          p.add(rows[x]);
        JFrame f = new JFrame();
        f.getContentPane().add(p,BorderLayout.CENTER);
        f.getContentPane().add(tf,BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Fit image to JLabel or JButton

    I have searched the topic and found some instances of the Image package being used to resize images.
    I have a DB of images (think photos) that I want to display based on user input. The display size will be the same but the actual picture dimensions stored in the DB won't necessarily be.
    My experience is that the amount of image displayed in the JLabel is entirely based on the size of the image itself (i.e. a small image is completely displayed while a large image is partially displayed.
    I wish to have the image fit to the JLabel (or JButton) dynamically.
    Is there an obvious method I am overlooking?
    TIA,
    Sil

    Here is the code for getting the image from the DB. As you can see it is a byte[].
    private static byte[] image = retrieveImage2;
    private static byte[] retrieveImage2() throws Exception
            String query = "SELECT GifBlob FROM Blobfile WHERE Name = ?";
            ResultSet rs = null;
            PreparedStatement pstmt = null;
            Blob blob = null;
            try
               pstmt = conn.prepareStatement(query);
               pstmt.setString(1,"7.jpg");
               rs = pstmt.executeQuery();
               rs.next();
               blob = rs.getBlob("GifBlob");
               byte[] gifBlob = blob.getBytes(1, (int) blob.length());
               return gifBlob;
            }I then call the method to place the image on the JLabel
    public void addImage(byte[] byteImage) {  
            javax.swing.Icon iconImage = new javax.swing.ImageIcon(byteImage);
            jLabel1.setIcon(iconImage);I don't see where I can set the size of an ImageIcon. Should I be using a different way of converting the image?
    Thanks again,
    Sil

  • Align JLabels and JTextFields vertically in different areas

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

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

  • Having probelm with JLabel and setText

    I posted a message in Java Programming but I think it will be more appropriate here. I am trying to create a calculator so I want my JLabel(output) to display the number of the button that is clicked on. I used output.setText("7") but I get an error when compiling saying <identifier> expected. Any advice would be great. Also, is there a getText method in JLabel? I need to concatenate the current contents of JLabel and the value of the button pushed. For example:
    output.setText( output.getText() + "7" );
    Anyways, here is my code. I tried to make it indent so it is easier to read but it doesn't show up once I post it.
    Thanks for you help.
    * 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 );

    // not tested but try it ...
    1. put an empty string into the JLabel
    declare
    String labString = "";
    (and declare the JLabel too)
    2. initialise label - init() {
    myLabel = new JLabel(labString)
    3. activate
    actionPerformed(ActionEvent evt) {
    if (evt.getSource()==button#7) {
    labString = getActionCommand();
    myLabel.setText(labString);
    validate();
    Something like that anyway - it should work + if you 'play' with it, you can probably make it a bit more efficiently than the methods I've outlined here.

  • Layout of JLabels and JTextFields

    Hi!
    I am looking for an easy way to layout JLabels and JTextFields side by side like this:
    jlabel             jtextField
    small jlabel       jtextField
    longer jlabel      jtextFieldAny ideas on how to do this?
    Peter

    Read this section from the Swing tutorial on "Using Layout Managers":
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
    The easiest way is to use a GridLayout.
    JPanel panel = new JPanel();
    panel.setLayout( new GridLayout(0, 2) );
    panel.add( new JLabel("...") );
    panel.add( new JTextField(10) );
    panel.add( new JLabel("...") );
    panel.add( new JTextField(10) );
    A more complicated, but more flexible way is to use a GridBagLayout. Something like this:
    public class ActivityPanel extends JPanel
         public ActivityPanel()
              setBorder( new EmptyBorder(5, 5, 5, 5) );
              setLayout( new GridBagLayout() );
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.insets = new Insets(5, 10, 5, 10);
              // add street
              JLabel lStreet = new JLabel("Street");
              JTextField cStreet = new JTextField(32);
              addRow(gbc, lStreet, cStreet);
              // add city
              JLabel lCity = new JLabel("City");
              JTextField cCity = new JTextField(32);
              addRow(gbc, lCity, cCity);
         private void addRow(GridBagConstraints gbc, Component left, Component right)
              gbc.gridx = GridBagConstraints.RELATIVE;
              gbc.gridy = GridBagConstraints.RELATIVE;
              gbc.gridheight = 1;
              gbc.gridwidth = 1;
              gbc.anchor = GridBagConstraints.EAST;
              add(left, gbc);
              gbc.gridwidth = GridBagConstraints.REMAINDER;
              gbc.anchor = GridBagConstraints.WEST;
              add(right, gbc);
    }

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

Maybe you are looking for