JLabel`s property doesn`t change - java

I have a class , called boardGUI , it has a list of 64 labels (like a chess board). Every label coresponds to a specific tile on the board.
List<JLabel> labelList = new ArrayList<>();
In another class, I'm trying to set some of this labels opaque, with setOpaque(true) method , whenever I click on one of the labels (inside mouseClicked method).
JLabel l1 = boardGUI.labelList.get(1);
l1.setOpaque(true);
The problem is that although l1 refers the right label in labelList (I checked with the debugger) , it doesn`t make any visual change (on the GUI ).
But, if I'm trying to set opacity of the labels in the boardGUI class , it's working.
for (int i=0;i<64;i++)
labelList.get(i).setOpaque(true);
Where can the problem be?
here is the class where I'm trying to apply the changes :
public class Controller {
private Board board = new Board();
private BoardGUI boardGUI = new BoardGUI();
public Controller () {
boardGUI.setVisible(true);
boardGUI.addLabelListener(new LabelListener());
}
class LabelListener implements MouseListener{
#Override
public void mouseClicked(MouseEvent arg0) {
JLabel l1 = boardGUI.labelList.get(1);
l1.setOpaque(true);
}
BoardGUI class (there's more code , but it's not relevant) :
public class BoardGUI extends JFrame{
List<JLabel> labelList = new ArrayList<>();
public BoardGUI() {
createView();
}
public void createView() {
createLabels(mainPanel);
}
public void createLabels(JPanel mainPanel) {
int startX = 100;
int startY = 87;
int x = 100;
int y = 87;
int j = 0;
for (int i=0;i<64;i++) {
JLabel label = new JLabel();
label.setBounds(x , y , 62, 62);
labelList.add(label);
mainPanel.add(label);
if ( (i == 7*(j+1) +j )) {
x = startX;
y = startY + 62 *( i / 7);
j=j+1;
}
else {
x = x+62;
}
}
}

You need to set both background color and opaqueness; here's an example to show how these play together:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.getContentPane().setBackground(Color.GREEN);
JLabel label1 = new JLabel("label1");
label1.setBackground(Color.RED);
label1.setOpaque(false);
frame.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
label1.setOpaque(!label1.isOpaque());
label1.setBackground(label1.getBackground() == Color.RED ? Color.BLUE : Color.RED);
}
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
});
frame.add(label1);
frame.pack();
frame.setVisible(true);
}
The label is initially transparanet, then changes to BLUE and opaque and back with every MouseClick. So basically, you would need to set the background color together with opaque (the RED color is just to demonstrate that it is never shown as the label is never both opaque and RED).

Related

Repainting JPanel

So i'm trying to clear my drawing Panel and I have looked at multiple examples but none of them seem to be working for me? I have a clear button that clears textfields/errors which I got to work perfectly but the Drawing panel still does not clear arraylists or "repaint".
I'm playing around with changing around the size of the oval so please ignore my drawPoints method.
Here is my code:
public class Panel extends JPanel{
ArrayList<Point> pointArray = new ArrayList<>();
ArrayList<Color> colorArray = new ArrayList<>();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
repaint();
//Create the 2D graphics object
Graphics2D myDrawing = (Graphics2D) g;
for (int i = 0; i < pointArray.size(); i++) {
myDrawing.setColor(colorArray.get(i));
myDrawing.fillOval(pointArray.get(i).x,pointArray.get(i).y, 10, 10);
}
}
public void drawPoints(int mouseX, int mouseY, int height, int width){
Point p = new Point(mouseX,mouseY);
pointArray.add(p);
colorArray.add(this.getForeground());
repaint();
}
public void changeColor(){
int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
this.setForeground(new Color(red,green,blue));
}
public void mousePressed(MouseEvent event) {
pointArray.clear();
colorArray.clear();
repaint();
}
}
public static void main(String[] args) {
//set the frame
JFrame frame = new JFrame();
frame.setSize(600, 300);
frame.setTitle("Multiple Panels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create the panel for GUI
JPanel panelGUI = new JPanel();
panelGUI.setBackground(Color.yellow);
//GUIs
//create textfields
JTextField radiusField1 = new JTextField("10", 10);
JTextField radiusField2 = new JTextField("10", 10);
//create buttons
final JButton clearDrawingButton = new JButton("Clear Screen");
final JButton changeColorButton = new JButton("Change Color");
//labels
final JLabel displayLabel = new JLabel("");
//add all GUIs to the GUI panel
panelGUI.add(radiusField1);
panelGUI.add(radiusField2);
panelGUI.add(changeColorButton);
panelGUI.add(clearDrawingButton);
panelGUI.add(displayLabel);
//create the panel to draw
final Panel drawingPanel = new Panel();
drawingPanel.setBackground(Color.white);
//create the initial color
Color drawingColor = new Color(255,0,0);
//set the initial drawing color of the panel
drawingPanel.setForeground(drawingColor);
//add the grid with two columns and two rows to add the three panels
GridLayout grid = new GridLayout(0,2,10,20);
//add the grid to the frame
frame.setLayout(grid);
//add the panels to the frame
frame.add(panelGUI);
frame.add(drawingPanel);
class MouseClickListener implements MouseListener
{
public void mouseClicked(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
System.out.println(x + " " + y);
try {
String text1 = radiusField1.getText();
String text2 = radiusField2.getText();
int height = Integer.parseInt(text1);
int width = Integer.parseInt(text2);
drawingPanel.drawPoints(x, y, height, width);
} catch (NumberFormatException ex) {
displayLabel.setText("Textfields empty! Please enter number.");}
}
// Do­nothing methods
public void mouseReleased(MouseEvent event) {}
public void mousePressed(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource()== changeColorButton){
drawingPanel.changeColor();
}
if(event.getSource()==clearDrawingButton){
radiusField1.setText("10");
radiusField2.setText("10");
displayLabel.setText("");
}
}
}
MouseListener listener1 = new MouseClickListener();
drawingPanel.addMouseListener(listener1);
ActionListener listener = new ButtonListener();
changeColorButton.addActionListener(listener);
clearDrawingButton.addActionListener(listener);
frame.setVisible(true);
}
}
I have a clear button that clears textfields/errors which I got to work perfectly but the Drawing panel still does not clear arraylists or "repaint".
Well look at the code that clears the text fields:
if(event.getSource()==clearDrawingButton){
radiusField1.setText("10");
radiusField2.setText("10");
displayLabel.setText("");
}
Where is the code that clears the ArrayLists?
Add the code to clear the ArrayLists to the ActionListener.
You can also check out Custom Painting Approaches for working code that draws "rectangles". It supports different colors and a "Clear" button.
Also, instead of using a JTextField for the oval size, you might want to consider using a JSpinner. This will allow the user to easily change the numeric value and you don't have to add any special editing to make sure the value entered is a number.
You have this mousePressed method in your main class:
public void mousePressed(MouseEvent event) {
pointArray.clear();
colorArray.clear();
repaint();
}
But it isn't doing anything because your main class does not implement MouseListener and no one is calling this method.
The rest of your code is not very pretty looking. I assume you are doing this as part of a course or otherwise just trying to learn Java Swing in a non-work environment. If this is true, I would recommend that you start over - at least with your MouseListeners, and instead create Actions for your button responses by subclassing AbstractAction and using it with JButton.setAction(myAction); This may seem painful now, but you'll be glad you did it in the future

How can I add multiple MouseListeners to a single JFrame?

I have two things that I am trying to do: highlight a JPanel on mouse hover and move a blue square on mouse drag. The thing is, this requires me to add MouseListeners to different components. When I do this, I can only use one feature - the other is blocked. What can I do so that both features work?
NOTE: Sometimes the JFrame doesn't show anything - you just have to keep running it until it does (usually takes 2-3 tries). If it does any other weird stuff just keep running it until it works. Comment if it still isn't working right after >5 tries.
What it should look like:
Main(creates the JFrame, the container, and the children, and adds the MouseListeners)
public class Main extends JFrame{
private static final long serialVersionUID = 7163215339973706671L;
private static final Dimension containerSize = new Dimension(640, 477);
static JLayeredPane layeredPane;
static JPanel container;
public Main() {
super("Multiple MouseListeners Test");
setSize(640, 477);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(containerSize);
getContentPane().add(layeredPane);
createContainer();
layeredPane.add(container, JLayeredPane.DEFAULT_LAYER);
createChildren(4, 4);
new MovableObject();
MovableObjectMouseListener moml = new MovableObjectMouseListener();
//comment these two out and the highlighter works
layeredPane.addMouseListener(moml);
layeredPane.addMouseMotionListener(moml);
}
private void createChildren(int columns, int rows){
for (int i = 0; i < columns; i++){
for (int j = 0; j < rows; j++){
JPanel child = new JPanel(new BorderLayout());
child.setBackground(Color.LIGHT_GRAY);
//comment this out and you can move the MovableObject
child.addMouseListener(new HighlightJPanelsMouseListener());
container.add(child);
}
}
}
private JPanel createContainer(){
container = new JPanel();
container.setLayout(createLayout(4, 4, 1, 1));
container.setPreferredSize(containerSize);
container.setBounds(0, 0, containerSize.width, containerSize.height);
return container;
}
private GridLayout createLayout(int rows, int columns, int hGap, int vGap){
GridLayout layout = new GridLayout(rows, columns);
layout.setHgap(hGap);
layout.setVgap(vGap);
return layout;
}
public static void main(String[] args) {
new Main();
}
}
HighlightJPanelsMouseListener(creates the MouseListeners that will be added to the children)
public class HighlightJPanelsMouseListener implements MouseListener{
private Border grayBorder = BorderFactory.createLineBorder(Color.DARK_GRAY);
public HighlightJPanelsMouseListener() {
}
public void mouseEntered(MouseEvent e) {
Component comp = (Component) e.getSource();
JPanel parent = (JPanel) comp;
parent.setBorder(grayBorder);
parent.revalidate();
}
public void mouseExited(MouseEvent e) {
Component comp = (Component) e.getSource();
JPanel parent = (JPanel) comp;
parent.setBorder(null);
parent.revalidate();
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e) {}
}
MovableObject(creates the MovableObject)
download blueSquare.png, or use another image. Remember to change the name of the image below to whatever yours is.
public class MovableObject {
public MovableObject() {
JPanel parent = (JPanel) Main.container.findComponentAt(10, 10);
ImageIcon icon = null;
//use any image you might have laying around your workspace - or download the one above
URL imgURL = MovableObject.class.getResource("/blueSquare.png");
if (imgURL != null){
icon = new ImageIcon(imgURL);
}else{
System.err.println("Couldn't find file");
}
JLabel movableObject = new JLabel(icon);
parent.add(movableObject);
parent.revalidate();
}
}
MovableObjectMouseListener(creates the MouseListener to be used for MovableObject)
public class MovableObjectMouseListener implements MouseListener, MouseMotionListener{
private JLabel replacement;
private int xAdjustment, yAdjustment;
public void mousePressed(MouseEvent e){
replacement = null;
Component c = Main.container.findComponentAt(e.getX(), e.getY());
if (!(c instanceof JLabel)){
return;
}
Point parentLocation = c.getParent().getLocation();
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
replacement = (JLabel)c;
replacement.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
Main.layeredPane.add(replacement, JLayeredPane.DRAG_LAYER);
Main.layeredPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
public void mouseDragged(MouseEvent me){
if (replacement == null){
return;
}
int x = me.getX() + xAdjustment;
int xMax = Main.layeredPane.getWidth() - replacement.getWidth();
x = Math.min(x, xMax);
x = Math.max(x, 0);
int y = me.getY() + yAdjustment;
int yMax = Main.layeredPane.getHeight() - replacement.getHeight();
y = Math.min(y, yMax);
y = Math.max(y, 0);
replacement.setLocation(x, y);
}
public void mouseReleased(MouseEvent e){
Main.layeredPane.setCursor(null);
if (replacement == null){
return;
}
int xMax = Main.layeredPane.getWidth() - replacement.getWidth();
int x = Math.min(e.getX(), xMax);
x = Math.max(x, 0);
int yMax = Main.layeredPane.getHeight() - replacement.getHeight();
int y = Math.min(e.getY(), yMax);
y = Math.max(y, 0);
Component c = Main.container.findComponentAt(x, y);
Container parent = (Container) c;
parent.add(replacement);
parent.validate();
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
Didn't look at your code in detail but I would suggest that you need to add the drag MouseListener to the movable object (ie. the JLabel) and not the panel. Then the label will get the drag events and the panel will get the mouseEntered/Exited events.
This will lead to an additional problem with the mouseExited event now being generated when you move over the label (which you don't want to happen). Check out: how to avoid mouseExited to fire while on any nested component for a solution to this problem.

repaint() method not getting called

So I made a program where users can draw dots on the screen depending on where they click and then it draws lines from each dot to the next dot. Now I want to make it so another JFrame pops up where the user can choose to change the colour of the dots(vertex), the background or the lines(edges). The code I have thus far is:
// Fig. 14.34: Painter.java
// Testing PaintPanel.
public class Painter
{
public static void main( String[] args )
{
// create JFrame
JFrame application = new JFrame( "A simple paint program" );
PaintPanel paintPanel = new PaintPanel(); // create paint panel
ColorChanger myColorChanger = new ColorChanger();
application.add( paintPanel, BorderLayout.CENTER ); // in center
// create a label and place it in SOUTH of BorderLayout
application.add( new JLabel( "Drag the mouse to draw" ),
BorderLayout.SOUTH );
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.setSize(600, 600 ); // set frame size
application.setVisible( true ); // display frame
} // end main
} // end class Painter
Class PaintPanel (Class that draws the lines and dots on the screen)
// Fig. 14.34: PaintPanel.java
// Using class MouseMotionAdapter.
public class PaintPanel extends JPanel
{
private int pointCount = 0; // count number of points
// array of 10000 java.awt.Point references
private Point[] points = new Point[100];
private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private Color backgroundColour = Color.GRAY;
private Color edgeColour = Color.WHITE;
private Color vertexColour = Color.WHITE;
private Color textColour = Color.BLACK;
// set up GUI and register mouse event handler
public PaintPanel()
{
setLayout(new BorderLayout());
setBackground(backgroundColour);
// handle frame mouse motion event
addMouseListener(
new MouseAdapter() // anonymous inner class
{
public void mousePressed(MouseEvent e) {
points[pointCount] = e.getPoint();
//Subtract 15 from both x and y so the middle of the circle is drawn where we click
points[pointCount].x -= 15;
points[pointCount].y -= 15;
pointCount++;
repaint(); //THIS repaint() IS BEING CALLED
}
} // end anonymous inner class
); // end call to addMouseMotionListener
} // end PaintPanel constructor
public void changeBackground(Color newColour) {
System.out.println("Paint Panel change");
backgroundColour = newColour;
edgeColour = newColour;
repaint(); //repaint() NOT BEING CALLED
}
public void changeEdge(Color newColour) {
edgeColour = newColour;
repaint(); //repaint() NOT BEING CALLED
}
// draw ovals in a 4-by-4 bounding box at specified locations on window
public void paint( Graphics g )
{
System.out.println("PAINTCOMPONENT");
super.paintComponent( g ); // clears drawing area
System.out.println("paintComponent backgroundColour = " + backgroundColour);
setBackground(backgroundColour);
g.setColor(textColour);
Font myFont = new Font("Serif", Font.BOLD, 20);
g.setFont(myFont);
// draw all points in array
for ( int i = 0; i < pointCount; i++ ) {
g.setColor(vertexColour);
g.fillOval( points[ i ].x, points[ i ].y, 30, 30 );
g.setColor(textColour);
g.drawString(Character.toString(alphabet.charAt(i % 26)), points[i].x + 10, points[i].y + 20);
g.setColor(edgeColour);
if(i > 0) {
g.drawLine(points[i].x + 15, points[i].y + 15, points[i-1].x + 15, points[i-1].y + 15);
}
}
} // end method paintComponent
} // end class PaintPanel
Class ColorChanger (Opens JFrame that shows three JButtons (to change colour of line, dots or background):
public class ColorChanger extends PaintPanel {
JFrame myFrame;
JButton background, edge, vertex;
public ColorChanger() {
myFrame = new JFrame("Color select tool");
myFrame.setLayout(new FlowLayout());
myFrame.setSize(500, 100);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
background = new JButton("Change background colour");
edge = new JButton("Change edge colour");
vertex = new JButton("Change vertex colour");
background.addActionListener(new ButtonListener());
edge.addActionListener(new ButtonListener());
vertex.addActionListener(new ButtonListener());
myFrame.add(background);
myFrame.add(edge);
myFrame.add(vertex);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == background) {
changeBackground();
} else if (e.getSource() == edge) {
changeEdge();
} else {
System.out.println("Vertex");
}
}
}
private void changeBackground() {
System.out.println("ColorChanger change Background");
super.changeBackground(Color.BLACK);
}
private void changeEdge() {
System.out.println("change edge");
super.changeEdge(Color.RED);
}
}
So this program successfully draws the dots and connects the lines but my problem is that it will not change the colour of anything because the repaint() calls in class PaintPanel wont work except for the first one inside the anonymous inner class

Java Swing - Drag & Drop drawString text

I've had a look around for this problem but couldn't find an answer...
I currently have a JPanel in which I'm painting a load of unicode characters (music notes) using the Graphics2D g2.drawString() method.
I have an ArrayList of KeyPress objects, each of which contains one or more g2.drawString() calls.
So each KeyPress object is a music note and is painted on the JPanel.
How would I go about adding the functionality to enable the user to select and drag the objects?
Why not put your Strings in JLabels and simply drag them...
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class DragLabelEg {
private static final String[] LABEL_STRINGS = { "Do", "Re", "Me", "Fa",
"So", "La", "Ti" };
private static final int HEIGHT = 400;
private static final int WIDTH = 600;
private static final Dimension MAIN_PANEL_SIZE = new Dimension(WIDTH, HEIGHT);
private static final int LBL_WIDTH = 60;
private static final int LBL_HEIGHT = 40;
private static final Dimension LABEL_SIZE = new Dimension(LBL_WIDTH,
LBL_HEIGHT);
private JPanel mainPanel = new JPanel();
private Random random = new Random();
public DragLabelEg() {
mainPanel.setPreferredSize(MAIN_PANEL_SIZE);
mainPanel.setLayout(null);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
for (int i = 0; i < LABEL_STRINGS.length; i++) {
JLabel label = new JLabel(LABEL_STRINGS[i], SwingConstants.CENTER);
label.setSize(LABEL_SIZE);
label.setOpaque(true);
label.setLocation(random.nextInt(WIDTH - LBL_WIDTH),
random.nextInt(HEIGHT - LBL_HEIGHT));
label.setBackground(new Color(150 + random.nextInt(105), 150 + random
.nextInt(105), 150 + random.nextInt(105)));
label.addMouseListener(myMouseAdapter);
label.addMouseMotionListener(myMouseAdapter);
mainPanel.add(label);
}
}
public JComponent getMainPanel() {
return mainPanel;
}
private class MyMouseAdapter extends MouseAdapter {
private Point initLabelLocation = null;
private Point initMouseLocationOnScreen = null;
#Override
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
// get label's initial location relative to its container
initLabelLocation = label.getLocation();
// get Mouse's initial location relative to the screen
initMouseLocationOnScreen = e.getLocationOnScreen();
}
#Override
public void mouseReleased(MouseEvent e) {
initLabelLocation = null;
initMouseLocationOnScreen = null;
}
#Override
public void mouseDragged(MouseEvent e) {
// if not dragging a JLabel
if (initLabelLocation == null || initMouseLocationOnScreen == null) {
return;
}
JLabel label = (JLabel) e.getSource();
// get mouse's new location relative to the screen
Point mouseLocation = e.getLocationOnScreen();
// and see how this differs from the initial location.
int deltaX = mouseLocation.x - initMouseLocationOnScreen.x;
int deltaY = mouseLocation.y - initMouseLocationOnScreen.y;
// change label's position by the same difference, the "delta" vector
int labelX = initLabelLocation.x + deltaX;
int labelY = initLabelLocation.y + deltaY;
label.setLocation(labelX, labelY);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGui();
}
});
}
private static void createGui() {
JFrame frame = new JFrame("App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DragLabelEg().getMainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
See the tutorial on supporting user interaction. It comes down to determining which (if any) objects were underneath the mouse when it was clicked and held. On a drag event, the selected object is moved and the canvas is repainted.
You can obtain the bounds of the string by using FontMetrics:
String text = "Hello world!";
Rectangle2D bounds = g2.getFontMetrics().getStringBounds(text, g2);
I assume the rectangle top-left will be (0, 0), so you need to add (x, y) to it (where x, y are the parameters you passed to drawString).
This example shows one way to select multiple objects, using keyboard or mouse, and drag
them as a group. It manipulates arbitrary nodes rather than glyphs, but you may find it instructive.

How to change the size of the graphics

I have Java applet to draw an array (just some rectangle one after another).
When user select to create array of size n, it will draw n rectangles connected together. When n gets bigger, the graphics get bigger, but since i use JPanel to draw the array, and JPanel won't scroll, i have to add that JPanel into a JScrollPane, but still it won't scroll. The user can see only part of the whole array.
Anyone can give me some help?
Here is my code:
public class ArrayPanel extends JPanel {
....
public void paintComponent(Graphics g) {
...draw array here..
// I wish to get the updated size of the graphis here,
// then i can reset the preferredSize()....?
System.out.println("width=" + getWidth() + " height=" + getHeight());
}
}
public class ArrayDemo extends JPanel {
public ArrayDemo() {
super(new BorderLayout());
arrayPanel = new ArrayPanel();
arrayPanel.setPreferredSize(new Dimension(400, 300));
JScrollPane container = new JScrollPane(arrayPanel,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
container.setPreferredSize(arrayPanel.getPreferredSize());
add(container, BorderLayout.CENTER);
...
}
}
Don't set the size in paintComponent.
You did not provide that code, but you have some position in your code where you know the size of that array, and the size of your rectangles, so set dimensions of your JPanel there.
Here is an example (using JFrame, not Applet, but the ideas is the same) that looks like this:
alt text http://img186.imageshack.us/img186/143/so2305419.png
public class ScrollPanelFrame extends JFrame{
public ScrollPanelFrame() {
ArrayPanel panel = new ArrayPanel(20, 20);
JScrollPane container = new JScrollPane(
panel,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
getContentPane().add(container);
}
class ArrayPanel extends JPanel {
final int RECTANGLE_WIDTH = 100;
final int RECTANGLE_HEIGHT = 100;
int rectangleCountX;
int rectangleCountY;
public ArrayPanel(int rectangleCountX, int rectangleCountY) {
this.rectangleCountX = rectangleCountX;
this.rectangleCountY = rectangleCountY;
this.setPreferredSize(new Dimension(RECTANGLE_WIDTH * rectangleCountX,
RECTANGLE_HEIGHT * rectangleCountY));
}
#Override
public void paintComponent(Graphics g) {
for(int x = 0 ; x < rectangleCountX ; x++) {
for(int y = 0 ; y < rectangleCountY ; y++) {
g.setColor(new Color(0, 0, (x+y)*64 % 256));
g.fillRect(x*RECTANGLE_WIDTH, y*RECTANGLE_HEIGHT,
RECTANGLE_WIDTH, RECTANGLE_HEIGHT);
}
}
}
}
public static void main(String[] args) {
ScrollPanelFrame frame = new ScrollPanelFrame();
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}

Categories

Resources