• Log in or sign up for an account here: https://www.sythe.org/login

gui programming with java.swing

paladen

Guru
Banned
Joined
Jan 21, 2007
Sythe Gold
0
Messages
1,633
Age
34
Location
pennsylvania
gui programming with java.swing
reposted from old sythe.org, no clue who origanal maker was

Well, let's get started!
Make a new file and save it as TextButton.java.
Then, open up the file and add this:

Code:
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.*;
import java.awt.FlowLayout;
You might have guessed that all Swing components have a J in front of them. So if you want to add a button, use the JButton class!

Type this:
Code:
public class TextButton extends JFrame {Next, lets add our main() method, so we can run the program:

public static void main(String args[]) {
TextButton frame = new TextButton();
frame.setSize(500,300);
frame.setVisible(true);
}
I've already explained what this does, so lets move on.
Well create the constructor for our GUI, like so:

Code:
public TextButton() {
setLayout(new FlowLayout());
You should be familiar with this, we did it in the last tutorial! OK, lets add our textfield and button:
First, a JTextField:

Code:
final JTextField textfield = new JTextField(15);
add(textfield);

Now, a JButton:
Code:
JButton button = new JButton("butt0n!");
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
textfield.setText("z0mg! t3xtz0r!");
}
});
add(button);
OK, you probably haven't seen a lot of that coding before, and despite it's length, is very simple. It tells java, that when we click the button, to put some text into out textfield! Whatever you want to happen when you click the buttuon should go under "public static void actionPerformed(ActionEvent e) {".

We're almost done, but have to finish off our code. Add this:

Code:
}
}
And we should be good to go! Compile our program and watch it when it runs. Click the button and see what happens.

Well, that about wraps it up for this tutorial, stay tuned guys, there's more to come!

Let me know what you guys think!

COMPLETE TextButton.java FILE:

Code:
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.*;
import java.awt.FlowLayout;

public class TextButton extends JFrame {

public static void main(String args[]) {
TextButton frame = new TextButton();
frame.setSize(500,300);
frame.setVisible(true);
}

public TextButton() {
setLayout(new FlowLayout());
final JTextField textfield = new JTextField(15);
add(textfield);
JButton button = new JButton("butt0n!");
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
textfield.setText("z0mg! t3xtz0r!");
}
});
add(button);
}
}
 
gui programming with java.swing
put it in
Code:
brackets...
 
Runescape Gamblingrunescape gambling
Back
Top