Menampilkan Checkbox di Java

Contoh program java berikut ini mendemokan bagaimana penanganan checkbox di java. Bukan hanya bagaimana membuat object checkbox dengan class JCheckBox, namun juga contoh penanganan event dengan ItemListener.

Berikut ini tampilannya:

Berikut ini contoh programnya:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class CheckBoxTest extends JFrame {

	private JTextField text;

	private JCheckBox bold, italic, merah;

	public CheckBoxTest() {

		super ("Mencoba CheckBox");

		Container container = getContentPane ();

		container.setLayout(new FlowLayout());

		text = new JTextField ("Lab. Bahasa Pemrograman 3", 20);

		text.setFont(new Font ("Arial", Font.PLAIN, 14));

		text.setForeground(Color.BLACK);

		text.setBackground(Color.WHITE);

		text.setEditable(false);

		container.add(text);

		bold = new JCheckBox ("Bold");

		container.add(bold);

		italic = new JCheckBox ("Italic");

		container.add(italic);

		merah = new JCheckBox ("Merah");

		container.add(merah);

		CheckBoxHandler atur = new CheckBoxHandler();

		bold.addItemListener(atur);

		italic.addItemListener(atur);

		merah.addItemListener(atur);

		setSize (275,100);

		setLocationRelativeTo(null);

		setVisible(true);

	}

	public static void main (String args[]) {

		CheckBoxTest test = new CheckBoxTest();

		test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

	//inner class

	private class CheckBoxHandler implements ItemListener {

		private int valBold = Font.PLAIN;

		private int valItalic = Font.PLAIN;

		private Color valMerah = Color.BLACK;

		//method untuk menangani checkbox event

		public void itemStateChanged(ItemEvent e) {

			if (e.getSource() == bold) {

				valBold = bold.isSelected() ? Font.BOLD : Font.PLAIN;

			}

			if (e.getSource() == italic) {

				valItalic = italic.isSelected() ? Font.ITALIC : Font.PLAIN;

			}

			text.setFont(new Font ("Arial",valBold + valItalic, 14) );

			if (e.getSource() == merah) {

				valMerah = merah.isSelected() ? Color.RED : Color.BLACK;	

			}

			text.setForeground(valMerah);

		}

	} //end of inner class

} //end of class CheckBoxTest

Semoga bermanfaat

0 votes, average: 0.00 out of 50 votes, average: 0.00 out of 50 votes, average: 0.00 out of 50 votes, average: 0.00 out of 50 votes, average: 0.00 out of 5 (0 votes, average: 0.00 out of 5)
You need to be a registered member to rate this post.
Loading ... Loading ...
Java, Java Swing

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

3 Responses to “Menampilkan Checkbox di Java”

Leave Comment

(required)

(required)


// Place This Code At The End Or After All Ad Zone Div Created