I do not even know if I can do this, so this may be quick and painless.
I have my existing code, all the fields, buttons, scroll panel and everything else where I need them. Simple FlowLayout is fine for what I am doing.
Yesterday I created this goofy little graphic and went to put it in right next to my buttons. Figured I would just insert it above the buttons and let FlowLayout handle the rest and just stick it where it wanted.
It wouldn't work. The graphic is there, no compile errors, no errors at all in fact, it just does not show up unless I open a separate panel (as I have below in bold).
Can I not stick this little graphic, meant to be like a logo, into my current GUI without having this extra panel open up?

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import java.lang.*;
import javax.swing.JFrame;

public class Inventory2 extends JFrame
{
	private JLabel cdNameLabel; // name label 
	private JLabel artistLabel; // item number label 
	private JLabel nstockLabel; // units in stock label 
	private JLabel priceLabel; // price each label 
	private JLabel itemLabel; // item number label 
	private JTextField cdNameField; // name display 
	private JTextField artistField; // artist display 
	private JFormattedTextField nstockField; // units in stock display 
	private JFormattedTextField priceField; // price each display 
	private JTextField itemField; // item number display 
	private NumberFormat nstockFormat; // format field and parse numbers 
	private NumberFormat priceFormat; // format field and parse numbers 
	private JButton btnAdd; // first button 
	private JButton btnPrev; // previous button 
	private JButton btnNext; // next button 
	private JButton btnDel; // last button 
	private JButton btnFirst; // first button
	private JButton btnLast; // last button
	private JButton btnModify; // modify button
	private JButton btnSave; // save button
	private JButton btnSearch; // search button
	private JPanel buttonJPanel; // JPanle to hold buttons 
	private JPanel fieldJPanel; // JPanel to hold labels and displays 
	private JPanel fontJPanel; // JPanel to display logo 
	private int currCD; 
	private double total = 0; // variable for total inventory 
	private JList Inventorylist; // JList to take place of old array
	private DefaultListModel listModel;
	private JScrollPane jScrollPanel;  
	private float Invtotal = .00f;
	
	 DecimalFormat formatter = new DecimalFormat("$0.00");
	
	public Inventory2() // create class and method to perform GUI build 
	{ 
		initComponents(); 
	} 

	private void initComponents() 
	{ 
		// create label names 
		cdNameLabel = new JLabel("CD Name:"); 
		artistLabel = new JLabel("Artist:");
		nstockLabel = new JLabel("In Stock:"); 
		priceLabel = new JLabel("Each Item Cost:$"); 
		itemLabel = new JLabel("Item Number:"); 
 
		
		// initial fields
		cdNameField = new JTextField(25);
		cdNameField.setEditable(true);
		artistField = new JTextField(15);
		artistField.setEditable(true);
		nstockField = new JFormattedTextField(nstockFormat);
		nstockField.setEditable(true);
		nstockField.setColumns(5);
		priceField = new JFormattedTextField(priceFormat);
		priceField.setEditable(true);
		priceField.setColumns(5);
		itemField = new JTextField(4);
		itemField.setEditable(true);
				
		// JList
		jScrollPanel = new JScrollPane();
		Inventorylist = new JList(); 
		currCD = 0;
	
				
		// buttons 
		btnAdd = new JButton(); 
		btnNext = new JButton(); 
		btnPrev = new JButton(); 
		btnDel = new JButton();
		btnLast = new JButton();
		btnFirst = new JButton();
		btnModify = new JButton(); 
		btnSave = new JButton();
		btnSearch = new JButton();
		
		getContentPane().setLayout(new FlowLayout());
		
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		
				

		// place textFields and labels
		
		//artist
		artistLabel.setText("Artist"); 
		getContentPane().add(artistLabel); 

		artistField.setMinimumSize(new Dimension(70,20)); 
		artistField.setPreferredSize(new Dimension(70,20));
		getContentPane().add(artistField); 
		
		// cd name
		cdNameLabel.setText("CD Name"); 
		getContentPane().add(cdNameLabel); 

		cdNameField.setMinimumSize(new Dimension(70,20)); 
		cdNameField.setPreferredSize(new Dimension(70,20));
		getContentPane().add(cdNameField);
		
		// copies in stock
		nstockLabel.setText("Copies In Stock"); 
		getContentPane().add(nstockLabel); 

		nstockField.setMinimumSize(new Dimension(5,20)); 
		nstockField.setPreferredSize(new Dimension(5,20));
		getContentPane().add(nstockField); 
		
		//price of cd
		priceLabel.setText("Price"); 
		getContentPane().add(priceLabel); 

		priceField.setMinimumSize(new Dimension(20,20)); 
		priceField.setPreferredSize(new Dimension(20,20));
		getContentPane().add(priceField); 
		
		//item number of cd
		itemLabel.setText("Item Number"); 
		getContentPane().add(itemLabel); 

		itemField.setMinimumSize(new Dimension(5,20)); 
		itemField.setPreferredSize(new Dimension(5,20));
		getContentPane().add(itemField); 
		

		// add listeners
		
		btnAdd.setText("Add");
		btnAdd.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnAddActionPerformed(evt);
			}
		});
		getContentPane().add(btnAdd);
		 
		// PREVIOUS
		btnPrev.setText("Previous");
		btnPrev.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnPrevActionPerformed(evt);
			}
		});
		getContentPane().add(btnPrev);
		
		// NEXT
		btnNext.setText("Next");
		btnNext.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnNextActionPerformed(evt);
			}
		});
		getContentPane().add(btnNext);
		
		// SEARCH
		btnSearch.setText("Search");
		btnSearch.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnAddActionPerformed(evt);
			}
		});
		getContentPane().add(btnSearch);
		
		// FIRST
		btnFirst.setText("First");
		btnFirst.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnFirstActionPerformed(evt);
			}
		});
		getContentPane().add(btnFirst);
		
		// LAST
		btnLast.setText("Last");
		btnLast.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnLastActionPerformed(evt);
			}
		});
		getContentPane().add(btnLast);
				
		// MODIFY
		btnModify.setText("Modify");
		btnModify.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnAddActionPerformed(evt);
			}
		});
		getContentPane().add(btnModify);
					
		// SAVE
		btnSave.setText("Save");
		btnSave.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnAddActionPerformed(evt);
			}
		});
		getContentPane().add(btnSave);
		
		// DELETE
		btnDel.setText("Delete");
		btnDel.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnAddActionPerformed(evt);
			}
		});
		getContentPane().add(btnDel);
		
		
		// new Jlist model
		listModel = new DefaultListModel();
		Inventorylist.setModel(listModel);
		
		jScrollPanel.setViewportView(Inventorylist);
		
		getContentPane().add(jScrollPanel);
		
		pack();
	}// close
	
			
		private void btnAddActionPerformed(ActionEvent evt)
		{
			// Create cd to add
			CdwArtist newCD = new CdwArtist();
			newCD.setArtist(artistField.getText());
			newCD.setName(cdNameField.getText());	
			newCD.setItemno(Integer.parseInt(itemField.getText()));
			newCD.setNstock(Integer.parseInt(nstockField.getText()));
			newCD.setPrice(Float.parseFloat(priceField.getText()));
			
			// Add cd to list
			listModel.addElement(newCD);
			currCD = listModel.size()-1;  // sets currCD to added index
			
			
			// Clear the text fields after add
			artistField.setText(null);
			cdNameField.setText(null);	
			itemField.setText(null);
			nstockField.setText(null);
         priceField.setText(null);
	
			}// end ADD
		
		private void btnPrevActionPerformed(ActionEvent evt)
		{
			// Grab Previous cd 
			if (--currCD<0) currCD = listModel.size()-1;
			CdwArtist newCD = (CdwArtist) listModel.get( currCD );
			

			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
					
			
			}// end PREV
			
				private void btnNextActionPerformed(ActionEvent evt)
			{
			// Grab Next cd 
			if (++currCD >= listModel.size()) currCD= 0;
			CdwArtist newCD = (CdwArtist) listModel.get( currCD );
			

			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
					
			
			}// end NEXT
			
			
				private void btnFirstActionPerformed(ActionEvent evt)
			{
			// Grab First cd 
			CdwArtist newCD = (CdwArtist) listModel.get(0);
			

			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
					
			
			}// end FIRST
			
			
				private void btnLastActionPerformed(ActionEvent evt)
			{
			// Grab Last cd 
			CdwArtist newCD = (CdwArtist) listModel.lastElement();
			

			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
					
			
			}// end LAST
			
		// run it
		public static void main(String args[])
		{
		JFrame frame = new JFrame( "Drawing 2D shapes" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

     [B] // create ShapesJPanel
      ShapesJPanel shapesJPanel = new ShapesJPanel();
      frame.add( shapesJPanel ); // add shapesJPanel to frame
      frame.setSize( 125, 200 ); // set frame size
      frame.setVisible( true ); // display frame[/B]
		java.awt.EventQueue.invokeLater(new Runnable()
			{
			public void run()
				{
				new Inventory2().setVisible(true);
			   }
			});
		}
			
} // close class

I thought I could just slide

frame.add( shapesJPanel ); // add shapesJPanel to frame

in after my

getContentPane().setLayout(new FlowLayout());
		
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

and it would just show up as the first item in my pane. But it does not work.

Recommended Answers

All 20 Replies

It will not work as rest of your components(buttons, text fields and text area) just lay around un-organized and then you just try to show in another component.
I think people will argee with me when I say you need to group them.
This is what I do normaly

/* Default constructor of RenameImage object. */
    public void runRenameImage()
    {
    	renameFrame = new JFrame("Rename");    	
    	gbc.insets = new Insets(1, 1, 1, 1);
		buildGUI();
		renameFrame.setSize(470,470);
		renameFrame.setResizable(false);
		renameFrame.setLocation(150,150);
		renameFrame.addWindowListener(this);
    	renameFrame.setVisible(true);
		runRename = new RunRename(barProgress, labelProcess);
    }
    
    /* Method to setup GUI*/
    public void buildGUI()
    {
    	setupIndexPanel();
    	setupDestinationPanel();
    	setupOptPanel();
    	setupProcessPanel();
    	setupProgressPanel();
    	setupRenameLayout();
    }

=======================================

// Sortest example
public void setupProgressPanel()
    {
    	panelProgress = new JPanel();
    	Dimension size = new Dimension(440, 40);
        panelProgress.setPreferredSize(size);
    	panelProgress.setBorder(new TitledBorder(bs));
    	barProgress = new JProgressBar(0, 100);
        barProgress.setValue(0);
        barProgress.setStringPainted(true);
        barProgress.setPreferredSize(new Dimension(360, 20));
        panelProgress.add(barProgress);
    }


============================================

/* Method to will set layout of all panels*/
    public void setupRenameLayout()
    {
    	renameFrame.setLayout(gbag);
    	gbc.gridx = 0;
    	gbc.gridy = 0;
    	gbag.setConstraints(panelIndex, gbc);    	
    	gbc.gridx = 0;
    	gbc.gridy = 1;
    	gbag.setConstraints(panelDestination, gbc);
    	gbc.gridx = 0;
    	gbc.gridy = 2;
    	gbag.setConstraints(panelOptions, gbc);    	
    	gbc.gridx = 0;
    	gbc.gridy = 3;
    	gbag.setConstraints(panelProcess, gbc);
    	gbc.gridx = 0;
    	gbc.gridy = 4;
    	gbag.setConstraints(panelProgress, gbc);
    	renameFrame.getContentPane().add(panelIndex);
    	renameFrame.getContentPane().add(panelDestination);
    	renameFrame.getContentPane().add(panelOptions);
    	renameFrame.getContentPane().add(panelProcess);
    	renameFrame.getContentPane().add(panelProgress);
    }

This is my way to do it, other people may do it differently.
Here is also link to official Java tutorial

OK, I think I understand. Because I am using Flowlayout, and my items are unorganized I cannot put my graphic in.
I will need to reorganize as you have shown here.
I have a few questions about the code you show.

1st
Does it replace my

getContentPane().setLayout(new FlowLayout())

or run in addition to this, down in my runable replacing

new Inventory2().setVisible(true);

or is it in addition to both and should be placed elsewhere.

2nd
Is this all just generic default code, or is it ready to be used?
I do not know what progress bar, process panel, or rename do for me here.

As peter_budo pointed out, there are some organizational issues with the way you are trying to build your layouts, but I think if you put

getContentPane().add( new ShapesJPanel() ); // add shapesJPanel to frame

right after you set the layout in initComponents(), your panel should show up fine.

That is what I had hoped, and what I tried to impliment yesterday.
Almost exactly. Here is where I slide yours in, witht he same resutls.
Nothing errors, it just does not show up.

private void initComponents() 
	{ 
			
		// create label names 
		cdNameLabel = new JLabel("CD Name:"); 
		artistLabel = new JLabel("Artist:");
		nstockLabel = new JLabel("In Stock:"); 
		priceLabel = new JLabel("Each Item Cost:$"); 
		itemLabel = new JLabel("Item Number:"); 
 
		
		// initial fields
		cdNameField = new JTextField(25);
		cdNameField.setEditable(true);
		artistField = new JTextField(15);
		artistField.setEditable(true);
		nstockField = new JFormattedTextField(nstockFormat);
		nstockField.setEditable(true);
		nstockField.setColumns(5);
		priceField = new JFormattedTextField(priceFormat);
		priceField.setEditable(true);
		priceField.setColumns(5);
		itemField = new JTextField(4);
		itemField.setEditable(true);
				
		// JList
		jScrollPanel = new JScrollPane();
		Inventorylist = new JList(); 
		currCD = 0;
	
				
		// buttons 
		btnAdd = new JButton(); 
		btnNext = new JButton(); 
		btnPrev = new JButton(); 
		btnDel = new JButton();
		btnLast = new JButton();
		btnFirst = new JButton();
		btnModify = new JButton(); 
		btnSave = new JButton();
		btnSearch = new JButton();
		
		getContentPane().setLayout(new FlowLayout());
		
		
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		
		[B]// add shapesJPanel to frame	
		getContentPane().add( new ShapesJPanel() );[/B]			

		// place textFields and labels

I put it a few different places, before the fields, after the buttons, just seeing if placement would matter, but no matter what I put it nothing happens.

Is there anything in the ShapesPanel?

yes. If I implement it in is own panel it shows up fine, although in another panel behind my cd window ... as so ...

// run it
		public static void main(String args[])
		{
		JFrame frame = new JFrame( "CD Inventory Logo" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      // create ShapesJPanel
      ShapesJPanel shapesJPanel = new ShapesJPanel();
      frame.add( shapesJPanel ); // add shapesJPanel to frame
      frame.setSize( 125, 200 ); // set frame size
      frame.setVisible( true ); // display frame
		java.awt.EventQueue.invokeLater(new Runnable()
			{
			public void run()
				{
				new Inventory2().setVisible(true);
			   }
			});
		}

That is why, like Peter indicates, that maybe it could not be done in an unorganized pane like I have.

How are you displaying the logo? You may have to set the size on your panel before you add it to your container if the logo has no intrinsic size of its own.

This is what jwenting told me few months back while I had problem with my layout

Don't try to force your design into a single layoutmanager.
Layer your layout.
You could for example place a panel in the region of the gridbag that you want those two components to appear, set that to gridlayout, and place the components in the cells of that grid.
These cells can be individually configured to have different alignment properties.

Meaning, organize your component in groups of fever components, if necessary put them even on their own. Given them requered arrangement, in their own space and then after that put this separate layouts together. It is like building with LEGO.
Fastest solution for you will be to put all your existing components on to JPanel, create separate JPanel for graphic and then add these two JPanels to frame. That is the fastest you can do. Longer, but more satisfying would be doing some arrangements in existing code so it will not requere whole re-do. You have to admit no1zson that current layout is not best solution, specialy without fixed frame size....

This is what jwenting told me few months back while I had problem with my layout

Meaning, organize your component in groups of fever components, if necessary put them even on their own. Given them requered arrangement, in their own space and then after that put this separate layouts together. It is like building with LEGO.
Fastest solution for you will be to put all your existing components on to JPanel, create separate JPanel for graphic and then add these two JPanels to frame. That is the fastest you can do. Longer, but more satisfying would be doing some arrangements in existing code so it will not requere whole re-do. You have to admit no1zson that current layout is not best solution, specialy without fixed frame size....

I certianly understand it is not the greatest design .. :$ , it was kind of put together on the fly one week at a time, it is my first dont forget.
This logo is the last thing I am adding to it though, so I did not want to redo the entire layout for it. I like your idea about adding my two panels into one new frame, but have no idea how to even start that, and do not want to get in over my head again as I did last week.

Ezzarral - I am displaying it the only way I know how, I just put the code up for you to look at ... but I do not know what you mean by resize, or if there is a different way to display.

Instead of adding everything directly to JFrame getContentPane().add(artistLabel); add all components to JPanel

//First JPanel
JPanel allComponents = new JPanel();
allComponents.add(artistLabel);
allComponents.add(artistField);

=====================
//Second JPanel
JPanel myGraphic = new JPanel();
ShapesJPanel shapesJPanel = new ShapesJPanel();
myGraphic.add(shapesJPanel);


===========================
//Add JPanels to JFrame
getContentPane().add(allComponents);
getContentPane().add(myGraphics);

If you willing to learn you should not be ashamed of the mistakes that you do in process of learning. You should be ashamed if you would not want to learn just wanted results...

// add shapesJPanel to frame    
ShapesJPanel logo = new ShapesJPanel();
logo.setSize(125,200);
getContentPane().add( logo );

Peter ... you are right, and I am trying.

I will give that a shot, hope I do not mess up everything else implimenting it!

Ezzarral, that did not work either. Does not error, does not do anything, and no logo appears when the app opens.

It would help if you posted the ShapesJPanel code.

My bad. Here it is. Pretty simple, but most of my work is.

import javax.swing.JFrame;

public class Shapes
{
   // execute application
   public static void main( String args[] )
   {
      // create frame for ShapesJPanel
      JFrame frame = new JFrame( "Logo" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      // create ShapesJPanel
      ShapesJPanel shapesJPanel = new ShapesJPanel();
      frame.add( shapesJPanel ); // add shapesJPanel to frame
      frame.setSize( 425, 200 ); // set frame size
      frame.setVisible( true ); // display frame
   } // end main
} // end class Shapes

Um, this class has nothing in it. Are you sure this is the code? It's also called Shapes - not ShapesJPanel.

I am sorry, I have too many windows open at once, this is the logo.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.BasicStroke;
import java.awt.GradientPaint;
import java.awt.TexturePaint;
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class ShapesJPanel extends JPanel 
{
   // draw cd logo
	public void paintComponent( Graphics g )
   {
      super.paintComponent( g ); // call superclass's paintComponent

      Graphics2D g2d = ( Graphics2D ) g; // cast g to Graphics2D

      // draw 2D ellipse filled with a blue-yellow gradient
      g2d.setPaint( new GradientPaint( 5, 30, Color.BLUE, 35, 100, 
         Color.WHITE, true ) );  
      g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );

      // draw 2D rectangle in blue
      g2d.setPaint( Color.BLUE );                  
      g2d.setStroke( new BasicStroke( 10.0f ) ); 
      g2d.draw( new Rectangle2D.Double( 1, 25, 75, 110 ) );

     
     } // end method paintComponent
} // end class ShapesJPanel

Ok, use this instead

// add shapesJPanel to frame    
ShapesJPanel logo = new ShapesJPanel();
logo.setPreferredSize(new Dimension(200,200));
getContentPane().add( logo );

wow. that worked. so, setpreferredsize instead of logo.getsize was the answer?

Would you explain why that would make a difference?

wow. that worked. so, setpreferredsize instead of logo.getsize was the answer?

Would you explain why that would make a difference?

The layout manager uses the preferred size of a component in determining how much space to allocate for it in the layout. If preferred size is not set it will try to determine one on its own based upon inspection of the component. Since you don't have any other components in that panel, just a custom paint routine, it didn't have anything to go on and probably gave it a size of 0x0 (or nearly, I'm not really sure there).

The point is, setPreferredSize(), setMinimumSize(), and setMaximumSize() are used by the layout managers in determining the initial, min, and max sizes to allocate to your components.

Just a side note:
You could also add the following constructor to your ShapesJPanel class, which would keep the preferred size info inside the panel that requires it

public ShapesJPanel(){
         super();
         setPreferredSize(new Dimension(75,150));
     }

That was mynext question! You have helped me so much you know what I am going to ask before I even ask it now!
I have some more buttons to work on, the modify is kicking my butt, but I have a few more things to try before I bring it out here.

Thanks also Peter - I only have a few more things to do to this app, and then I am going to go back through everything and see if I have learned enough to make it better. Things like you have mentioned with my fields and panels, and probably even breaking some of these methods up and stuff like that.

I appreciate the help guys.

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.