LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-03-2004, 08:29 AM   #1
Mega Man X
LQ Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 65
Java help! Using Swing and Layouts


Hello there!

I'm trying to create a very simple program with Java. It's not working yet, nor the buttons will work, since I've not added any listener yet (most likely I will ask for help again here when I add listeners..ghehe), but I will tell what I'm trying to do, so more experienced programmers may point out what I'm doing wrong. The program is simple. I've a menu (File = close and Options = copy text, clean field). Meaning that if you click in File, it will drop down a menu where you can close the program, and a text option to copy and clear. Bellow the menu, I've a textfield, where the user can type any message he/she wants (Default message is insert text). Bellow this, you have 3 keys, Picture 1, Picture 2 and Text. If the user click in Picture 1, picture will be displayed, same goes to Picture 2. However, if the user clicks in Text, the field where the pictures were, will turn into a text field (remember the copy/clear functions from the menu?. It will be used here. If the user type something in TextFiled1 and choose copy/clear from the menu, it will be used in here).
Another button(?) bellow these 3 keys was added to hold the image. Here is the buggy code so far:

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

public class MyProgram extends JFrame
{


	// Build Constraints
	void buildConstraints(GridBagConstraints gbc, int gx, int gy,
							int gw, int gh, int wx, int wy) {

		gbc.gridx      = gx;
		gbc.gridy      = gy;
		gbc.gridwidth  = gw;
		gbc.gridheight = gh;
		gbc.weightx    = wx;
		gbc.weighty    = wy;
	}


	// Menu variables
	JMenuItem j1 = new JMenuItem("Close");
	JMenuItem j2 = new JMenuItem("Copy Text");
	JMenuItem j3 = new JMenuItem("Clean Field");


	// Contructor
	MyProgram()
	{
		super("My Program");
		setSize(320,240);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints constraints = new GridBagConstraints();
		JPanel pane = new JPanel();
		pane.setLayout(gridbag);


		// Create and place the menu
		buildConstraints(constraints, 0,0,1,1,100,100);
		constraints.fill   = GridBagConstraints.NONE;
		constraints.anchor = GridBagConstraints.NORTHWEST;
		JMenu m1 = new JMenu("File");
		m1.add(j1);
		JMenu m2 = new JMenu("Options");
		m2.add(j2);
		m2.add(j3);
		JMenuBar bar = new JMenuBar();
		bar.add(m1);
		bar.add(m2);
		gridbag.setConstraints(bar, constraints);
		pane.add(bar);


		// Create and place the textField
		buildConstraints(constraints, 0,1,1,1,100,100);
		constraints.fill = GridBagConstraints.NONE;
		constraints.anchor = GridBagConstraints.NORTHWEST;
		JTextField edit = new JTextField("Insert Text", 30);
		gridbag.setConstraints(edit, constraints);
		pane.add(edit);


		// Create buttons for picture 1, 2 and text field
		buildConstraints(constraints, 0,2,1,1,100,100);
		constraints.fill = GridBagConstraints.NONE;
		JButton picture1 = new JButton("Picture 1");
		gridbag.setConstraints(picture1, constraints);
		pane.add(picture1);

		buildConstraints(constraints, 1,2,1,1,100,100);
		constraints.fill = GridBagConstraints.NONE;
		JButton picture2 = new JButton("Picture 2");
		gridbag.setConstraints(picture2, constraints);
		pane.add(picture2);

		buildConstraints(constraints, 2,2,1,1,100,100);
		constraints.fill = GridBagConstraints.NONE;
		JButton textField = new JButton("Text");
		gridbag.setConstraints(textField, constraints);
		pane.add(textField);


		// Image

		buildConstraints(constraints, 0,3,1,1,100,100);
		constraints.fill = GridBagConstraints.NONE;
		ImageIcon imageMmx1 = new ImageIcon("mmx1.gif");
		JButton  mmx1 = new JButton(imageMmx1);
		gridbag.setConstraints(mmx1, constraints);
		pane.add(mmx1);


		setContentPane(pane);
		setVisible(true);
		pack();

	}


	public static void main( String[] arguments )
	{
		MyProgram testing = new MyProgram();

	}

}
If you run the code, you will see that it looks messy as hell. I want the buttons to be aligned differently. for example, the second line, has a huge text field, located at the first column. Then, my first button (column1) at the third line will look too big, and the space to the button 2 as well (second column). How could I fix it?
Another question before I start writing listeners... The fourth line has a button (holding the image). I want the user to be able to switch between two pictures, or a textfield. Is it wise to use a button in there?.

Again, nothing will work. In the book I'm reading (the crap Sams teach yourself Java, 3rd edition) says we have to work out first the layout and then the functions... so

I'm trying to use those gif images in my program:

http://www.geocities.com/mmworld27/mm.html

with Megaman X, indeed

Thanks in advance for any help my friends...

Last edited by Mega Man X; 02-03-2004 at 08:31 AM.
 
Old 02-03-2004, 12:56 PM   #2
Looking_Lost
Senior Member
 
Registered: Apr 2003
Location: Eire
Distribution: Slackware 12.0, OpenSuse 10.3
Posts: 1,120

Rep: Reputation: 45
Just at a quick glance, the positioning of the menu seems a bit - well unique You can put it where it is but I guess it looks a lot better in the standard place menus go just below the title bar.


Dump the lines/comment out

gridbag.setConstraints(bar, constraints);
pane.add(bar);

and pop in

setJMenuBar(bar);


setvisible(true);
has been deprecated in preference of
show();

and

hide();

I'll have a look a little later to see if I can help if you don't get it sorted by yourself
 
Old 02-04-2004, 04:35 PM   #3
Mega Man X
LQ Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 65
Thanks so much mate!!!

Sorry that I did not answer you before. For some reason, the forum did not send me an e-mail notification(?). I've been working all day long trying to find a better solution for the problem. GridBagLayout is way to complicated to be used, at least in my humble program... I just need to make something to learn the basics of working with layout and user inputs

So, here is what I've done. I've took out the hold GridBagLayout away, and instead of it, I added two JPanel to the program. The first one has three buttons (image1, image2 and text) and the second JPanel holds the image (which can also be used as text...).

The program works, and the listeners responds well. Here is the code so far, still buggy and over-commented:

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Component;


public class MyProgram extends JFrame implements ActionListener{

	// Create image holder
	ImageIcon picture1  = new ImageIcon("mmx1.gif");	// load image1
	JLabel lb1          = new JLabel(picture1);

	ImageIcon picture2  = new ImageIcon("mmx2.gif");	// load image2
	JLabel lb2          = new JLabel(picture2);

	JScrollPane scroll  = new JScrollPane(lb1);			// place the image in the container


	JTextField edit     = new JTextField("Insert Text");		// Textfield

	// Buttons and Listeners
	JButton btn1 = new JButton("Image 1");
	JButton btn2 = new JButton("Image 2");
	JButton btn3 = new JButton("Text");



	public MyProgram(){

		super("My Program");	// default title
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		// default close operation
		setSize(320,240);		// set a minimum size


		// Creates the main menu
		// Still working on it... :p

		// add listeners to all the buttons
		btn1.addActionListener(this);
		btn2.addActionListener(this);
		btn3.addActionListener(this);


		// Create two panels
		// This holds the text field
		JPanel pane1 = new JPanel();
		pane1.setLayout(new BorderLayout());
		pane1.add(edit, "Center");


		// This panel holds three buttons
		JPanel pane2 = new JPanel();
		pane2.setLayout(new FlowLayout());
		pane2.add(btn1);
		pane2.add(btn2);
		pane2.add(btn3);


		//
		Container container = getContentPane();		// create a container
		container.add(pane1,  "North");				// add pane1 to container
		container.add(pane2,  "Center");			// add pane2 to container
		container.add(scroll, "South");				// add image or text to container



		setVisible(true);		// makes it all visible
		pack();					// makes it fit to the frame
	}


	// main comes in here
	public static void main (String[] arguments) {
		MyProgram testing = new MyProgram();
	}


	// taking care of user input
	public void actionPerformed (ActionEvent evt){

		Object source = evt.getSource();

		if (source == btn1) {

			setTitle ("The listener works");

		} else if (source == btn2) {

			setTitle ("The second listener works");

		} else if (source == btn3) {

			setTitle ("Third Listener up and running");
		}

		repaint();		// re-draw the hole screen
	}

}
Now I've faced another problem. If you run the program, you will see three buttons. Clicking on the button will change the titles. I've been all day long trying to make it switch between the pictures and I could not . I simply cannot think in a wise way of doing it (picture1 = picture2) or whatever...

Despite it, I cannot add a top menu to my application... Container can handle a lot of positions:

container.add(bla1, "Center")
container.add(bla2, "South")

and etc. The problem is, my menu should be at the top ("North"), the textfield at the middle ("Center"), the button at the bottom ("South") and the last should also be at the bottom (the image/text holder). I cannot use two "North" or "South" position, since the second will always overwrite the first one... Any ideas about it?

Thanks a lot in advance fellows, hope you can understand a little better what I'm trying to achieve here

Regards!
 
Old 02-04-2004, 04:39 PM   #4
Mega Man X
LQ Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 65
Oh yeah, the menu should be just as in the first code as well:

Code:
        // Menu variables
	JMenuItem j1 = new JMenuItem("Close");
	JMenuItem j2 = new JMenuItem("Copy Text");
	JMenuItem j3 = new JMenuItem("Clean Field");

        JMenu m1 = new JMenu("File");
        m1.add(j1);
	JMenu m2 = new JMenu("Options");
	m2.add(j2);
	m2.add(j3);
	JMenuBar bar = new JMenuBar();
	bar.add(m1);
	bar.add(m2);
but the problem is, how to set it up at the top, since I cannot use two South or North Positions .
 
Old 02-04-2004, 06:35 PM   #5
Looking_Lost
Senior Member
 
Registered: Apr 2003
Location: Eire
Distribution: Slackware 12.0, OpenSuse 10.3
Posts: 1,120

Rep: Reputation: 45
if you put

setJMenubar(bar);

right after the menu stuff there, the menu will be located where you'd expect to see it along the top of the window.

To change the picture is one line away - just use one label - lb1 - but load the two pictures into picture1 and picture2 then to switch them depending on what button was picked plop in:


lb1.setIcon(picture1)

or

lb1.setIcon(picture2)

depending on what part of the if statement in the actionlistener is appropriate...the layout managers can be a right pain in the.......

oh - and repaint is unecessary in this case I think.

Last edited by Looking_Lost; 02-04-2004 at 06:39 PM.
 
Old 02-05-2004, 11:16 AM   #6
Mega Man X
LQ Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 65
You really are good at this Looking_Lost. Although, your nick should fits me better, since I get often lost in here . lol. Well, thanks a lot mate. You were totally right, the setJMenuBar(bar) sets the menu exactly where it should be . repaint() is not necessary either. I've just dumped the line and it works. And right again about changing only lb1.

As I said, I've been following Sams Teach yourself Java in 21 days(*cough). It's not a bad book, but from time to time, I feel lost or am not totally sure about what a line does or where/when to use (repaint is a great example). I understand the target of "Fast Learning" with that book, but for it's price (I've paied about 40 USD) it should really be more clear...

I've to say, I was (perhaps still am... dunno) a big Java fan until I went into Layouts. Man, it's just awfully complicated, at least for me :S. Perhaps I should learn gtk or qt instead to work with graphics, ghehe. Nah, I will stick with Java a little bit more .

Well, the program works almost entirely right now . Although, being a pretty useless program, looks like an application now. I have to still polish the code. The only thing that I didn't like is when the user presses the button Image and then the button Text. The image stays there along with the text and it's ugly. I wanted to only display text when text is pressed, only image when image is pressed and so on .

Well, I'm happy with the program . Perhaps someday it can be an image viewer (dream-on) . Thanks a lot for the help mate. Could never get it to work without ya .

Here comes the full working code:

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Component;


public class MyProgram extends JFrame implements ActionListener{


	ImageIcon picture1  = new ImageIcon("mmx1.gif");		// load image1
	ImageIcon picture2  = new ImageIcon("mmx2.gif");		// load image2

	JLabel lb1 = new JLabel();								// a simple holder
	JScrollPane scroll  = new JScrollPane(lb1);				// place the image or text input in the container

	JTextField edit     = new JTextField("Megaman X");		// Textfield for user input

	// create buttons Image1, Image2 and Text
	JButton btn1 = new JButton("Image 1");
	JButton btn2 = new JButton("Image 2");
	JButton btn3 = new JButton("Text");

	// create menu components
	JMenuItem j1 = new JMenuItem("Close");
	JMenuItem j2 = new JMenuItem("Copy Text");
	JMenuItem j3 = new JMenuItem("Clean Field");


	// constructor
	public MyProgram(){

		super("My Hard-Coded Program");						// default title
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		// default close operation
		setSize(320,240);									// set a minimum size
		//setBounds (320,240,600,600);


		// add components to menubar
		JMenu m1 = new JMenu("File");
	    m1.add(j1);							// close
	    j1.addActionListener(this);

		JMenu m2 = new JMenu("Options");
		m2.add(j2);							// copy text
		j2.addActionListener(this);

		m2.add(j3);							// clear field
		j3.addActionListener(this);

		JMenuBar bar = new JMenuBar();
		bar.add(m1);
		bar.add(m2);

		// add listeners to the buttons Image1, Image2 and Text
		btn1.addActionListener(this);
		btn2.addActionListener(this);
		btn3.addActionListener(this);

		// create two panels
		// this holds the text field for user input
		JPanel pane1 = new JPanel();
		pane1.setLayout(new BorderLayout());
		pane1.add(edit, "Center");

		// this panel holds the button Image1, Image2 and Text
		JPanel pane2 = new JPanel();
		pane2.setLayout(new FlowLayout());
		pane2.add(btn1);
		pane2.add(btn2);
		pane2.add(btn3);

		// create an abstract container and place all the components
		Container container = getContentPane();
		setJMenuBar(bar);
		container.add(pane1,  "North");
		container.add(pane2,  "Center");
		container.add(scroll, "South");

		setVisible(true);		// makes it all visible
		//pack();	// makes it fit to the frame
	}


	void closeProgram(){
		System.exit(0);
	}

	void showImage1(){
		lb1.setIcon(picture1);
		pack();
	}


	void showImage2(){
		lb1.setIcon(picture2);
		pack();
	}


	void copyText(){
		String copyTxt = edit.getText();
		lb1.setText(copyTxt);
		pack();
	}


	void cleanText(){
		lb1.setText(" ");
	}


	// main comes in here
	public static void main (String[] arguments) {
		MyProgram testing = new MyProgram();
	}


	// taking care of user input
	public void actionPerformed (ActionEvent evt){

		Object source = evt.getSource();

		if (source == btn1) {

			showImage1();

		} else if (source == btn2) {
			showImage2();

		} else if (source == btn3) {

			copyText();

		} else if (source == j1) {

			closeProgram();

		} else if (source == j2) {

			copyText();

		} else if (source == j3) {

			cleanText();

		}

		//repaint();		// re-draw the hole screen
	}

}
Thanks again!
 
Old 02-05-2004, 12:35 PM   #7
Looking_Lost
Senior Member
 
Registered: Apr 2003
Location: Eire
Distribution: Slackware 12.0, OpenSuse 10.3
Posts: 1,120

Rep: Reputation: 45
if you add

lb1.setIcon(null);

to your copyText() method that'll get rid of the picture

and if you call cleanText() just before showImage1() and showImage2() that'll get rid of the text

Either way you're off the Java starting blocks now. The downloadable/online api docs on the sun site are a great resource.
 
Old 02-05-2004, 05:02 PM   #8
Mega Man X
LQ Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 65
Great mate. It simply works great now. You rock at this . Now I will concentrate myself at the api docs as you suggested (there's a down-loadable version for offline viewing) and turn this program, in a far away future, into an useful image viewer. It was way straight forward for my current Java knowledge, but it was really, really cool to do. If it was a game, I'd say I had a lot of fun playing it, but got a little upset to finish the game (more or less the way I felt when I finished Halo on the Xbox, you know, it simply was not the time to finish the game, it was just getting better and better...lol, what comparison...).

Thanks mate!. Cheers!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
a java-swing problem... shosh Programming 2 06-26-2009 05:38 AM
java swing JTextArea gauravbagga Programming 1 05-23-2005 04:34 AM
questions on my java/swing gui xviddivxoggmp3 Programming 6 07-19-2004 10:44 AM
missing java swing libraries? a1ghagh05t Programming 5 01-26-2004 06:04 AM
Cannot Get Swing to work in a Java Applet? Checkers Linux - Software 0 03-17-2003 03:23 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 11:11 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration