You are on page 1of 49

Tugas Pemograman 2

Komponen Swing
MATA KULIAH : PEMOGRAMAN 2
DOSEN PENGAMPU : ADI DEWANTO

DISUSUN OLEH :
Claudia Oktaviani SP

(14520241005)

Agung Subastian

(14520241009)

Rita Septiana

(14520241017)

Maulidina Achmad

(14520241027)

Arif Sulistya

(14520241036)

PROGRAM STUDI PENDIDIKAN TEKNIK INFORMATIKA


JURUSAN PENDIDIKAN TEKNIK ELEKTRONIKA
FAKULTAS TEKNIK
UNIVERSITAS NEGERI YOGYAKARTA
2015

1. JPanel
JPanel adalah versi swing tentang Panel kelas AWT dan menggunakan tata letak
standar yang sama, FlowLayout. JPanel adalah keturunan langsung dari JComponent.
Contoh Program:
import javax.swing.*;
public class Panel {
public static void main(String[] args) {
JFrame f = new JFrame("JPanelExample");
JPanel p = new JPanel();
JButton b = new JButton("Button");
p.add(b);
f.setContentPane(p);
f.show();
f.setSize(300,100);
}
}
Tampilan:

2. JScrollPane
Scroll pane merupakan tombol penggulung yan letakkanya pasti secara horizontal
maupun vertical berbeda dengan scrollbar.
Contoh Program:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class ScrollPane extends JFrame {
JScrollPane scrollpane;
public ScrollPane() {
super("JScrollPaneExample");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
init();
setVisible(true);
}
public void init() {
JRadioButton form[][] = new JRadioButton[12][5];

String counts[] = { "", "0-1", "2-5", "6-10", "11-100", "101+" };


String categories[] = { "Household", "Office", "Extended Family",
"Company (US)", "Company (World)", "Team", "Will",
"Birthday Card List", "High School", "Country", "Continent",
"Planet" };
JPanel p = new JPanel();
p.setSize(600, 400);
p.setLayout(new GridLayout(13, 6, 10, 0));
for (int row = 0; row < 13; row++) {
ButtonGroup bg = new ButtonGroup();
for (int col = 0; col < 6; col++) {
if (row == 0) {
p.add(new JLabel(counts[col]));
} else {
if (col == 0) {
p.add(new JLabel(categories[row - 1]));
} else {
form[row - 1][col - 1] = new JRadioButton();
bg.add(form[row - 1][col - 1]);
p.add(form[row - 1][col - 1]);
}
}
}
}
scrollpane = new JScrollPane(p);
getContentPane().add(scrollpane, BorderLayout.CENTER);
}
public static void main(String args[]) {
new ScrollPane();
}
}

Tampilan:

3. JTabbedPane
Turuanan JComponent. Yang memiliki fungsi membuat beberapa pane dalam suatu
frame.
Contoh Program:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class JTabbedPaneExample extends JFrame {
public static void main( String[] argv ) {
JTabbedPaneExample myExample = new JTabbedPaneExample( "Contoh
JTabbedPane" );
}
public JTabbedPaneExample( String title ) {
super( title );
setSize( 150, 150 );
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent we ) {
dispose();
System.exit( 0 );
}
} );
init();
pack();
setVisible( true );
}
private void init() {
JTabbedPane jtb = new JTabbedPane();
for( int i = 1; i < 4; i++ ) {
ImageIcon icon = new ImageIcon( i + ".gif" );

JTextArea jta = new JTextArea( 20, 40 );


jta.setText( "This is text within tab number " + i );
JScrollPane jsp = new JScrollPane( jta );
jtb.addTab( i + "-tab", icon, jsp );
}
getContentPane().add( jtb );
jtb.setBorder( BorderFactory.createEtchedBorder() );
}
}
Tampilan:

4. JRootPane
Root pane merupakan layer yang berada di terletak antara layered pane dan frame
sehingga root pane memiliki fungsi yang sama dengan layered pane ataupun content pane
dan glass pane.
Contoh Program:
import javax.swing.*;
import javax.swing.border.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
/*
* RootLayeredPaneExample.java requires images/dukeWaveRed.gif.
*/
public class RootLayeredPaneExample extends JPanel
implements ActionListener,
MouseMotionListener {
private int[] layers = {-30000, 0, 301};

private String[] layerStrings = { "Yellow (-30000)",


"Magenta (0)",
"Cyan (301)" };
private Color[] layerColors = { Color.yellow,
Color.magenta,
Color.cyan };
private JLayeredPane layeredPane;
private JLabel dukeLabel;
private JCheckBox onTop;
private JComboBox layerList;
//Action commands
private static String ON_TOP_COMMAND = "ontop";
private static String LAYER_COMMAND = "layer";
//Adjustments to put Duke's toe at the cursor's tip.
private static final int XFUDGE = 40;
private static final int YFUDGE = 57;
//Initial layer of dukeLabel.
private static final int INITIAL_DUKE_LAYER_INDEX = 1;
public RootLayeredPaneExample(JLayeredPane layeredPane)
super(new GridLayout(1,1));

//Create and load the duke icon.


final ImageIcon icon = createImageIcon("images/dukeWaveRed.gif");
//Create and set up the layered pane.
this.layeredPane = layeredPane;
layeredPane.addMouseMotionListener(this);
//This is the origin of the first label added.
Point origin = new Point(10, 100);
//This is the offset for computing the origin for the next label.
int offset = 35;
//Add several overlapping, colored labels to the layered pane
//using absolute positioning/sizing.
for (int i = 0; i < layerStrings.length; i++) {
JLabel label = createColoredLabel(layerStrings[i],
layerColors[i], origin);
layeredPane.add(label, new Integer(layers[i]));
origin.x += offset;

origin.y += offset;
}
//Create and add the Duke label to the layered pane.
dukeLabel = new JLabel(icon);
if (icon != null) {
dukeLabel.setBounds(15, 225,
icon.getIconWidth(),
icon.getIconHeight());
} else {
System.err.println("Duke icon not found; using black square instead.");
dukeLabel.setBounds(15, 225, 30, 30);
dukeLabel.setOpaque(true);
dukeLabel.setBackground(Color.BLACK);
}
layeredPane.add(dukeLabel,
new Integer(layers[INITIAL_DUKE_LAYER_INDEX]),
0);
//Add control pane to this JPanel.
add(createControlPanel());
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = RootLayeredPaneExample.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
//Create and set up a colored label.
private JLabel createColoredLabel(String text,
Color color,
Point origin) {
JLabel label = new JLabel(text);
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(color);
label.setForeground(Color.black);
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.setBounds(origin.x, origin.y, 140, 140);

return label;
}
//Create the control pane for the top of the frame.
private JPanel createControlPanel() {
onTop = new JCheckBox("Top Position in Layer");
onTop.setSelected(true);
onTop.setActionCommand(ON_TOP_COMMAND);
onTop.addActionListener(this);
layerList = new JComboBox(layerStrings);
layerList.setSelectedIndex(INITIAL_DUKE_LAYER_INDEX);
layerList.setActionCommand(LAYER_COMMAND);
layerList.addActionListener(this);
JPanel controls = new JPanel();
controls.add(layerList);
controls.add(onTop);
controls.setBorder(BorderFactory.createTitledBorder(
"Choose Duke's Layer and Position"));
return controls;
}
//Make Duke follow the cursor.
public void mouseMoved(MouseEvent e) {
dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE);
}
public void mouseDragged(MouseEvent e) {} //do nothing
//Handle user interaction with the check box and combo box.
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (ON_TOP_COMMAND.equals(cmd)) {
if (onTop.isSelected())
layeredPane.moveToFront(dukeLabel);
else
layeredPane.moveToBack(dukeLabel);
} else if (LAYER_COMMAND.equals(cmd)) {
int position = onTop.isSelected() ? 0 : -1;
layeredPane.setLayer(dukeLabel,
layers[layerList.getSelectedIndex()],
position);
}
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("RootLayeredPaneExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
RootLayeredPaneExample newContentPane = new RootLayeredPaneExample(
frame.getLayeredPane());
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.setSize(new Dimension(300, 350));
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Tampilan:

5. JInternalFrame
berfungsi seperti JFrame tapi di gunakan untuk Form Child(form terdapat form di
dalamnya lagi).
Contoh Program:
import javax.swing.JInternalFrame;
import javax.swing.JDesktopPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JFrame;
import java.awt.event.*;
import java.awt.*;
public class JInternalFrameExample extends JFrame {
JDesktopPane jdpDesktop;
static int openFrameCount = 0;
public JInternalFrameExample() {
super("JInternalFrameExample");
// Make the main window positioned as 50 pixels from each edge of the
// screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2,
screenSize.height - inset * 2);

// Add a Window Exit Listener


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Create and Set up the GUI.
jdpDesktop = new JDesktopPane();
// A specialized layered pane to be used with JInternalFrames
createFrame(); // Create first window
setContentPane(jdpDesktop);
setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode",
"outline");
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Frame");
menu.setMnemonic(KeyEvent.VK_N);
JMenuItem menuItem = new JMenuItem("New IFrame");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createFrame();
}
});
menu.add(menuItem);
menuBar.add(menu);
return menuBar;
}
protected void createFrame() {
MyInternalFrame frame = new MyInternalFrame();
frame.setVisible(true);
// Every JInternalFrame must be added to content pane using
JDesktopPane
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String[] args) {
JInternalFrameExample frame = new JInternalFrameExample();

frame.setVisible(true);
}
class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame() {
super("IFrame #" + (++openFrameCount), true, // resizable
true, // closable
true, // maximizable
true);// iconifiable
setSize(300, 300);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition
* openFrameCount);
}
}
}
Tampilan:

6. JSplitPane
JSplitPane adalah membagi 2 komponen dalam Frame Java,Dua Komponen grafis
dibagi berdasarkan tampilan dan implementasi, dan dua komponennya dapat diubah
ukurannya secara interaktif oleh user/pengguna.
Contoh Program:
import java.awt.*;
import javax.swing.*;
public class SplitPane extends JFrame
{
Container konten = getContentPane();
private JLabel lblText,lblPratinjau,lblPreviewGambar,lblGambar;
private JTextField txtText;

private JButton btnCari;


private JTextArea ta1,ta2;
private JPanel panel1,panel2,panel3,panelGambar;
private JSplitPane vSplit,hSplit1,hSplit2;
private JScrollPane pane;
private ImageIcon gambar;
//Membuat Konstruktor
public SplitPane()
{
setTitle("Membuat SplitPane");
setSize(700,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); //Mengatur Tampilan Frame di tengah
lblText = new JLabel("Text");
lblPratinjau = new JLabel("Pratinjau");
lblPreviewGambar = new JLabel("Preview Gambar");
txtText = new JTextField(" " ,20);
btnCari = new JButton("Cari");
ta1 = new JTextArea();
ta2 = new JTextArea();
//Panel1
panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(lblText,BorderLayout.WEST); //Mengatur lblText tampil di kiri
panel1.add(txtText,BorderLayout.CENTER); //Mengatur txtText tampil di tengah
panel1.add(btnCari,BorderLayout.EAST); //Mengatur btnCari tampil di kanan
pane = new JScrollPane();
pane.add(ta1);
//Mengatur bagian yang akan dibagi(split)
hSplit1 = new JSplitPane();
hSplit1.setOrientation(JSplitPane.VERTICAL_SPLIT);
hSplit1.setTopComponent(panel1);
hSplit1.setBottomComponent(pane);
//Panel2
panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
panel2.add(lblPratinjau,BorderLayout.NORTH); //Mengatur lblPratinjau tampil di
atas
panel2.add(ta2,BorderLayout.CENTER); //Mengatur TextArea2 tampil di tengah

//Panel3
panel3 = new JPanel();
panel3.setLayout(new BorderLayout());
panel3.add(lblPreviewGambar,BorderLayout.NORTH);
lblGambar = new JLabel();
lblGambar.setIcon(new ImageIcon("src/D/IMG_20150421_085004.jpg"));
panel3.add(lblGambar,BorderLayout.CENTER);
//Mengatur bagian yang akan dibagi
hSplit2 = new JSplitPane();
hSplit2.setOrientation(JSplitPane.VERTICAL_SPLIT);
hSplit2.setTopComponent(panel2);
hSplit2.setBottomComponent(panel3);
vSplit = new JSplitPane();
vSplit.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
vSplit.setTopComponent(hSplit1);
vSplit.setBottomComponent(hSplit2);
konten.add(vSplit);
} //Akhir Konstruktor
public static void main(String[] ar)
{
new SplitPane();
}
}
Tampilan:

7. JLayeredPane
Merupakan wadah komponen yang membolehkan komponen-konponen
didalamnya secara bersamaan
Contoh Program:
import javax.swing.*;
import javax.swing.border.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
public class LayeredPaneDemo extends JPanel
implements ActionListener,
MouseMotionListener {
private String[] layerStrings = { "Yellow (0)", "Magenta (1)",
"Cyan (2)", "Red (3)",
"Green (4)" };
private Color[] layerColors = { Color.yellow, Color.magenta,
Color.cyan, Color.red,
Color.green };
private JLayeredPane layeredPane;
private JLabel dukeLabel;
private JCheckBox onTop;
private JComboBox layerList;
//Action commands
private static String ON_TOP_COMMAND = "ontop";
private static String LAYER_COMMAND = "layer";

//Adjustments to put Duke's toe at the cursor's tip.


private static final int XFUDGE = 40;
private static final int YFUDGE = 57;
public LayeredPaneDemo() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
//Create and load the duke icon.
final ImageIcon icon = createImageIcon("images/dukeWaveRed.gif");
//Create and set up the layered pane.
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(300, 310));
layeredPane.setBorder(BorderFactory.createTitledBorder(
"Move the Mouse to Move Duke"));
layeredPane.addMouseMotionListener(this);
//This is the origin of the first label added.
Point origin = new Point(10, 20);
//This is the offset for computing the origin for the next label.
int offset = 35;
//Add several overlapping, colored labels to the layered pane
//using absolute positioning/sizing.
for (int i = 0; i < layerStrings.length; i++) {
JLabel label = createColoredLabel(layerStrings[i],
layerColors[i], origin);
layeredPane.add(label, new Integer(i));
origin.x += offset;
origin.y += offset;
}
//Create and add the Duke label to the layered pane.
dukeLabel = new JLabel(icon);
if (icon != null) {
dukeLabel.setBounds(15, 225,
icon.getIconWidth(),
icon.getIconHeight());
} else {
System.err.println("Duke icon not found; using black square instead.");
dukeLabel.setBounds(15, 225, 30, 30);
dukeLabel.setOpaque(true);
dukeLabel.setBackground(Color.BLACK);
}

layeredPane.add(dukeLabel, new Integer(2), 0);


//Add control pane and layered pane to this JPanel.
add(Box.createRigidArea(new Dimension(0, 10)));
add(createControlPanel());
add(Box.createRigidArea(new Dimension(0, 10)));
add(layeredPane);
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = LayeredPaneDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
//Create and set up a colored label.
private JLabel createColoredLabel(String text,
Color color,
Point origin) {
JLabel label = new JLabel(text);
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(color);
label.setForeground(Color.black);
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.setBounds(origin.x, origin.y, 140, 140);
return label;
}
//Create the control pane for the top of the frame.
private JPanel createControlPanel() {
onTop = new JCheckBox("Top Position in Layer");
onTop.setSelected(true);
onTop.setActionCommand(ON_TOP_COMMAND);
onTop.addActionListener(this);
layerList = new JComboBox(layerStrings);
layerList.setSelectedIndex(2); //cyan layer
layerList.setActionCommand(LAYER_COMMAND);
layerList.addActionListener(this);

JPanel controls = new JPanel();


controls.add(layerList);
controls.add(onTop);
controls.setBorder(BorderFactory.createTitledBorder(
"Choose Duke's Layer and Position"));
return controls;
}
//Make Duke follow the cursor.
public void mouseMoved(MouseEvent e) {
dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE);
}
public void mouseDragged(MouseEvent e) {} //do nothing
//Handle user interaction with the check box and combo box.
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (ON_TOP_COMMAND.equals(cmd)) {
if (onTop.isSelected())
layeredPane.moveToFront(dukeLabel);
else
layeredPane.moveToBack(dukeLabel);
} else if (LAYER_COMMAND.equals(cmd)) {
int position = onTop.isSelected() ? 0 : 1;
layeredPane.setLayer(dukeLabel,
layerList.getSelectedIndex(),
position);
}
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("LayeredPaneExamPle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new LayeredPaneDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);

}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Tampilan:

8. JOptionPane
Turunan Jcomponent. Disediakan untuk mempermudah menampilkan pop- up
kotak dialog.
Contoh Program:
import javax.swing.*;
public class OptionTampilan {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,"JOptionPane","JOptionPaneExample",JOptionPa
ne.INFORMATION_MESSAGE);
}

}
Tampilan:

9. JLabel
JLabel, keturunan dari JComponent, digunakan untuk membuat label teks.
Contoh Program:
import javax.swing.*;
public class Label {
public static void main(String[] args) {
JFrame f = new JFrame("JLabelExample");
JPanel p = new JPanel();
JLabel b = new JLabel("Label");
b.setBounds(10, 10, 270, 10);
p.add(b);
f.setContentPane(p);
f.show();
f.setSize(300,100);
}
}
Tampilan :

10. JComboBox
Turunan Jcomponent. Yang berfungsi untuk memberikan list pada pilihan box
Contoh Program:
import javax.swing.*;
public class ComboBox {
public static void main(String[] args) {
JFrame f = new JFrame("JComboBoxExample");
JPanel p = new JPanel();
// JComboBox(String nama)
String[] menu = {"Nasi","Ayam","Goreng"};
JComboBox b = new JComboBox(menu);
p.add(b);

f.setContentPane(p);
f.show();
f.setSize(300,100);
}
}
Tampilan:

11. JMenuBar
JMenuBar dapat berisi beberapa JMenu ini. Setiap JMenu dapat berisi
serangkaian JMenuItem 's yang dapat Anda pilih. Ayunan menyediakan dukungan
untuk pull-down dan menu popup.
Contoh Program:
import javax.swing.*;
public class MenuBar {
public static void main(String[] args) {
JFrame f = new JFrame("JMenuBarExample");
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem menuItem = new JMenuItem("Menu Item");
menuBar.add(menu);
menu.add(menuItem);
f.setContentPane(menuBar);
f.show();
f.setSize(300,100);
}
}
Tampilan :

12. JToolBar
JToolbar berisi sejumlah komponen yang jenis ini biasanya beberapa jenis tombol
yang juga dapat mencakup pemisah pada komponen grup terkait dalam toolbar.
Contoh Program :
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
public class JToolBarExample extends JFrame {
protected JTextArea textArea;
protected String newline = "\n";
public JToolBarExample() {
//Do frame stuff.
super("Contoh JToolBar");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
addButtons(toolBar);
textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the content pane.
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.setPreferredSize(new Dimension(400, 100));
contentPane.add(toolBar, BorderLayout.NORTH);
contentPane.add(scrollPane, BorderLayout.CENTER);
setContentPane(contentPane);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
button = new JButton(new ImageIcon("images/left.gif"));
button.setToolTipText("This is the left button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayResult("Action for first button");
}
});
toolBar.add(button);
button = new JButton(new ImageIcon("images/middle.gif"));
button.setToolTipText("This is the middle button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

displayResult("Action for second button");


}
});
toolBar.add(button);
button = new JButton(new ImageIcon("images/right.gif"));
button.setToolTipText("This is the right button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayResult("Action for third button");
}
});
toolBar.add(button);
toolBar.addSeparator();
button = new JButton("Another button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayResult("Action for fourth button");
}
});
toolBar.add(button);
JTextField textField = new JTextField("A text field");
toolBar.add(textField);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
}
public static void main(String[] args) {
JToolBarExample frame = new JToolBarExample();
frame.pack();
frame.setVisible(true);
}
}
Tampilan :

13. JProgressBar
Progress bar menampilkan grafik yang menggambarkan beberapa lama suatu
proses akan selesai.
Contoh Progam:
import javax.swing.*;
import java.awt.*;
public class Progress {
private JProgressBar JP;
private JFrame frame;
private JPanel panel;
public static void main(String[] args) {
new Progress();
}
public Progress() {
frame = new JFrame("JProgressBarExample");
panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 55));
JP = new JProgressBar(0, 200);
JP.setStringPainted(true);
panel.add(JP);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
Task();
}
public void Task() {
for (int i = 0; i <= 200; i++) {
try {
JP.setValue(i);
Thread.sleep(50);
} catch (Exception e) {

}
}
}
}
Tampilan:

14. JSlider
Slider digunakan untuk menentukan nilai dengan cara menggeser control dalam
rentang nilai minimum yang telah ditentukan. Secara default, slider berbentuk horizontal.
Contoh Program:
import javax.swing.*;
import java.awt.*;
public class Slider {
public static void main(String[] args) {
final JFrame frame = new JFrame("JSliderExample");
// create a slider
JSlider slider = new JSlider(JSlider.VERTICAL, 0, 40, 10);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setLabelTable(slider.createStandardLabels(10));
//
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 300);
frame.getContentPane().add(slider);
frame.setVisible(true);
}
}
Tampilan:

15. JScrollBar
Implementasi batang gulungan. Dimana gulungan atau scroll ini kita bisa atur
letaknya yaitu horizontal ataupun vertical atau juga bisa kedua-duannya.
Contoh Program:
import javax.swing.*;
import java.awt.*;
public class ScroolBar {
public static void main(String[] args) {
final JFrame frame = new JFrame("JScrollBarExample");
final JLabel label = new JLabel("ScrollBar Vertical" );
JScrollBar vbar=new JScrollBar(JScrollBar.VERTICAL, 20, 40, 0, 500);
frame.setLayout(new BorderLayout( ));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
frame.getContentPane().add(label);
frame.getContentPane().add(vbar, BorderLayout.EAST);
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.setVisible(true);
}
}
Tampilan:

16. JPopupMenu
JPopupMenu digulir adalah menu popup digulir yang dapat digunakan setiap kali
kita memiliki begitu banyak item dalam menu popup yang melebihi ketinggian layar
terlihat.
Contoh Program :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JPopupMenuExample extends JFrame
{
private JRadioButtonMenuItem items[];
private Color colorValues[] = { Color.blue, Color.yellow, Color.red };
public JPopupMenuExample()
{
super( "Contoh PopupMenu" );
final JPopupMenu popupMenu = new JPopupMenu();
ItemHandler handler = new ItemHandler();
String colors[] = { "Blue", "Yellow", "Red" };
ButtonGroup colorGroup = new ButtonGroup();
items = new JRadioButtonMenuItem[ 3 ];
// construct each menu item and add to popup menu; also
// enable event handling for each menu item
for ( int i = 0; i < items.length; i++ )
{
items[ i ] = new JRadioButtonMenuItem( colors[ i ] );
popupMenu.add( items[ i ] );
colorGroup.add( items[ i ] );
items[ i ].addActionListener( handler );
}
getContentPane().setBackground( Color.white );

// define a MouseListener for the window that displays


// a JPopupMenu when the popup trigger event occurs
addMouseListener( new MouseAdapter()
{
public void mousePressed( MouseEvent e )
{
checkForTriggerEvent( e );
}
public void mouseReleased( MouseEvent e )
{
checkForTriggerEvent( e );
}
private void checkForTriggerEvent( MouseEvent e )
{
if ( e.isPopupTrigger() )
popupMenu.show( e.getComponent(), e.getX(), e.getY() );
}
} );
setSize( 300, 200 );
show();
}
public static void main( String args[] )
{
JPopupMenuExample app = new JPopupMenuExample();
app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
});
}
private class ItemHandler implements ActionListener
{
public void actionPerformed( ActionEvent e )
{
// determine which menu item was selected
for ( int i = 0; i < items.length; i++ )
if ( e.getSource() == items[ i ] )
{

getContentPane().setBackground( colorValues[ i ] );
repaint();
return;
}
}
}
}
Tampilan :

17. JFileChooser
Mengijinkan pengguna untuk memilih sebuah file. Korespondensi pada filechooser
class dalam package AWT
Contoh Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class FileChooser {
public static void main(String[] args) {
final JFrame frame = new JFrame("JFileChooserExample");
final JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setCurrentDirectory(new File("C:\\tmp"));
JButton btn1 = new JButton("Show Dialog");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.showDialog(frame, "Choose");
}

});
JButton btn2 = new JButton("Show Open Dialog");
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int retVal = fc.showOpenDialog(frame);
if (retVal == JFileChooser.APPROVE_OPTION) {
File[] selectedfiles = fc.getSelectedFiles();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < selectedfiles.length; i++) {
sb.append(selectedfiles[i].getName() + "\n");
}
JOptionPane.showMessageDialog(frame, sb.toString());
}
}
});
JButton btn3 = new JButton("Show Save Dialog");
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.showSaveDialog(frame);
}
});
Container pane = frame.getContentPane();
pane.setLayout(new GridLayout(3, 1, 10, 10));
pane.add(btn1);
pane.add(btn2);
pane.add(btn3);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Tampilan:

18. JColorChooser
Turunan Jcomponent. Mengijinkan pengguna untuk memilih warna
Contoh Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class ColorChooser {
public static void main(String[] args) {
final JFrame frame = new JFrame("JColorChooserExample");
JButton btn1 = new JButton("Pilih Warna");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color newColor = JColorChooser.showDialog(
frame,
"Pilih Warna Background",
frame.getBackground());
if(newColor != null){
frame.getContentPane().setBackground(newColor);
}
}
});
Container pane = frame.getContentPane();
pane.setLayout(new FlowLayout());
pane.add(btn1);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Tampilan:

19. JTree
Untuk menampilkan data dengan tipe hierarki.
Contoh Program :
import javax.swing.tree.*;
import javax.swing.*;
import java.awt.*;
public class JTreeExample extends JFrame
{
public static void main(String[] args)
{
JTreeExample obj=new JTreeExample();
obj.setTitle("Contoh JTree");
obj.setSize(350,500);
obj.setVisible(true);
}
public JTreeExample()
{
try
{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}

catch(Exception exception)
{
exception.printStackTrace();
}
JPanel panel =new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
DefaultMutableTreeNode top=new DefaultMutableTreeNode("Library");
DefaultMutableTreeNode branch1=new
DefaultMutableTreeNode("Comics");
DefaultMutableTreeNode branch2=new
DefaultMutableTreeNode("History");
DefaultMutableTreeNode branch3=new
DefaultMutableTreeNode("Scientific");
//adding to the topmost node
top.add(branch1);
top.add(branch2);
top.add(branch3);
//adding to the First branch
DefaultMutableTreeNode node1_b1=new DefaultMutableTreeNode("Tom
and Jerry");
DefaultMutableTreeNode node2_b1=new
DefaultMutableTreeNode("Simpsons");
branch1.add(node1_b1);
branch1.add(node2_b1);
//adding to the Second branch
DefaultMutableTreeNode node1_b2=new DefaultMutableTreeNode("The
Great History of Aruna Kumar Reddy");
DefaultMutableTreeNode node2_b2=new
DefaultMutableTreeNode("Chanakya");
DefaultMutableTreeNode node3_b2=new
DefaultMutableTreeNode("Changhiz Khan");
branch2.add(node1_b2);
branch2.add(node2_b2);
branch2.add(node3_b2);
//adding to the Third branch
DefaultMutableTreeNode node1_b3=new
DefaultMutableTreeNode("Physical");
DefaultMutableTreeNode node2_b3=new
DefaultMutableTreeNode("Biological");

DefaultMutableTreeNode n1_node2_b3=new
DefaultMutableTreeNode("Animal Science");
DefaultMutableTreeNode n2_node2_b3=new
DefaultMutableTreeNode("Plant Science");
node2_b3.add(n1_node2_b3);
node2_b3.add(n2_node2_b3);
DefaultMutableTreeNode node3_b3=new
DefaultMutableTreeNode("Chemical");
branch3.add(node1_b3);
branch3.add(node2_b3);
branch3.add(node3_b3);
ImageIcon icon=new ImageIcon("abook.gif");
JTree tree=new JTree(top,true);
tree.setToolTipText(" and ");
panel.add(tree);
getContentPane().add(panel);
}
}
Tampilan :

20. JTable
JTable adalah class pada aplikasi Swing yang digunakan untuk menampilkan data
dalam format tabel.

Contoh Program:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class JTableExample extends JFrame {
String data[][] = {{"John", "Sutherland", "Student"},
{"George", "Davies", "Student"},
{"Melissa", "Anderson", "Associate"},
{"Stergios", "Maglaras", "Developer"},
};
String fields[] = {"Name", "Surname", "Status"};
public static void main( String[] argv ) {
JTableExample myExample = new JTableExample( "JTableExample" );
}
public JTableExample( String title ) {
super( title );
setSize( 150, 150 );
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent we ) {
dispose();
System.exit( 0 );
}
} );
init();
pack();
setVisible( true );
}
private void init() {
JTable jt = new JTable( data, fields );
JScrollPane pane = new JScrollPane( jt );
getContentPane().add( pane );
}
}
Tampilan:

21. JList
List merupakan daftar pilihan yang ditampilkan sekaligus. Pengguna program
dapat memebuat beberapa pilihan dari daftar yang di tampilkan.
Contoh Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class List {
public static void main(String[] args) {
final int MAX = 50;
// initialize list elements
String[] listElems = new String[MAX];
for (int i = 0; i < MAX; i++) {
listElems[i] = "List Data ke-" + i;
}
final JList list = new JList(listElems);

final JScrollPane pane = new JScrollPane(list);


final JFrame frame = new JFrame("JListExample");
// create a button and add action listener
final JButton btnGet = new JButton("Ambil Pilihan");
btnGet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedElem = "";
int selectedIndices[] = list.getSelectedIndices();
for (int j = 0; j < selectedIndices.length; j++) {
String elem =
(String) list.getModel().getElementAt(selectedIndices[j]);
selectedElem += "\n" + elem;
}
JOptionPane.showMessageDialog(frame,
"Data Yang Kamu Pilih:" + selectedElem);
}// end actionPerformed
});
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(pane, BorderLayout.CENTER);
frame.getContentPane().add(btnGet, BorderLayout.SOUTH);
frame.setSize(250, 200);
frame.setVisible(true);
}
}
Tampilan:

22. JTextComponent
a) JTextField
Text field merupakan area yang terdapat menampung tulisan yang di ketik
pengguna program.
i. JPasswordFiel
Password field hampir sama seperti text field, namun isi tulisan
disembunyikan.
Contoh Program:

Tampilan:

ii.

JFormattedTextField
Subclass dari JTextField yang mendukung format nilai yang bisa
kita tentukan sendiri format tersebut .
Contoh Program:

Tampilan:

b) JTextArea
Text area merupakan tempat pengeditan teks yang dapat menampung lebih
dari satu baris.
Contoh Program:

Tampilan:

c) JTextEditor
i. JTextPane
Menciptakan panel teks .Sehingga sebuah opsi argument dapat
menentukan model teks panel ini dan akan merubah bentuk teks tersebut
Contoh Program:
import java.awt.*;

import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextPaneExample extends JFrame
{
public TextPaneExample()
{
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// Set alignment to be centered for all paragraphs
MutableAttributeSet standard = new SimpleAttributeSet();
StyleConstants.setAlignment(standard,
StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, 0, standard, true);
// Define a keyword attribute
MutableAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.red);
StyleConstants.setItalic(keyWord, true);
// Add initial text
textPane.setText( "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n" );
// Highlight some keywords
doc.setCharacterAttributes(0, 3, keyWord, false);
doc.setCharacterAttributes(19, 4, keyWord, false);
// Add some text
try
{
doc.insertString(0, "Start of text\n", null );
doc.insertString(doc.getLength(), "End of text\n", keyWord );
}
catch(Exception e)
{}
// Add text pane to frame
JScrollPane scrollPane = new JScrollPane( textPane );
scrollPane.setPreferredSize( new Dimension( 200, 200 ) );
getContentPane().add( scrollPane );
// Add a bold button
JButton button = new JButton("bold");
getContentPane().add(button, BorderLayout.SOUTH);
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new StyledEditorKit.BoldAction().actionPerformed(null);
}

});
}
public static void main(String[] args)
{
TextPaneExample frame = new TextPaneExample();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setTitle("TextPaneExample");
frame.setVisible(true);
}
}

Tampilan:

23. AbstractButton
a) JToggleButton
Mengimplementasikan dua keadaan button yang diseleksi atau tidak.
i. JCheckBox
Check box dapat di gunakan untuk membuat beberapa pilihan
sekaligus.
Contoh Program:

Tampilan:

ii.

JRadioButton
Radio buttons digunakan untuk membuat satu pilihan dari sekian
banyak pilihan yang tersedia.
Contoh Program :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButtonExample extends JFrame
{
private JTextField t;
private Font plainFont, boldFont,
italicFont, boldItalicFont;
private JRadioButton plain, bold, italic, boldItalic;
private ButtonGroup radioGroup;
public JRadioButtonExample()
{
super( "Contoh RadioButton" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
t = new JTextField( "Watch the font style change", 25 );
c.add( t );
// Create radio buttons
plain = new JRadioButton( "Plain", true );
c.add( plain );

bold = new JRadioButton( "Bold", false);


c.add( bold );
italic = new JRadioButton( "Italic", false );
c.add( italic );
boldItalic = new JRadioButton( "Bold/Italic", false );
c.add( boldItalic );
// register events
RadioButtonHandler handler = new RadioButtonHandler();
plain.addItemListener( handler );
bold.addItemListener( handler );
italic.addItemListener( handler );
boldItalic.addItemListener( handler );
// create logical relationship between JRadioButtons
radioGroup = new ButtonGroup();
radioGroup.add( plain );
radioGroup.add( bold );
radioGroup.add( italic );
radioGroup.add( boldItalic );
plainFont = new Font( "TimesRoman", Font.PLAIN, 14 );
boldFont = new Font( "TimesRoman", Font.BOLD, 14 );
italicFont = new Font( "TimesRoman", Font.ITALIC, 14 );
boldItalicFont = new Font( "TimesRoman", Font.BOLD +
Font.ITALIC, 14 );
t.setFont( plainFont );
setSize( 300, 100 );
show();
}
public static void main( String args[] )
{
JRadioButtonExample app = new JRadioButtonExample();
app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
private class RadioButtonHandler implements ItemListener
{
public void itemStateChanged( ItemEvent e )

{
if ( e.getSource() == plain )
t.setFont( plainFont );
else if ( e.getSource() == bold )
t.setFont( boldFont );
else if ( e.getSource() == italic )
t.setFont( italicFont );
else if ( e.getSource() == boldItalic )
t.setFont( boldItalicFont );
t.repaint();
}
}
}
Tampilan :

b) JButton
Tombol merupakan komponen GUI yang menyerupai tombol. Ketika
tombol ini diklik, perintah tertentu akan dijalankan.
Contoh Program:

Tampilan:

c) JMenuItem
Class yang digunakan untuk membuat Item baru.
i. JMenu
Class yang digunakan untuk membuat menu yang dapat diinsert

dengan JmenuItem
Contoh Program:

Tampilan:

Referensi
Judul : Java > Swing Code Examples
http://java.happycodings.com/swing/, di akses pada Kamis,30 April 2015 pukul 16.39

WIB
Judul : Lesson: Using Swing Components
https://docs.oracle.com/javase/tutorial/uiswing/components/index.html , di akses pada

Jumat,1 Mei 2015 pukul 07.43 WIB

You might also like