CounterApp.java, Counter.java - IDA

snottybugbearSoftware and s/w Development

Nov 3, 2013 (3 years and 9 months ago)

102 views

package
lecture1.painting;
import
java.awt.Color;
import
java.awt.Container;
import
java.awt.FlowLayout;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import
java.util.Random;
import
javax.swing.BorderFactory;
import
javax.swing.JButton;
import
javax.swing.JFrame;
import
javax.swing.SwingUtilities;
import
javax.swing.WindowConstants;
/**
* <p>
* Example of how to create a simple user interface in Java using swing.
* </p>
* <p>
* This application also provides a demonstration of the <code>Counter</code>
* class. The interface contains a button and a counter. When clicked the button
* increases the counter by a random amount.
* </p>
*
* @author jernlas
* @version 1.0.0
*/
public

class

CounterApp {

public

static

void
main(String[] args) {

new
CounterApp();
}

/**
* The counter component. It must be declared here in order for the action
* listener to be able to refer to it.
*/

private
Counter counter;

/**
* Creates a new LayoutFrame with default settings.
*/

public
CounterApp() {
SwingUtilities.invokeLater(
new
Runnable() {

public

void
run() {
createAndShowGUI();
}
});
}

/**
* Builds the graphical user interface, sets it up with listeners and so on.
* If this method gets too long, it is sometimes nice to break it into
* several methods.
*/

private

void
createAndShowGUI() {
JFrame frame =
new
JFrame("
Layout frame
");

/*
* Makes sure that the java program shuts down when all windows are
* closed.
Example 1Page 1/2
CounterApp.java
*/
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

/*
* JFrames can only have one component. You use your own by running
* something like "frame.setContentPane(new JPanel());", but there is
* already a default container provided that you can use.
*/
Container pane = frame.getContentPane();

// This gives us a centered flow layout with 5 px padding on all sides.
pane.setLayout(
new
FlowLayout());

/*
* Create the button an ActionListener that increases the counter by a
* random amount
*/
JButton btn =
new
JButton("
Add random value!
");
btn.addActionListener(
new
ActionListener() {
@Override

public

void
actionPerformed(ActionEvent e) {
counter.setValue(counter.getValue() +
new
Random().nextInt(1000));
}
});

/*
* Create the counter component. Put a border around it just to show how
* easy it is to use it like any other standard swing component.
*/
counter =
new
Counter();
counter.setBorder(BorderFactory.createLineBorder(Color.BLACK));

/*
* Don't forget to add the components to their container(s). If you forget
* this part nothing will be painted on screen.
*/
pane.add(btn);
pane.add(counter);

/*
* Lays out the JFrame and all subcomponents according to their respective
* layout managers. When done the frame is shown on screen.
*/
frame.pack();
frame.setVisible(
true
);
}
}
Example 1Page 2/2
CounterApp.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20091/2/home/jernlas/src/java/Swing-fö/src/lecture1/painting/CounterApp.java
package
lecture1.painting;
import
java.awt.Dimension;
import
java.awt.FontMetrics;
import
java.awt.Graphics;
import
java.awt.Rectangle;
import
javax.swing.JComponent;
/**
* A simple counter swing component. It draws a text explaining what the current
* count is.
*
* @author jernlas
* @version 1.0.0
*/
public

class

Counter
extends
JComponent {

/**
* The format of the text that is to be printed in the component. The %d part
* means that an integer goes there.
*/

private

static

final
String COUNT_FORMAT_STRING = "
Count is: %d
";

private

static

final

long
serialVersionUID = 5015664096430540232L;

/**
* The current value of the counter.
*/

private

int
value = 0;

/**
* The gap between the text and the edge of the component. In this simple
* example the gap is constant.
*/

private

final

int
GAP_SIZE = 3;
@Override

public
Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
Dimension d =
new
Dimension();
d.height = fm.getHeight() + 2 * GAP_SIZE;
d.width = fm.stringWidth(getStringValue()) + 2 * GAP_SIZE;

return
d;
}

/**
* Returns the value of the counter as a variable length string.
*
* @return The string representation of the counter value
*/

private
String getStringValue() {

return
String.format(COUNT_FORMAT_STRING, value);
}

/**
* Gets the current counter value.
*
* @return the value of the counter
*/

public

int
getValue() {

return
value;
Example 1Page 1/2
Counter.java
}
@Override

public

void
paintComponent(Graphics g) {

/*
* Only draw background if the component is opaque. This allows for
* transparant components to be put on top of others without ruining them
* by painting a big rectangular background on top of them.
*/

if
(isOpaque()) {
g.setColor(getBackground());
Rectangle b = getBounds();
g.drawRect(b.x, b.y, b.width, b.height);
}

/*
* Draw the string, FontMetrics is used to know how big it will be so that
* the drawing starts at the right place.
*/
FontMetrics fm = getFontMetrics(getFont());
g.setColor(getForeground());
g.drawString(getStringValue(), GAP_SIZE, fm.getAscent() + GAP_SIZE);
}

/**
* Sets a new value for the counter. This will cause a revalidation of the
* layout and a repaint of the component.
*
* @param i
* the new value to set
*/

public

void
setValue(
int
i) {

/*
* Set the new value for the counter.
*/
value = i;

/*
* Indicates that this component (and all subcomponents) must be laid out
* again. The root (JFrame) is told to redo the layout. When the layout is
* updated repaint() is called to update the graphics which also should
* change.
*/
revalidate();
repaint();
}
}
Example 1Page 2/2
Counter.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20092/2/home/jernlas/src/java/Swing-fö/src/lecture1/painting/Counter.java
package
lecture1.layout;
import
java.awt.BorderLayout;
import
java.awt.Color;
import
java.awt.Container;
import
javax.swing.JButton;
import
javax.swing.JComponent;
/**
* Tests the BorderLayout layout manager by adding a component to all the
* positions defined by the manager.
*
* @author jernlas
*/
public

class

BorderLayoutTest
extends
LayoutTest {

public

static

void
main(String[] args) {

new
BorderLayoutTest();
}
@Override

protected

void
createGUI() {
Container panel = frame.getContentPane();
panel.setLayout(
new
BorderLayout(H_GAP, V_GAP));
JComponent b;
b =
new
JButton("
NORTH
");
b.setBackground(Color.RED);
panel.add(b, BorderLayout.NORTH);
b =
new
JButton("
WEST
");
b.setBackground(Color.BLUE);
panel.add(b, BorderLayout.WEST);
b =
new
JButton("
CENTER
");
b.setBackground(Color.YELLOW);
panel.add(b, BorderLayout.CENTER);
b =
new
JButton("
EAST
");
b.setBackground(Color.GREEN);
panel.add(b, BorderLayout.EAST);
b =
new
JButton("
SOUTH
");
b.setBackground(Color.PINK);
panel.add(b, BorderLayout.SOUTH);
}
}
Example 2Page 1/1
BorderLayoutTest.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20091/7/home/jernlas/src/java/Swing-fö/src/lecture1/layout/BorderLayoutTest.java
package
lecture1.layout;
import
java.awt.Color;
import
java.awt.Component;
import
java.awt.Container;
import
java.awt.Dimension;
import
javax.swing.Box;
import
javax.swing.BoxLayout;
import
javax.swing.JButton;
import
javax.swing.JComponent;
/**
* Tests the BoxLayout by creating three components and aligning different parts
* of them in a vertical line.
*
* @author jernlas
*/
public

class

BoxLayoutTest
extends
LayoutTest {

public

static

void
main(String[] args) {

new
BoxLayoutTest();
}
@Override

protected

void
createGUI() {
Container panel = frame.getContentPane();
panel.setLayout(
new
BoxLayout(panel, BoxLayout.PAGE_AXIS));
JComponent b;
panel.add(Box.createGlue());
b =
new
JButton("
Left Align
");
b.setBackground(Color.RED);
b.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(b);
panel.add(Box.createRigidArea(
new
Dimension(0, H_GAP)));
b =
new
JButton("
Center Align
");
b.setBackground(Color.BLUE);
b.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(b);
panel.add(Box.createRigidArea(
new
Dimension(0, H_GAP)));
b =
new
JButton("
Right Align
");
b.setBackground(Color.YELLOW);
b.setAlignmentX(Component.RIGHT_ALIGNMENT);
panel.add(b);
}
}
Example 2Page 1/1
BoxLayoutTest.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20092/7/home/jernlas/src/java/Swing-fö/src/lecture1/layout/BoxLayoutTest.java
package
lecture1.layout;
import
java.awt.Container;
import
java.awt.FlowLayout;
import
javax.swing.JButton;
import
javax.swing.JComponent;
/**
* Tests the FlowLayout layout manager by creating a Frame containing a lot of
* buttons.
*
* @author jernlas
*/
public

class

FlowLayoutTest
extends
LayoutTest {

public

static

void
main(String[] args) {

new
FlowLayoutTest();
}

/**
* The number of buttons to create in the test.
*/

protected

final

int
NUMBER_OF_BUTTONS = 20;
@Override

protected

void
createGUI() {
Container panel = frame.getContentPane();

/*
* Align components by leading edge
*/
panel.setLayout(
new
FlowLayout(FlowLayout.LEADING, H_GAP, V_GAP));

/*
* Create the buttons and add them to the panel.
*/
JComponent b;

for
(
int
i = 1; i  NUMBER_OF_BUTTONS; i++) {
b =
new
JButton(String.format("
#%02d
", i));
panel.add(b);
}
}
}
Example 2Page 1/1
FlowLayoutTest.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20093/7/home/jernlas/src/java/Swing-fö/src/lecture1/layout/FlowLayoutTest.java
package
lecture1.layout;
import
java.awt.Container;
import
java.awt.GridLayout;
import
javax.swing.JButton;
import
javax.swing.JComponent;
/**
* Tests the GridLayoutTest by adding a large number of components.
*
* @author jernlas
*/
public

class

GridLayoutTest
extends
LayoutTest {

public

static

void
main(String[] args) {

new
GridLayoutTest();
}

/**
* The number of buttons to create in the test.
*/

protected

final

int
NUMBER_OF_BUTTONS = 20;
@Override

protected

void
createGUI() {
Container panel = frame.getContentPane();

/*
* Align components by leading edge
*/
panel.setLayout(
new
GridLayout(5, 4, H_GAP, V_GAP));

/*
* Create the buttons and add them to the panel.
*/
JComponent b;

for
(
int
i = 1; i  NUMBER_OF_BUTTONS; i++) {
b =
new
JButton(String.format("
#%02d
", i));
panel.add(b);
}
}
}
Example 2Page 1/1
GridLayoutTest.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20094/7/home/jernlas/src/java/Swing-fö/src/lecture1/layout/GridLayoutTest.java
package
lecture1.layout;
import
java.awt.Container;
import
javax.swing.GroupLayout;
import
javax.swing.JButton;
import
javax.swing.LayoutStyle;
/**
* Tests the GroupLayout layout manager by placing three buttons in an odd
* arrangement.
*
* @author jernlas
*/
public

class

GroupLayoutTest
extends
LayoutTest {

public

static

void
main(String[] args) {

new
GroupLayoutTest();
}
@Override

protected

void
createGUI() {
Container panel = frame.getContentPane();
GroupLayout layout =
new
GroupLayout(panel);
panel.setLayout(layout);

/*
* Create three buttons and add them to the panel.
*/
JButton btn1 =
new
JButton("
Grp1Btn1
");
JButton btn2 =
new
JButton("
Grp1Btn2
");
JButton btn3 =
new
JButton("
Grp1Btn3
");
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);

/*
* Create a horizontal group where the first button is alone, followed by
* button two and three in parallell.
*/
layout
.setHorizontalGroup(layout.createSequentialGroup().addComponent(
btn1).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGroup(
layout.createParallelGroup().addComponent(btn2).addComponent(
btn3)));

/*
* Create a vertical group where the first and second buttons are
* positioned in paralell, followed by the third button alone.
*/
layout
.setVerticalGroup(layout.createSequentialGroup().addGroup(
layout.createParallelGroup().addComponent(btn1).addComponent(
btn2)).addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(btn3))
;
}
Example 2Page 1/2
GroupLayoutTest.java
}
Example 2Page 2/2
GroupLayoutTest.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20095/7/home/jernlas/src/java/Swing-fö/src/lecture1/layout/GroupLayoutTest.java
package
lecture1.layout;
import
javax.swing.JFrame;
import
javax.swing.SwingUtilities;
import
javax.swing.WindowConstants;
/**
* Abstract class intended to simplify creation of tests for different layout
* managers. It provides a frame, predefined constantrs for gaps and takes care
* of common parts of user interface creation.
*
* @author jernlas
*/
public

abstract

class

LayoutTest {

/**
* The frame that the test is performed in.
*/

protected

final
JFrame frame =
new
JFrame();

/**
* The length of horizontal gaps in the layout.
*/

protected

final

int
H_GAP = 5;

/**
* The length of vertical gaps in the layout.
*/

protected

final

int
V_GAP = 5;

/**
* Creates a new LayoutTest with standard settings.
*/

public
LayoutTest() {
SwingUtilities.invokeLater(
new
Runnable() {

public

void
run() {
createGUI();
showGUI();
}
});
}

/**
* Creates the user interface. This method is intended to be overridden so
* that each subclass creates the interface that best illustrates it's layout
* manager.
*/

protected

abstract

void
createGUI();

/**
* Pack the frame and show it.
*/

private

void
showGUI() {
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(
true
);
}
}
Example 2Page 1/1
LayoutTest.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20096/7/home/jernlas/src/java/Swing-fö/src/lecture1/layout/LayoutTest.java
package
lecture1.layout;
import
java.awt.Dimension;
import
javax.swing.JButton;
import
javax.swing.JFrame;
import
javax.swing.SwingUtilities;
import
javax.swing.WindowConstants;
/**
* Tests the what will happen if layout manager is null.
* @author jernlas
*
*/
public

class

NullLayoutTest {


public

static

void
main(String[] args){

new
NullLayoutTest();
}


public
NullLayoutTest(){

super
();
SwingUtilities.invokeLater(
new
Runnable() {

public

void
run() {
createAndShowGUI();
}
});
}


/**
* Creates the GUI
*/

private

void
createAndShowGUI() {
JFrame frame =
new
JFrame("
Empty frame
");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setSize(
new
Dimension(200, 100));
frame.getRootPane().setLayout(
null
);

JButton btn =
new
JButton("
Knapp
");
frame.getRootPane().add(btn);
btn.setSize(
new
Dimension(100, 50));

frame.setVisible(
true
);
}
}
Example 2Page 1/1
NullLayoutTest.java
TDDD13/TDDC73 Lecture: Swing 1
onsdag oktober 28, 20097/7/home/jernlas/src/java/Swing-fö/src/lecture1/layout/NullLayoutTest.java