《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Test extends JApplet {
public Test() {
Container contentPane = getContentPane();
JViewport viewport = new JViewport();
JPanel view = new JPanel();
view.add(new JLabel(
new ImageIcon("anjinAndMariko.gif")));
viewport.setView(view);
contentPane.add(new ControlPanel(viewport),
BorderLayout.NORTH);
contentPane.add(viewport, BorderLayout.CENTER);
contentPane.add(new StatusPanel(viewport),
BorderLayout.SOUTH);
}
}
class StatusPanel extends JPanel {
private JLabel extentLabel = new JLabel(),
viewPositionLabel = new JLabel(),
viewSizeLabel = new JLabel();
private JViewport viewport;
public StatusPanel(JViewport vp) {
viewport = vp;
setBorder(BorderFactory.createEtchedBorder());
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
extentLabel.setAlignmentX(0.5f);
viewPositionLabel.setAlignmentX(0.5f);
viewSizeLabel.setAlignmentX(0.5f);
add(extentLabel);
add(viewPositionLabel);
add(viewSizeLabel);
viewport.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Dimension extent = viewport.getExtentSize();
Point viewPosition = viewport.getViewPosition();
Rectangle viewSize = viewport.getViewRect();
extentLabel.setText("View Extent: " +
extent.toString());
viewPositionLabel.setText("View Position: " +
viewPosition.toString());
viewSizeLabel.setText("View Size: " +
viewSize.toString());
revalidate();
}
});
}
}
class ControlPanel extends JPanel {
private JViewport viewport;
private JButton[] buttons = {
new JButton("up"), new JButton("down"),
new JButton("left"), new JButton("right"),
};
public ControlPanel(JViewport vp) {
viewport = vp;
for(int i=0; i < buttons.length; ++i) {
add(buttons[i]);
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scroll(e.getActionCommand());
}
});
}
}
private void scroll(String actionCmd) {
Point vp = viewport.getViewPosition();
if(actionCmd.equals("up")) vp.y += 5;
else if(actionCmd.equals("down")) vp.y -= 5;
else if(actionCmd.equals("left")) vp.x += 5;
else if(actionCmd.equals("right")) vp.x -= 5;
viewport.setViewPosition(vp);
}
}