Java Swing (Example)

snottybugbearSoftware and s/w Development

Nov 3, 2013 (4 years and 10 days ago)

102 views

Java Swing (Example)
April 25, 2013

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


// Code location: /home/course/java2/code/ByTopics/ExGUISwing/
public class SwingButExample extends JFrame {
protected JButton[] niagaraFall = new JButton[2]; // For Button
String messageString = new String("Default String"); // For Message String
DisplayCVS dcvs = new DisplayCVS(); // For Canvas to display the
message string

private void initialize(){ // Initialize method
Container ctn = this.getContentPane(); // Get Content Pane
ctn.setLayout(new GridLayout(2,2,1,1)); // Set Layout Manager

for(int i=0; i<2; i++) {
JButton bt = new JButton("Niagara"+i);
bt.setSize(100, 55);
String imgName = "Niagara"+i+".jpg";
bt.setIcon(new ImageIcon(imgName));
bt.setLocation(100*i + 1, 0);
niagaraFall[i] = bt;
ctn.add(bt);
}

niagaraFall[0].addActionListener(new LeftButtonListener());
niagaraFall[1].addActionListener(new RightButtonListener());
ctn.add(dcvs);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

Import classes for AWT,
events, and Swing.
Inherit JFrame to use Java
Swing for Frame.
Creating two buttons and set
Icon images, and add to the
container of the frame.
Add listeners to the buttons,
and canvas to the container.

public SwingButExample(){
super.setTitle("Swing Button Example");
initialize();
}
public SwingButExample(String title){
super.setTitle(title + "::"+"Swing Button Example");
initialize();
}

class LeftButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
messageString = "Left Scene!";
dcvs.repaint(); }
}
class RightButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
messageString = "Right Scene!";
dcvs.repaint(); }
}

class DisplayCVS extends Canvas {
public void paint(Graphics g) {
g.setColor(new Color(1, 1, 1));
g.setFont(new Font(null, Font.BOLD, 10));
g.drawString(messageString, 20,30);
}
}
public void setTitle(String title){ super.setTitle(title + "::"+"Swing Button
Example"); }

public static void main(String argv[]){
JFrame f = new SwingButExample();
f.setSize(300,200); f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
}
} // end of the class SwingButExample
Constructors
Action Listeners
Canvas Class