Make a button round - java

I'm trying to make a JButton round at the (x,y) coordinates of (150,210). I want the button to be an oval of the size (40,40). And the buttons background color red. It doesn't need text, so I should get a button to whatever size I want, right?
I am using a panel, and I set the setLayout to null:
setLayout(null)
I checked Google, and it brought me here. How can I do this?

JDC Tech Tips: August 26, 1999: Creating Round Swing Buttons
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class RoundButton extends JButton {
public RoundButton(String label) {
super(label);
// These statements enlarge the button so that it
// becomes a circle rather than an oval.
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width,
size.height);
setPreferredSize(size);
// This call causes the JButton not to paint
// the background.
// This allows us to paint a round background.
setContentAreaFilled(false);
}
// Paint the round background and label.
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
// You might want to make the highlight color
// a property of the RoundButton class.
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width-1,
getSize().height-1);
// This call will paint the label and the
// focus rectangle.
super.paintComponent(g);
}
// Paint the border of the button using a simple stroke.
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1,
getSize().height-1);
}
// Hit detection.
Shape shape;
public boolean contains(int x, int y) {
// If the button has changed size,
// make a new shape object.
if (shape == null ||
!shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0,
getWidth(), getHeight());
}
return shape.contains(x, y);
}
// Test routine.
public static void main(String[] args) {
// Create a button with the label "Jackpot".
JButton button = new RoundButton("Jackpot");
button.setBackground(Color.green);
// Create a frame in which to show the button.
JFrame frame = new JFrame();
frame.getContentPane().setBackground(Color.yellow);
frame.getContentPane().add(button);
frame.getContentPane().setLayout(new FlowLayout());
frame.setSize(150, 150);
frame.setVisible(true);
}
}

Related

Image From background being copied to jtextarea transparent background [duplicate]

I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).
I tried all these options:
text.setEditable(false);
text.setFocusable(false);
text.setEnabled(false);
text.setHighlighter(null);
but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?
You can't simply set the background color of a component to "transparent" and expect Swing to deal with it. You need to flag the component as transparent (setOpaque(false)), only then will Swing's repaint manager know that it has to update the components under it.
This then leads you to the problem of how to paint the background (as Swing only has the concept of fully opaque or fully transparent).
To do this, you need to supply your own paint routines (override paintComponent, fill the background, update the component)...this is essentially what Rob Camick's solution is doing, it just provides a nice wrapper component for you...
Below is an example of using a JLabel using text wrapped in HTML and a JTextArea, both updated to support "translucency"...
Using a JLabel
Using a JTextArea
Now, it would be a lot easier to achieve using Rob's wrapper class, but this provides you with the idea of what is going wrong and what you would need to do to fix it.
public class MultiLineLabel {
public static void main(String[] args) {
new MultiLineLabel();
}
public MultiLineLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TransclucentLabel extends JLabel {
public TransclucentLabel(String text) {
super(text);
setVerticalAlignment(TOP);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Insets insets = getInsets();
int x = insets.left;
int y = insets.top;
int width = getWidth() - (insets.left + insets.right);
int height = getHeight() - (insets.top + insets.bottom);
g2d.setColor(new Color(255, 0, 0, 128));
g2d.fillRect(x, y, width, height);
super.paintComponent(g);
}
}
public class TransclucentTextArea extends JTextArea {
public TransclucentTextArea(String text) {
super(text);
setOpaque(false);
setLineWrap(true);
setWrapStyleWord(true);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Insets insets = getInsets();
int x = insets.left;
int y = insets.top;
int width = getWidth() - (insets.left + insets.right);
int height = getHeight() - (insets.top + insets.bottom);
g2d.setColor(new Color(255, 0, 0, 128));
g2d.fillRect(x, y, width, height);
super.paintComponent(g);
}
}
public class BackgroundPane extends JPanel {
private BufferedImage background;
public BackgroundPane() {
setLayout(new BorderLayout());
// addLabel();
addTextArea();
setBorder(new EmptyBorder(24, 24, 24, 24));
try {
background = ImageIO.read(new File("/path/to/your/image"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
protected void addTextArea() {
StringBuilder sb = new StringBuilder(128);
sb.append("I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).\n\n");
sb.append("I tried all these options:\n\n");
sb.append("text.setEditable(false);\n");
sb.append("text.setFocusable(false);\n");
sb.append("text.setEnabled(false);\n");
sb.append("text.setHighlighter(null);\n\n");
sb.append("but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?\n");
add(new TransclucentTextArea(sb.toString()));
}
protected void addLabel() {
StringBuilder sb = new StringBuilder(128);
sb.append("<html>");
sb.append("<p>I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).</p><br>");
sb.append("<p>I tried all these options:</p><br>");
sb.append("<p>text.setEditable(false);<br>");
sb.append("text.setFocusable(false);<br>");
sb.append("text.setEnabled(false);<br>");
sb.append("text.setHighlighter(null);</p><br>");
sb.append("<p>but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?</p>");
add(new TransclucentLabel(sb.toString()));
}
#Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
}
}
}
}

Draw border below the text of a component in Swing

I've created a custom border class where I fill a rectangle to act as a background for a component. Note that this border will have a more complex shape in the future, not just a simple rectangle.
When I add my border to a component, the text of the component will appear behind the border and make the text unreadable. (The result is depicted in the image below.)
Is there a way to draw the border below the text?
My border class:
public class CustomBorder extends AbstractBorder {
private static final long serialVersionUID = 1L;
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(125, 125, 125, 255));
g2d.fillRect(x - 10, y - 10, width + 20, height + 20);
}
#Override
public Insets getBorderInsets(Component c) {
return super.getBorderInsets(c);
}
#Override
public Insets getBorderInsets(Component c, Insets insets) {
return super.getBorderInsets(c, insets);
}
#Override
public boolean isBorderOpaque() {
return super.isBorderOpaque();
}
}
Main:
public static void main(String[] args) {
JLabel label = new JLabel("JLabel text");
label.setBorder(new CompoundBorder(new EmptyBorder(50, 20, 20, 20), new CustomBorder()));
JFrame frame = new JFrame("");
frame.setLayout(new FlowLayout());
frame.setSize(200, 200);
frame.add(label);
frame.setVisible(true);
}
Edit: I should also note that I will be using this border to a chat program, which will be using bubble-shaped messages, so a colored square using setBackground() is a no-no.
See A Closer Look at the Paint Mechanism which explains how the painting is done. The border is painted after the text of the label is painted.
What exactly are you trying to do? Your border painting code doesn't make sense. You are trying to fill a rectangle equal to the width/height of the component + 20 pixels, which means you are trying to paint an area larger than the component.
If you are just trying to paint a background on a label then you can use:
label.setOpaque( true );
label.setBackground(...);
Edit: The code in this answer that was linked in the comment section below solved the problem.
You could always use g2d.drawString().
However, if that is not to be utilised for some reason, you could just do:
JLabel l = new JLabel("foo");
l.setBackground(Color.GRAY);
l.setOpaque(true);

what is Alternative of Paint and repaint function?

Is there any function which can be replaced with paint() and repaint()in java.
I have a scenario.
There is a triangle (Triangle 1). when user will click in triangle another triangle (Triangle 2) will appear and 1st (Triangle 1) will be removed from screen. (coded using JFrame, paint() and repaint())
I have achieved it so far. but problem is when I minimize or change size of window with mouse the output window, it just paint again Triangle 1 rather than Triangle 2. OR Clear the whole screen if i call g2d.clearRect(0, 0, 1000, 1000);
triangle.reset();
Note: These both functions are to remove previous triangle (Triangle 1).
Is there any function that state should not be changed on minimize or when window size changed ?
or can we override repaint() or anything helping according to scenario.
Here is the Working code. Execute it, Click in triangle then minimize and see again. You will get the problem more clearly.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Triangle_shape extends JFrame implements ActionListener {
public static JButton btnSubmit = new JButton("Submit");
public Triangle_shape() {
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLayout(new BorderLayout());
frame.add(new TrianglePanel(), BorderLayout.CENTER);
frame.add(btnSubmit, BorderLayout.PAGE_END);
frame.pack();
frame.repaint();
frame.setTitle("A Test Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public static class TrianglePanel extends JPanel implements MouseListener {
private Polygon triangle, triangle2;
public TrianglePanel() {
//Create triangle
triangle = new Polygon();
triangle.addPoint(400, 550); //left
triangle.addPoint(600, 550); //right
triangle.addPoint(500, 350); //top
//Add mouse Listener
addMouseListener(this);
//Set size to make sure that the whole triangle is shown
setPreferredSize(new Dimension(300, 300));
}
/**
* Draws the triangle as this frame's painting
*/
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.draw(triangle);
}
//Required methods for MouseListener, though the only one you care about is click
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
/**
* Called whenever the mouse clicks. Could be replaced with setting the
* value of a JLabel, etc.
*/
public void mouseClicked(MouseEvent e) {
Graphics2D g2d = (Graphics2D) this.getGraphics();
Point p = e.getPoint();
if (triangle.contains(p)) {
System.out.println("1");
g2d.clearRect(0, 0, 1000, 1000);
triangle.reset();
g2d.setColor(Color.MAGENTA);
triangle2 = new Polygon();
triangle2.addPoint(600, 550); // left
triangle2.addPoint(700, 350); //top
triangle2.addPoint(800, 550); //right
g2d.draw(triangle2);
} else {
System.out.println("Triangle dont have point");
}
}
}
}
paint() and repaint() work fine, but you are not using them as they are designed to be used. The window system doesn't keep a persistent image of what a component looks like. It expects your component to be able to repaint its entire appearance on demand (such as when the window is resized or un-minimized).
If you grab a Graphics object with getGraphics() and draw something on the component, the stuff you draw will indeed be lost if/when the entire component needs to be repainted. So you should not do that, but instead make sure your paintComponent method has all the information it needs to completely repaint the component.
If you only want one triangle on the screen at once, do not create a separate variable triangle2. Just replace the one triangle you have by altering your mouse click handler as follows:
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
if (triangle.contains(p)) {
triangle = new Polygon();
triangle.addPoint(600, 550); // left
triangle.addPoint(700, 350); //top
triangle.addPoint(800, 550); //right
repaint();
} else {
System.out.println("Point not in triangle");
}
}
Your paintComponent method should call super.paintComponent to ensure the background is painted, but otherwise you do not need to change it:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.draw(triangle);
}
Alternatively if you are trying to keep multiple triangles on the screen, for example, to add a new one at every click, you should add them into a list of shapes which will be drawn whenever the component needs to be repainted:
private final List<Shape> shapes = new ArrayList<>();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for (Shape s : shapes)
g2d.draw(s);
}
Then to control the set of shapes that is on screen, manipulate the contents of the list, and call repaint();.
For instance, to add a new shape to the ones on screen:
Polygon triangle = new Polygon();
triangle.addPoint(200, 300);
triangle.addPoint(200, 200);
triangle.addPoint(300, 200);
shapes.add(triangle);
repaint();
To remove all shapes from the screen:
shapes.clear();
repaint();
You should also make sure that you switch to the Swing thread at the start of the program, because it is not safe to interact with Swing components from the main thread. In main:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
.
.
.
frame.setVisible(true);
}
});
}
Your mouseClicked method should not create a new Triangle object. After resetting triangle just add new points to it. Also don't draw in this method but call repaint:
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
if (triangle.contains(p)) {
System.out.println("1");
triangle.reset(); // change the current triangle
triangle.addPoint(600, 550); // new left
triangle.addPoint(700, 350); // new top
triangle.addPoint(800, 550); // new right
repaint(); // force repainting
} else {
System.out.println("Triangle dont have point");
}
}
Now if you want many triangles you should have a collection of Polygons. Like this :
public static class TrianglePanel extends JPanel implements MouseListener {
private Vector<Polygon> triangles;
public TrianglePanel() {
n = 0;
// Create an empty collection
triangles = new Vector<Polygon>();
//Create first triangle
Polygon triangle = new Polygon();
triangle.addPoint(400, 550); //left
triangle.addPoint(600, 550); //right
triangle.addPoint(500, 350); //top
// Add the triangle to the collection
triangles.add(triangle);
//Add mouse Listener
addMouseListener(this);
//Set size to make sure that the whole triangle is shown
setPreferredSize(new Dimension(300, 300));
}
/**
* Draws the triangles as this frame's painting
*/
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
for (Polygon p : triangles) // Draw all triangles in the collection
g2d.draw(p);
}
//Required methods for MouseListener, though the only one you care about is click
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
/**
* Called whenever the mouse clicks. Could be replaced with setting the
* value of a JLabel, etc.
*/
public void mouseClicked(MouseEvent e) {
Graphics2D g2d = (Graphics2D) this.getGraphics();
Point p = e.getPoint();
// Do what you want with p and the collection
// For example : remove all triangles that contain the point p
ListIterator<Polygon> li = triangles.listIterator();
while (li.hasNext()) {
if (li.next().containsâ„—) li.remove();
}
// Do what you want to update the list
// For example: Add a new triangle...
Polygon triangle = new Polygon();
triangle.addPoint(600+n, 550); // left
triangle.addPoint(700+n, 350); //top
triangle.addPoint(800+n, 550); //right
triangles.add(triangle); // add the new triangle to the list
n += 10; // next new triangle will be "moved" right
repaint();
}
private int n;
}

JTextArea not selectable, but still showing a "ghost" cursor

I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).
I tried all these options:
text.setEditable(false);
text.setFocusable(false);
text.setEnabled(false);
text.setHighlighter(null);
but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?
You can't simply set the background color of a component to "transparent" and expect Swing to deal with it. You need to flag the component as transparent (setOpaque(false)), only then will Swing's repaint manager know that it has to update the components under it.
This then leads you to the problem of how to paint the background (as Swing only has the concept of fully opaque or fully transparent).
To do this, you need to supply your own paint routines (override paintComponent, fill the background, update the component)...this is essentially what Rob Camick's solution is doing, it just provides a nice wrapper component for you...
Below is an example of using a JLabel using text wrapped in HTML and a JTextArea, both updated to support "translucency"...
Using a JLabel
Using a JTextArea
Now, it would be a lot easier to achieve using Rob's wrapper class, but this provides you with the idea of what is going wrong and what you would need to do to fix it.
public class MultiLineLabel {
public static void main(String[] args) {
new MultiLineLabel();
}
public MultiLineLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TransclucentLabel extends JLabel {
public TransclucentLabel(String text) {
super(text);
setVerticalAlignment(TOP);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Insets insets = getInsets();
int x = insets.left;
int y = insets.top;
int width = getWidth() - (insets.left + insets.right);
int height = getHeight() - (insets.top + insets.bottom);
g2d.setColor(new Color(255, 0, 0, 128));
g2d.fillRect(x, y, width, height);
super.paintComponent(g);
}
}
public class TransclucentTextArea extends JTextArea {
public TransclucentTextArea(String text) {
super(text);
setOpaque(false);
setLineWrap(true);
setWrapStyleWord(true);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Insets insets = getInsets();
int x = insets.left;
int y = insets.top;
int width = getWidth() - (insets.left + insets.right);
int height = getHeight() - (insets.top + insets.bottom);
g2d.setColor(new Color(255, 0, 0, 128));
g2d.fillRect(x, y, width, height);
super.paintComponent(g);
}
}
public class BackgroundPane extends JPanel {
private BufferedImage background;
public BackgroundPane() {
setLayout(new BorderLayout());
// addLabel();
addTextArea();
setBorder(new EmptyBorder(24, 24, 24, 24));
try {
background = ImageIO.read(new File("/path/to/your/image"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
protected void addTextArea() {
StringBuilder sb = new StringBuilder(128);
sb.append("I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).\n\n");
sb.append("I tried all these options:\n\n");
sb.append("text.setEditable(false);\n");
sb.append("text.setFocusable(false);\n");
sb.append("text.setEnabled(false);\n");
sb.append("text.setHighlighter(null);\n\n");
sb.append("but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?\n");
add(new TransclucentTextArea(sb.toString()));
}
protected void addLabel() {
StringBuilder sb = new StringBuilder(128);
sb.append("<html>");
sb.append("<p>I put a JTextArea in a JPanel. This JPanel has a picture on the background, and the JTextArea is translucent (translucid red) to show the background through. I don't want the user to be able to edit or select the text, I want it to act just as a JLabel (but with multiple lines and easy to word wrap and adjust to screen resize).</p><br>");
sb.append("<p>I tried all these options:</p><br>");
sb.append("<p>text.setEditable(false);<br>");
sb.append("text.setFocusable(false);<br>");
sb.append("text.setEnabled(false);<br>");
sb.append("text.setHighlighter(null);</p><br>");
sb.append("<p>but still some change of color happens as the user drags the mouse over the JTextArea. Anyone knows what is going on?</p>");
add(new TransclucentLabel(sb.toString()));
}
#Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
}
}
}
}

Image mapping like feature in Java swing, Points vs GeneralPath

My gaol is to draw several images using 2D graphics in a paintComponent() method. However, I'm not sure how I could add a MouseListener such that each image would know if it was selected.
My solution thus far is too simply record the coordinates of the mouse click, and see if they are contained within the boundaries of each of the images. However this will be difficult with images that have more complex boundaries.
Another option would be too create simple shapes and place them over the images, but again images with more complex boundaries will be difficult. In another discussion on SO found
here, someone mentioned using GeneralPath to draw more complex shapes. I have never played with is, but this seems encouraging.
Of these 2 options, what seems to be the best solution, or are there other recommendations
Are you images painted on top of one another or are they drawn separately.
If they are drawn separately, then you should do the custom painting on a JComponent. Then you can do the drawing by using the GeneralPath. You will also need to implement the contains(...) method by checking if the mouseclick is contained in the GeneralPath. If the contains() method is implemented properly then the MouseListener will respond properly.
Here is a simpler example:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class RoundButton extends JButton {
public RoundButton(String label) {
super(label);
// These statements enlarge the button so that it
// becomes a circle rather than an oval.
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width, size.height);
setPreferredSize(size);
// This call causes the JButton not to paint the background.
// This allows us to paint a round background.
setContentAreaFilled(false);
}
// Paint the round background and label.
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
// You might want to make the highlight color
// a property of the RoundButton class.
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width-1, getSize().height-1);
// This call will paint the label and the focus rectangle.
super.paintComponent(g);
}
// Paint the border of the button using a simple stroke.
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
// Hit detection.
Shape shape;
public boolean contains(int x, int y) {
// If the button has changed size, make a new shape object.
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}
// Test routine.
public static void main(String[] args) {
// Create a button with the label "Jackpot".
JButton button = new RoundButton("Jackpot");
button.setBackground(Color.green);
button.setBounds(0, 0, 100, 100);
JButton button2 = new RoundButton("Jackpot2");
button2.setBackground(Color.red);
button2.setBounds(50, 50, 100, 100);
// Create a frame in which to show the button.
JFrame frame = new JFrame();
frame.getContentPane().setBackground(Color.yellow);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(button);
frame.getContentPane().add(button2);
// frame.getContentPane().setLayout(new FlowLayout());
frame.setSize(200, 200);
frame.setVisible(true);
MouseListener mouseListener = new MouseAdapter() {
public void mouseEntered( MouseEvent e )
{}
public void mouseExited( MouseEvent e )
{}
public void mouseClicked( MouseEvent e )
{
System.out.println( "clicked " );
}
public void mousePressed( MouseEvent e )
{
System.out.println( "pressed " );
}
public void mouseReleased( MouseEvent e )
{
System.out.println( "released " );
}
};
button.addMouseListener( mouseListener );
}
}

Categories

Resources