I have this code, when run, it is terribly unorganized. It looks like this:

[Label Here] [Button Here]

[invisible Label][Button]

my program does this:

when something is entered in the JTextField and then you click the [Button Here] then it prints what you printed in the [invisible Label] which is no longer invisible. When you click [Button] it sets the [invisible Label] to have no text in it. is there a way I can set [Button] to be under the [invisible Label] no matter how many spaces it has. What layout would I use and how would I change the JButton code to center it. I tried

JButton name = new JButton ("Name", JButton.CENTER);

but it didn't work. Thanks for the help.

also is there a way to clear a JTextField after a button is pressed?

> is there a way to clear a JTextField after a button is pressed?
setText(null)

@ Ezzaral

are you kidding from OP, this thread will be the longiest at all :-)

@ sirlink99

let's trying Ezzaral suggestion, now without jokes he's right, GridBaglayout is most complete and very nice LayoutManager,

@ Ezzaral

maybe will be better put here Empty value (possible NPE in futures issues with returns)

I'd preferred correct value

myTextField.setText("");

ok here is my code.

//import javax.swing.SwingUtilities;
//import javax.swing.JFrame;

//import javax.swing.JPanel;
import javax.swing.*;
//import javax.swing.BorderFactory;
//import java.awt.Color;
//import java.awt.Dimension;
//import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;


public class BasicApplication
{
	public static void addComponentsToPane(Container pane) {
		//pane.setLayout(new GridBagLayout ());
	}
    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable ()
        {
            public void run ()
            {
          
        
                createAndShowGUI ();         // creates new method

            }
        }
        );
    }


    private static void createAndShowGUI ()
    {
        //System.out.println ("Created GUI on EDT? " +
        //SwingUtilities.isEventDispatchThread ());
    	
        JFrame f = new JFrame ("Swing Paint Demo");                     // names window
        f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);             // sets close type
        //f.setLayout(new GridLayout (5, 1, 1, 1));
        f.add (new MyPanel ());                              // adds a JPannel
        f.setSize (250,200);   
        f.pack ();                                          // calls getPreferredSize method                                
         
                  
        f.setVisible (true);                             // sets all visible


    }
}





class MyPanel extends JPanel implements ActionListener
{
    JLabel paste;
    String pasted;
    JTextField enter;
    public MyPanel ()
    {
        
        setBorder (BorderFactory.createLineBorder (Color.black));
        JButton b1 = new JButton ("Click me to paste");
        enter = new JTextField (20);
        JLabel title = new JLabel ("Type text then click the button: ");
        paste = new JLabel ("                    ");
        JButton eraseMessage = new JButton ("Erase Message");
        
        add (title);
        //b1.setPreferredSize(new Dimension(25, 25));  
        add (b1);      
        add (enter);
        add (paste);
        add (eraseMessage);
        
        //b1.setActionCommand ("one");
        b1.addActionListener (this);
        eraseMessage.addActionListener(this);
    }

    public void actionPerformed (ActionEvent e){
        
        	if (e.getActionCommand ().equals  ("Click me to paste")){
        		pasted = enter.getText();
        		paste.setText (pasted);
        		System.out.print("Button Pressed");
        	
        }
        	if (e.getActionCommand ().equals("Erase Message")){
        		paste.setText("                  ");
        		enter.setText ("");
        	}
    }
    
    public Dimension getPreferredSize ()
    {
        return new Dimension (250, 200);
    }


    public void paintComponent (Graphics g)
    {
        super.paintComponent (g);

        // Draw Text
        //g.drawString ("This is my custom Panel!", 10, 20);              // prints text
        //g.setColor (Color.red);                                    // sets color
        //g.fillOval (115,100,10,10);                                // prints oval
       // g.setColor (Color.black);
    }
}

where do I change the layout?

@mKorbel: Both setText(null) and setText("") will have the same result on the component. getText() will return an empty string in both cases.

> where do I change the layout?
Did you read the tutorial that I posted the link to?

@ Ezzaral

I agreed with that, it will be very good JOKE how to set null for JFormattedTextField with Number Instance (f.e.), and so on ...

<FW>Both setText(null) and setText("") then you just can test with

if(!"".equals(someString))

</FW>

I think that isn't good advice for OP, nothing else, I escaped form this FW about empty/null

I did, but I still don't understand where to add it in my code.

ok here is the new code. I attempted to use the GridBagLayout. please tell me where I am going wrong.

//import javax.swing.SwingUtilities;
//import javax.swing.JFrame;

//import javax.swing.JPanel;
import javax.swing.*;
//import javax.swing.BorderFactory;
//import java.awt.Color;
//import java.awt.Dimension;
//import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;


public class BasicApplication
{
	public static void addComponentsToPane(Container pane) {
		//pane.setLayout (new BoxLayout (pane, BoxLayout.Y_AXIS));
		pane.setLayout(new GridBagLayout ());
		
		

		//pane.setLayout(new GridBagLayout ());
	}
    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable ()
        {
            public void run ()
            {
          
        
                createAndShowGUI ();         // creates new method

            }
        }
        );
    }


    private static void createAndShowGUI ()
    {
        //System.out.println ("Created GUI on EDT? " +
        //SwingUtilities.isEventDispatchThread ());
    	
        JFrame f = new JFrame ("Swing Paint Demo");                     // names window
        f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);             // sets close type
        
        f.add (new MyPanel ()); 								// adds a JPannel
        
        f.setSize (250,200);   
        f.pack ();                                          // calls getPreferredSize method                                
         
                  
        f.setVisible (true);                             // sets all visible


    }
}





class MyPanel extends JPanel implements ActionListener
{
    JLabel paste;
    String pasted;
    JTextField enter;
    
    public MyPanel ()
    {
    	GridBagConstraints c = new GridBagConstraints();
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.gridwidth = 1;
    	c.gridheight = 5;
        setBorder (BorderFactory.createLineBorder (Color.black));
        JLabel title = new JLabel ("Type text then click the button: ");
        c.gridy = 1;
        c.gridx = 1;
        add (title, c);
        JButton b1 = new JButton ("Click me to paste");
        c.gridy = 2;
        c.gridx = 1;
        add (b1, c);     
        enter = new JTextField (20);
        c.gridy = 3;
        c.gridx = 1;
        add (enter, c);
        paste = new JLabel ("                    ");
        c.gridy = 4;
        c.gridx = 1;
        add (paste, c);
        JButton eraseMessage = new JButton ("Erase Message");
        c.gridy = 5;
        c.gridx = 1;
        add (eraseMessage, c);
        //title.setAlignmentX(Component.CENTER_ALIGNMENT);
        //b1.setAlignmentX(Component.CENTER_ALIGNMENT);
        //enter.setAlignmentX(Component.CENTER_ALIGNMENT);
        //paste.setAlignmentX(Component.CENTER_ALIGNMENT);
        //eraseMessage.setAlignmentX(Component.CENTER_ALIGNMENT);
        
        //b1.setPreferredSize(new Dimension(25, 25));  

        //b1.setActionCommand ("one");
        b1.addActionListener (this);
        eraseMessage.addActionListener(this);
    }

    public void actionPerformed (ActionEvent e){
        
        	if (e.getActionCommand ().equals  ("Click me to paste")){
        		pasted = enter.getText();
        		paste.setText (pasted);
        		//System.out.print("Button Pressed");
        	
        }
        	if (e.getActionCommand ().equals("Erase Message")){
        		paste.setText("                  ");
        		enter.setText ("");
        	}
    }
    
    public Dimension getPreferredSize ()
    {
        return new Dimension (250, 200);
    }


    public void paintComponent (Graphics g)
    {
        super.paintComponent (g);

        // Draw Text
        //g.drawString ("This is my custom Panel!", 10, 20);              // prints text
        //g.setColor (Color.red);                                    // sets color
        //g.fillOval (115,100,10,10);                                // prints oval
       // g.setColor (Color.black);
    }
}

Thanks (you may notice I also tried the box layout).

hmmm, you read this tutoriar so quickly, there are lots of omitted sentences

you'd have four choises/options

1/ read tutorial again and more carrefully

plus

http://www.java2s.com/Code/Java/Swing-JFC/GridBagLayoutwithanchorconstraints.htm

http://www.java2s.com/Tutorial/Java/0240__Swing/1460__GridBagLayout.htm
http://www.java2s.com/Tutorial/Java/0240__Swing/1480__GridBagConstraints.htm

anything what you ***, you can save with setPreferredSize

2/ play with GridBagConstraints

3/ ignore that and create own initial Grid with ..., that's very complicated to write anything about "my stupid hack for GridBagLayout" without reads above two requirements, please remove Border for JLabels ot the top

import java.awt.*;
import javax.swing.*;

public class CopyTextNorthPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private JLabel hidelLabel;
    private JLabel firstLabel;
    private JTextField firstText;

    public CopyTextNorthPanel() {

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        for (int k = 0; k < 50; k++) {
            hidelLabel = new JLabel("     ");
            hidelLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 0.5;
            gbc.weighty = 0.5;
            gbc.gridx = k;
            gbc.gridy = 0;
            add(hidelLabel, gbc);
        }
        for (int k = 0; k < 5; k++) {
            firstLabel = new JLabel("Testing Label : ", SwingConstants.RIGHT);
            firstLabel.setFont(new Font("Serif", Font.BOLD, 20));
            firstLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets = new Insets(0, 0, 5, 0);
            gbc.gridx = 0;
            gbc.gridwidth = 8;
            gbc.gridy = k + 1;
            add(firstLabel, gbc);
        }
        for (int k = 0; k < 5; k++) {
            firstText = new JTextField("Testing TextField");
            firstText.setFont(new Font("Serif", Font.BOLD, 20));
            firstText.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets = new Insets(0, 0, 5, 0);
            gbc.gridx = 9;
            gbc.gridwidth = k + 8;
            gbc.gridy = k + 1;
            add(firstText, gbc);
        }
        for (int k = 0; k < 5; k++) {
            firstLabel = new JLabel("Testing Label : ", SwingConstants.RIGHT);
            firstLabel.setFont(new Font("Serif", Font.BOLD, 20));
            firstLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets = new Insets(0, 0, 5, 0);
            gbc.gridx = 20 + k;
            gbc.gridwidth = 8;
            gbc.gridy = k + 1;
            add(firstLabel, gbc);
        }
        for (int k = 0; k < 5; k++) {
            firstText = new JTextField("Testing TextField");
            firstText.setFont(new Font("Serif", Font.BOLD, 20));
            firstText.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets = new Insets(0, 0, 5, 0);
            gbc.gridx = 29 + k;
            gbc.gridwidth = 21 - k;
            gbc.gridy = k + 1;
            add(firstText, gbc);
        }
    }
}

4/ read this tutorial http://download.oracle.com/javase/tutorial/uiswing/layout/index.html because a good, nice and also working properly GUI is always mix with lots of JPanels layed with different LayoutManagers

@ Ezzaral

I agreed with that, it will be very good JOKE how to set null for JFormattedTextField with Number Instance (f.e.), and so on ...

<FW>Both setText(null) and setText("") then you just can test with

if(!"".equals(someString))

</FW>

I think that isn't good advice for OP, nothing else, I escaped form this FW about empty/null

He isn't using JFormattedTextField, so I would say you are just nitpicking for no good reason. The two are equivalent for the purposes of his question.

Ok I have a new code, but I am having trouble centering a JLabel. Here is my new code:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;


public class Layouts2 extends JFrame implements ActionListener{
	
	JLabel title = new JLabel ("Type in some text then click the button", JLabel.CENTER);
	JButton copy = new JButton ("Click me to Paste");
	JTextField txt = new JTextField (20);
	JLabel paste = new JLabel ("",JLabel.CENTER);
	JButton erase = new JButton ("Erase Message");
	String message;
	
	public Layouts2 () {
		super ("Basic Application");
		setSize (250,200);
		setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
		
		JPanel pane = new JPanel ();
		pane.setLayout(new GridLayout (5,1,10,10));
		pane.add (title);
		pane.add (copy);
		copy.addActionListener(this);
		copy.setActionCommand ("copy");
		pane.add (txt);
		pane.add(paste);
		pane.add (erase);
		erase.addActionListener(this);
		erase.setActionCommand ("erase");
		add(pane);
		
		setVisible(true);
	}
	public void actionPerformed (ActionEvent e){
		if ("copy".equals(e.getActionCommand())){
			message = txt.getText();
			paste.setText (message);
			// this is where I would like to center the JLabel paste
			
		}
		if ("erase".equals (e.getActionCommand())){
			paste.setText ("");
			txt.setText ("");
		}
		
	}
	
	public static void main (String [] args){
		Layouts2 layout2 = new Layouts2 ();
		
	}
	
}

Thanks for any help.

I don't understand the question. That label is already centered when I run your code.

when you click the paste button the text isn't centered. I'm sorry I phrased that wrong.

I am running the code right now and when I click the paste button, the text from the textfield is centered in the label below it.

for me it appears at the left side right beside the border of the window.

Are you sure that you have re-compiled the source with these latest changes?

when I run my newest code from my IDE it still places the text beside the frame. Also if I am changing to GridBagLayout, how do I set the size of the grid. for example I would like the panel to be split into a 3 x 5 grid.

The gridx and gridy properties specify which "cells" the components are placed in. gridwidth and gridheight specify how many cells on each axis the components occupy.

does the counting for the cells start off as

[0,0,][1,0][2,0] for my first row of cells

or

[1,1][2,1][3,1]

?

They are zero-based.

ok thanks I will try that. Also, When I am using a JToolBar I added some pictures only and the toolbar shows up, but the pictures don't load. Is it just because my pictures are small (50x50px), or is there something wrong with me defining the ImageIcons and adding them incorrectly? I can upload that part of the code if you wish. Here is one of the pictures added onto the ToolBar.

ImageIcon fWDa = new ImageIcon ("fwdArrow.png");
JButton fWD = new JButton (fWDa);
JToolBar bar = new JToolBar ();

then adding to the ToolBar

bar.add(fWD);

and here is where it all adds to the frame/pane

frame.setJMenuBar (menu);
pane.setLayout(new BorderLayout());
pane.add("North",bar);
frame.add(pane);

I am attempting to add the button with the image to the toolbar.

Thanks for the help.

edit: When I changed the size of one of the pictures to 150x150 px the buttons in the toolbar stayed the same.

Ok. So I added some buttons with images straight to the panel and the images still don't show up. The problem is with the images. How do I fix this? I am now also wondering how I would get the information the user entered from a

JOptionPane.showInputDialog

Never mind. apparently I need to place my images in the main folder not the src folder that contains the source code.

Now I have 2 more questions. If I have a new frame popping up when someone presses a button, then how do I add an actionListener for the button that appeared on the screen? Secondly am I able to use the \n character somehow in a JLabel?

Thanks

yes I am meaning a new line, and here is that part of my code.

public void actionPerformed (ActionEvent e){

if ("FAQ".equals(e.getActionCommand())){
			JFrame faq = new JFrame ("FAQ");
			faq.setSize(600,300);
			faq.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			JPanel faqPane = new JPanel();
			JPanel leftFaqPane = new JPanel ();
			JPanel rightFaqPane = new JPanel ();
			faqPane.setLayout(new GridLayout(1,2));
			leftFaqPane.setLayout (new GridLayout(3,2));
			Font faqTitleFont = new Font ("Arial", 20,20);
			leftFaqPane.setFont(faqTitleFont);
			JLabel faqTitle = new JLabel ("FAQ");
			JTextField search = new JTextField (20);
			JButton searchB = new JButton ("Search");searchB.addActionListener(this);searchB.setActionCommand ("FaqSearch");
			leftFaqPane.add(faqTitle);
			
			Font normal = new Font ("Arial", 10,10);
			leftFaqPane.setFont(normal);
			leftFaqPane.add(search);
			leftFaqPane.add(searchB);
			JLabel searchResult = new JLabel ("Type something in the searchbar. \r\n Type what yo would like to search and suggestions will pop up in this text box");
			
			rightFaqPane.add(searchResult);
			faqPane.add(leftFaqPane);
			faqPane.add(rightFaqPane);
			
			
			faq.add(faqPane);
			faq.setVisible(true);
			int a = 0;
			String searchWord = search.getText();
			if (searchWord != null){
				//searchWord.getDocument().addDocumentListener(this);

				searchWord = search.getText();
			if (searchWord.equalsIgnoreCase ("FAQ")){
				searchResult.setText ("Frequently Searched \n Who made this \n How to set Homepage \n Is this still a WIP");
				
			
			}
			}
			
			
		}
}

disregard some of the attempts at getting the JLabel to work when the text is entered into the textfield.

not for JLabel directly, if you want to paint multiLine text into JLabel, JOptionPane ToolTip.... , then the "best of" is using by Html syntax, wait sec.

myLabel.setText("<html>  QQQQQQQQQQQQ: <br>"
                + " - wwwwwwwwwwwwwwwwwwwwwwwwww <br>"
                + " - eeeeeeeeeeeeeeeeeeeeeeeeee <br>"
                + " - eeeeeeeeeeeeeeeeeeeeeeeeee </html>  ");

if you'll find (google) for MultiColor JLabel then your JLabel text would bw colored too

maybe there (these exanples is just and about "this method exist and I can overRode that this/these way(s)")

http://www.exampledepot.com/egs/index.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.