ADDING MORE ITEMS
Now its time to have a bit of fun. Lets add some other items and play with the logic.
Add some of these to your application:
JTextField:
JTextField is constructed the same way as others. Create an instance of JTextField, and set it's parameters.
public static JTextField textField; //Under main method: textField = new JTextField(); textField.setBounds(20,140,200,40); frame.add(textField);
- You can get the text from your box as follows
textField.getText();
".getText" returns a String to be used however you like.
DIY: Try having your button print the text in your JTextField to console.
JCheckBox:
Again, constructed the same way.
public static JCheckBox checkBox; //Under main method: checkBox = new JCheckBox(); checkBox.setBounds(20,180,200,40); frame.add(checkBox);
You can find if the box is selected in two ways.
if(checkBox.isSelected()){ // Do Something }
or
checkBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Do Something } });
DIY: Have your checkbox change the color of the button. You can change the buttons color with the following:
button.setBackgroundColor(Color.RED);
*Note - setting color to null sets back to default.
JLabel:
- Labels are your standard text objects.
Constructed the same way. JLabel takes a String argument.
public static JLabel label; //Under main method: label = new JLabel("Hello World!"); label.setBounds(20,220,200,40); frame.add(label);
- A label can be set by the following:
label.setText("Some new text here!");
- You can set the font like this:
label.setFont(new Font("Comic Sans MS", Font.BOLD, 16));
- DIY: Have your button, when pressed, set the label to the contents of your textField.
HAVE FUN: Have fun with your app. Make your button change position on click. Or change the colors of your objects. Experiment :D