import java.awt.*; import javax.swing.*; import java.awt.Toolkit; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class LeBeeper extends JPanel implements ActionListener { JButton button; public LeBeeper() { super(new BorderLayout()); button = new JButton("Click Me"); button.setPreferredSize(new Dimension(200, 80)); add(button, BorderLayout.CENTER); button.addActionListener(this); } public void actionPerformed(ActionEvent e) { Toolkit.getDefaultToolkit().beep(); } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Beeper"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new LeBeeper(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
import javax.swing.*; import java.awt.*; public class Layingout { final static String LOOKANDFEEL = null; // ... or: "Metal", "System", "Motif", "GTK+" public Component createComponents() { JButton button1 = new JButton("ONE"); JButton button2 = new JButton("TWO"); JButton button3 = new JButton("THREE"); JButton button4 = new JButton("FOUR"); JButton button5 = new JButton("FIVE"); JPanel pane = new JPanel(new GridLayout(2,1)); pane.add(button1); pane.add(button2); pane.add(button3); pane.add(button4); pane.add(button5); return pane; } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); // Make it so! JFrame frame = new JFrame("Button Showing"); // build frame with exit option! frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Layingout app = new Layingout(); Component contents = app.createComponents(); frame.getContentPane().add(contents, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } } ); // end of 'invokeLater' } // end of Main }
import javax.swing.*; import java.awt.*; public class NowDrawStuff { // save as NowDrawStuff.java private void buildUI(Container container) { container.setLayout( new BoxLayout(container, BoxLayout.PAGE_AXIS) ); CoordinateArea coordinateArea = new CoordinateArea(this); // see below container.add(coordinateArea); } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("DrawThingsDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); NowDrawStuff controller = new NowDrawStuff(); controller.buildUI(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } } ); // end of invokeLater } // end of main public static class CoordinateArea extends JComponent { //Point point = null; NowDrawStuff controller; Dimension preferredSize = new Dimension(400,575); // choose size!! Color gridColor; public CoordinateArea(NowDrawStuff controller) { this.controller = controller; //Add border of 10 pixels at L and bottom, and 4 pixels at the top and R. setBorder(BorderFactory.createMatteBorder(4,10,10,4,Color.RED)); setBackground(Color.WHITE); setOpaque(true); } // end of constructor public Dimension getPreferredSize() { return preferredSize; } protected void paintComponent(Graphics g) { if (isOpaque()) { g.setColor(getBackground()); //Paint bg if we're opaque. g.fillRect(0, 0, getWidth(), getHeight()); } g.setColor(Color.ORANGE); //Paint colour , even ...drawGrid(g, 20); below g.drawLine(78,200,100,38); g.setColor(getForeground()); g.fillRect(13, 23, 67, 107); int [] xcoords = new int[6]; int [] ycoords = new int[6]; for (int i=0; i<6; i++) { xcoords[i] = 50 * i + 100; ycoords[i] = 10 * i * i + 200; } g.setColor(Color.MAGENTA); g.drawPolyline( xcoords, ycoords, 6); } // end of paintComponent //Draws a 20x20 grid using the current color. private void drawGrid(Graphics g, int gridSpace) { Insets insets = getInsets(); int firstX = insets.left; int firstY = insets.top; int lastX = getWidth() - insets.right; int lastY = getHeight() - insets.bottom; int x = firstX; //Draw vertical lines. while (x < lastX) { g.drawLine(x, firstY, x, lastY); x += gridSpace; } int y = firstY; //Draw horizontal lines. while (y < lastY) { g.drawLine(firstX, y, lastX, y); y += gridSpace; } } // end of drawGrid } // end of CoordinateArea class }
import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import javax.swing.event.MouseInputListener; /* * This displays a framed area. As the user moves the cursor * over the area, a label displays the cursor's location. When * the user clicks, the area displays a 7x7 dot at the click * location. */ public class QCoordinatesDemo { private JLabel label; private Point clickPoint, cursorPoint; private void buildUI(Container container) { container.setLayout( new BoxLayout(container, BoxLayout.PAGE_AXIS) ); CoordinateArea coordinateArea = new CoordinateArea(this); // see below container.add(coordinateArea); label = new JLabel(); resetLabel(); // see below container.add(label); //Align the left edges of the components. coordinateArea.setAlignmentX(Component.LEFT_ALIGNMENT); label.setAlignmentX(Component.LEFT_ALIGNMENT); //redundant } public void updateCursorLocation(int x, int y) { if (x < 0 || y < 0) { cursorPoint = null; updateLabel(); // see below return; } if (cursorPoint == null) { cursorPoint = new Point(); } cursorPoint.x = x; cursorPoint.y = y; updateLabel(); // see below } public void updateClickPoint(Point p) { clickPoint = p; updateLabel(); // see below } public void resetLabel() { cursorPoint = null; updateLabel(); // see below } protected void updateLabel() { String text = ""; if ((clickPoint == null) && (cursorPoint == null)) text = "Click or move the cursor within the framed area."; else { if (clickPoint != null) { text += "The last click was at (" + clickPoint.x + ", " + clickPoint.y + "). "; } if (cursorPoint != null) { text += "The cursor is at (" + cursorPoint.x + ", " + cursorPoint.y + "). "; } } label.setText(text); } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("CoordinatesDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); QCoordinatesDemo controller = new QCoordinatesDemo(); controller.buildUI(frame.getContentPane()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } } ); // end of invokeLater } // end of main public static class CoordinateArea extends JComponent implements MouseInputListener { Point point = null; QCoordinatesDemo controller; Dimension preferredSize = new Dimension(400,75); Color gridColor; public CoordinateArea(QCoordinatesDemo controller) { this.controller = controller; //Add a border of 5 pixels at the left and bottom, //and 1 pixel at the top and right. setBorder(BorderFactory.createMatteBorder(1,5,5,1,Color.RED)); addMouseListener(this); addMouseMotionListener(this); setBackground(Color.WHITE); setOpaque(true); } // end of constructor public Dimension getPreferredSize() { return preferredSize; } protected void paintComponent(Graphics g) { if (isOpaque()) { g.setColor(getBackground()); //Paint bg if we're opaque. g.fillRect(0, 0, getWidth(), getHeight()); } g.setColor(Color.GRAY); //Paint 20x20 grid. drawGrid(g, 20); // defined below //If user has chosen a point, paint a small 'dot' on top. if (point != null) { g.setColor(getForeground()); g.fillRect(point.x - 3, point.y - 3, 7, 7); } } // end of paintComponent //Draws a 20x20 grid using the current color. private void drawGrid(Graphics g, int gridSpace) { Insets insets = getInsets(); int firstX = insets.left; int firstY = insets.top; int lastX = getWidth() - insets.right; int lastY = getHeight() - insets.bottom; int x = firstX; //Draw vertical lines. while (x < lastX) { g.drawLine(x, firstY, x, lastY); x += gridSpace; } int y = firstY; //Draw horizontal lines. while (y < lastY) { g.drawLine(firstX, y, lastX, y); y += gridSpace; } } // end of drawGrid //Methods required by the MouseInputListener interface. public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (point == null) { point = new Point(x, y); } else { point.x = x; point.y = y; } controller.updateClickPoint(point); repaint(); } public void mouseMoved(MouseEvent e) { controller.updateCursorLocation(e.getX(), e.getY()); } public void mouseExited(MouseEvent e) { controller.resetLabel(); } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } } // end of CoordinateArea class }
// SelectionDemo.java requires one other file: images/starfield.gif import javax.swing.*; import javax.swing.event.MouseInputAdapter; // so only need to override methods! import java.awt.*; import java.awt.event.MouseEvent; /* * This displays an image. When the user drags within the image, this program * displays a rectangle and a string indicating the bounds of the rectangle. */ public class SelectionDemo { // contains main and various static methods ... also JLabel label; // ... has SelectionArea as a private inner class static String filePrefix = "../uiswing/14painting/example-1dot4/"; static String starFile = filePrefix + "images/starfield.gif"; private void buildUI(Container container, ImageIcon image) { container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS)); SelectionArea area = new SelectionArea(image, this); container.add(area); label = new JLabel("Drag within the image."); label.setLabelFor(area); container.add(label); //Align the left edges of the components. area.setAlignmentX(Component.LEFT_ALIGNMENT); label.setAlignmentX(Component.LEFT_ALIGNMENT); //redundant } public void updateLabel(Rectangle rect) { int width = rect.width; int height = rect.height; //Make the coordinates look OK if a dimension is 0. if (width == 0) width = 1; if (height == 0) height = 1; label.setText("Rectangle goes from (" + rect.x + ", " + rect.y + ") to (" + (rect.x + width - 1) + ", " + (rect.y + height - 1) + ")."); } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = SelectionDemo.class.getResource(path); if (imgURL != null) return new ImageIcon(imgURL); else { System.err.println("Couldn't find file: " + path); return null; } } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("SelectionDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SelectionDemo controller = new SelectionDemo(); controller.buildUI( frame.getContentPane(), createImageIcon(starFile) ); //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(); } } ); // end of invokeLater } // end of main ////////////////////////////////////////////////////// private class SelectionArea extends JLabel { Rectangle currentRect = null; Rectangle rectToDraw = null; Rectangle previousRectDrawn = new Rectangle(); SelectionDemo controller; public SelectionArea(ImageIcon image, SelectionDemo controller) { // constructor super(image); //This component displays an image using the JLabel constructor this.controller = controller; setOpaque(true); setMinimumSize(new Dimension(10,10)); //don't hog space MyListener myListener = new MyListener(); // MyListener class is below addMouseListener(myListener); addMouseMotionListener(myListener); } // end of constructor private class MyListener extends MouseInputAdapter { public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); currentRect = new Rectangle(x, y, 0, 0); updateDrawableRect(getWidth(), getHeight()); // defined below repaint(); // this is what shows us the rectangle via JLabel's paint } // end of mousePressed public void mouseDragged(MouseEvent e) { updateSize(e); } // defined below public void mouseReleased(MouseEvent e) { updateSize(e); } /* * Update the size of the current rectangle and call repaint. Because * currentRect always has the same origin, translate it if the width or * height is negative. For efficiency, specify the painting region using * arguments to the repaint() call. */ void updateSize(MouseEvent e) { int x = e.getX(); int y = e.getY(); currentRect.setSize( x - currentRect.x, y - currentRect.y ); updateDrawableRect( getWidth(), getHeight() ); Rectangle totalRepaint = rectToDraw.union(previousRectDrawn); repaint(totalRepaint.x, totalRepaint.y, totalRepaint.width, totalRepaint.height); // uses JLabel's paint } // end of updateSize } // end of MyListener class protected void paintComponent(Graphics g) { super.paintComponent(g); //paints the background and image via JLabel's paintC // ... which in turn came from JComponent !! //If currentRect exists, paint a box on top. if (currentRect != null) { //Draw a rectangle on top of the image. g.setXORMode(Color.white); //Color of line varies dep on image colors g.drawRect(rectToDraw.x, rectToDraw.y, rectToDraw.width - 1, rectToDraw.height - 1); controller.updateLabel(rectToDraw); // since this inherits from JLabel } } private void updateDrawableRect(int compWidth, int compHeight) { int x = currentRect.x; // first get current data int y = currentRect.y; int width = currentRect.width; int height = currentRect.height; //Make the width and height positive, if necessary. if (width < 0) { width = 0 - width; // gets abs value of width if width was neg x = x - width + 1; // ... then moves x coord L by width if (x < 0) { width += x; x = 0; } // slides everything R if too far L } if (height < 0) { // analogous to the width magic above height = 0 - height; y = y - height + 1; if (y < 0) { height += y; y = 0; } } //The rectangle shouldn't extend past the drawing area. if ( (x + width) > compWidth ) width = compWidth - x; if ( (y + height) > compHeight ) height = compHeight - y; //Update rectToDraw after saving old value. if (rectToDraw != null) { previousRectDrawn.setBounds( rectToDraw.x, rectToDraw.y, rectToDraw.width, rectToDraw.height ); rectToDraw.setBounds(x, y, width, height); } else rectToDraw = new Rectangle(x, y, width, height); } // end of updateDrawableRect } // end of SelectionArea class }