Design Custom Box Class To Be Displayed In Applet - java

import java.awt.Color;
import java.awt.Graphics;
public class Box {
public static int length;
private int upperLeftX;
private int upperLeftY;
private int height;
private int width;
private Color boxColor;
public Box(int upperX, int upperY, int h, int w, Color myColor) {
this.upperLeftX = upperX;
this.upperLeftY = upperY;
this.height = h;
this.width = w;
this.boxColor = myColor;
this. setBoxColor(Color.BLUE);
this. setBoxColor(Color.CYAN);
this. setBoxColor(Color.BLACK);
this. setBoxColor(Color.DARK_GRAY);
this. setBoxColor(Color.GRAY);
this.setBoxColor(Color.LIGHT_GRAY);
this.setBoxColor(Color.MAGENTA);
this.setBoxColor(Color.ORANGE);
this.setBoxColor(Color.PINK);
this.setBoxColor(Color.RED);
this.setBoxColor(Color.WHITE);
this.setBoxColor(Color.YELLOW);
this.setBoxColor(Color.BLACK);
this.setBoxColor(Color.GREEN);
this.setBoxColor(Color.PINK);
}
public Box() {
}
public int getUpperLeftX() {
return upperLeftX;
}
public void setUpperLeftX(int upperLeftX) {
this.upperLeftX = upperLeftX;
}
public int getUpperLeftY() {
return upperLeftY;
}
public void setUpperLeftY(int upperLeftY) {
this.upperLeftY = upperLeftY;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public Color getBoxColor() {
return boxColor;
}
public void setBoxColor(Color boxColor) {
this.boxColor = boxColor;
}
public void display(Graphics g) {
g.setColor(boxColor);
g.fillRect(upperLeftX, upperLeftY, width, height);
}
}
import java.awt.*;
import java.applet.Applet;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Grid extends Applet implements ActionListener{
public Button changeButton;
public Button changeColorButton;
public void init() {
resize(400, 500);
setBackground(Color.white);
changeButton = new Button("Change");
add(changeButton);
changeButton.addActionListener(this); {
}
add(changeButton);
}
public void paint(Graphics g){
changeButton.setLocation(150, 450);
Box greenBox = new Box(0, 0, 100, 100, Color.GREEN);
greenBox.display(g);
Box blueBox = new Box(0, 100, 100, 100, Color.BLUE);
blueBox.display(g);
Box cyanBox = new Box(0, 200, 100, 100, Color.CYAN);
cyanBox.display(g);
Box blackBox = new Box(0, 300, 100, 100, Color.BLACK);
blackBox.display(g);
Box darkGrayBox = new Box(100, 0, 100, 100, Color.DARK_GRAY);
darkGrayBox.display(g);
Box grayBox = new Box(100, 100, 100, 100, Color.GRAY);
grayBox.display(g);
Box lightGrayBox = new Box(100, 200, 100, 100, Color.LIGHT_GRAY);
lightGrayBox.display(g);
Box magentaBox = new Box(100, 300, 100, 100, Color.MAGENTA);
magentaBox.display(g);
Box orangeBox = new Box(200, 0, 100, 100, Color.ORANGE);
orangeBox.display(g);
Box pingBox = new Box(200, 100, 100, 100, Color.PINK);
pingBox.display(g);
Box redBox = new Box(200, 200, 100, 100, Color.RED);
redBox.display(g);
Box whiteBox = new Box(200, 300, 100, 100, Color.WHITE);
whiteBox.display(g);
Box yellowBox = new Box(300, 0, 100, 100, Color.YELLOW);
yellowBox.display(g);
Box blackBox1 = new Box(300, 100, 100, 100, Color.BLACK);
blackBox1.display(g);
Box greenBox1 = new Box(300, 200, 100, 100, Color.GREEN);
greenBox1.display(g);
Box pingBox1 = new Box(300, 300, 100, 100, Color.PINK);
pingBox1.display(g);
}
public String getChangeColorButton() {
return getChangeColorButton();
}
public void setChangeColorButton(Button changeColorButton) {
this.changeColorButton = changeColorButton;
}
public void actionPerformed(ActionEvent e) {
}
}

Related

Flappy bird Pipes how to randomize in java the program I am using for school is JGrasp

In the paint component.graphics g I was creating pipes for my flappy bird game but I don't know how to approach making multiple pipes that are randomized. I've made the first one randomize but I don't know how to make more and have those new ones be randomized. Does anyone know any ways I can do this?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class FlappyPanel extends JPanel
{
private static final int FRAME = 1000;
private static final Color BACKGROUND = new Color(135, 206, 235);
private static final Color GREEN = new Color(0, 255, 0);
private BufferedImage myImage;
private Graphics myBuffer;
private Polkadot pd;
private Timer t;
int top = (int)(Math.random()*1000/2);
int bot = (int)(Math.random()*1000/2);
int x = 1000;
int w = 20;
int speed = 1;
public FlappyPanel()
{
myImage = new BufferedImage(400, 400, 1);
myBuffer = this.myImage.getGraphics();
pd = new Polkadot(200, 200, 25, Color.black);
pd.jump(400, 400);
pd.setX(75);
pd.setY(200);
setFocusable(true);
t = new Timer(10, new Listener());
t.start();
addKeyListener(new Key());
setFocusable(true);
}
public void paintComponent(Graphics g)
{
g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
g.setColor(GREEN);
g.drawRect(x, 0, w, top);
g.drawRect(x, 1000-bot, w, bot);
g.fillRect(x, 0, w, top);
g.fillRect(x, 1000-bot, w, bot);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
x -= speed;
myBuffer.setColor(BACKGROUND);
myBuffer.fillRect(0, 0, FRAME, FRAME);
if(pd.getY()+1 <= 400)
{
pd.setY(pd.getY()+1);
}
pd.draw(myBuffer);
repaint();
}
}
private class Key extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_UP)//bumper2 goes up 30 pixels when UP arrow key is pressed
{
if(pd.getY()-1 >= 0){
pd.setY(pd.getY()-50);//stops pd from getting out of frame
}
}
}
}
}

Draw a rectangle over image in Java

I am trying to draw a rectangle over Image using java.awt classes. For that I used below sample code:
public class DrawRectangle {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
}
class TestPane extends JPanel {
private BufferedImage myImage;
private Rectangle myOffice = new Rectangle(150, 50, 30, 20);
public TestPane() {
try {
File image = new File("C:\\Users\\NNaphade\\work\\ImageDetection\\Trial_Pascal_VOC\\test_image\\IMG_20180327_110210.jpg");
if(image.exists())
myImage = ImageIO.read(image);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
System.out.println("image exist!!!!!!");
return myImage == null ? new Dimension(200, 200) : new Dimension(
myImage.getWidth(), myImage.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (myImage != null) {
g2d.drawImage(myImage, 0, 0, 1000, 1000, this);
g2d.setColor(Color.RED);
g2d.translate(0, 0);
g2d.draw(myOffice);
}
g2d.dispose();
}
}
This works correct and output is displayed as expected. Here I am fixing the parameters for rectangle as:
private Rectangle myOffice = new Rectangle(150, 50, 30, 20);
However, in my application, I want to pass these parameters from another method. I want to pass these x1, y1, w and h to TestPane class given above. I tried changing the TestPane constructor by passing these 4 parameters, but I am not able to set them as instance variables. E.g. the following code doesn't work.
private void markWithBoundingBox(INDArray testData, int gridWidth, int gridHeight, double w, double h, DetectedObject obj) {
double[] xy1 = obj.getTopLeftXY();
int predictedClass = obj.getPredictedClass();
int x1 = (int) Math.round(w * xy1[0] / gridWidth);
int y1 = (int) Math.round(h * xy1[1] / gridHeight);
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane(x1, y1, w, h));
frame.pack();
frame.setVisible(true);
}
});
}
class TestPane extends JPanel {
private BufferedImage myImage;
//private Rectangle myOffice = new Rectangle(50, 50, 3, 20);
public TestPane(int x, int y, double w, double h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
try {
File file = new File("C:\\Users\\NNaphade\\work\\ImageDetection\\Trial_Pascal_VOC\\test_image\\IMG_20180327_110210.jpg");
if(file.exists()) {
myImage = ImageIO.read(file);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return myImage == null ? new Dimension(100, 100) : new Dimension(
myImage.getWidth(), myImage.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (myImage != null) {
g2d.drawImage(myImage, 0, 0, 2000, 2000, this);
g2d.setColor(Color.RED);
g2d.translate(0, 0);
g2d.draw(new Rectangle(this.x, this.y, this.w, this.h));
}
g2d.dispose();
}
}
It seems to me that TestPane here is not a class but the component. because Java compiler doesn't let me declare the instance variables in the constructor and all the available methods there are of component. How can I get rid of this issue?

AWT paints only last-added Canvas

I've a VERY simple AWT Painting. Just playing aound to make something bigger. But can't get it working ...
What happens is that only elypse2 is shown - regardless of repaint()ing it or not.
I also tried to use Swing components instead of AWT (JFrame, JComponent) but this also changes nothing.
Is using a Layout Manager necessary? But I want to draw only graphical components, like arcs, rectangles, line, poly-lines, aso ...
Here's the main():
public static void main(String[] args) {
Frame testFrame = new Frame("Grafx-Test");
testFrame.setSize(300, 200);
testFrame.setAlwaysOnTop(true);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
testFrame.setVisible(true);
}
});
Elypse elypse = new Elypse(new Point(70, 80), 30, 30, Color.BLUE, false);
testFrame.add(elypse);
Elypse elypse2 = new Elypse(new Point(70, 50), 50, 30, Color.BLUE, true);
testFrame.add(elypse2);
}
and here the used class:
public class Elypse extends Canvas {
private Point start;
private int width;
private int height;
private Color c;
private boolean filled;
public Elypse(Point start, int width, int height, Color c, boolean filled) {
this.start = start;
this.width = width;
this.height = height;
this.c = c;
this.filled = filled;
}
#Override
public void paint(Graphics g) {
g.setColor(c);
if (filled) {
g.fillOval(start.x, start.y, width, height);
}
else {
g.drawOval(start.x, start.y, width, height);
}
}
}
You neglect to pack() the enclosing Window. Note the characteristic symptom in your original code: resizing the frame, which generates an update, causes elypse2 to appear.
Addendum: You can see both Elypse instances by using a layout such as GridLayout.
testFrame.setLayout(new GridLayout(0, 1));
As tested:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;
public class Test {
public static void main(String[] args) {
Frame testFrame = new Frame("Grafx-Test");
testFrame.setAlwaysOnTop(true);
Elypse elypse = new Elypse(new Point(70, 80), 30, 30, Color.BLUE, false);
testFrame.add(elypse);
Elypse elypse2 = new Elypse(new Point(70, 50), 50, 30, Color.BLUE, true);
testFrame.add(elypse2);
testFrame.pack();
testFrame.setVisible(true);
}
private static class Elypse extends Canvas {
private Point start;
private int width;
private int height;
private Color c;
private boolean filled;
public Elypse(Point start, int width, int height, Color c, boolean filled) {
this.start = start;
this.width = width;
this.height = height;
this.c = c;
this.filled = filled;
}
#Override
public void paint(Graphics g) {
g.setColor(c);
if (filled) {
g.fillOval(start.x, start.y, width, height);
} else {
g.drawOval(start.x, start.y, width, height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
}
}

Very slow scrolling in JScrollPane when using per-pixel transparency

I am using per-pixel transparency using AWTUtilities.setWindowOpaque() on JFrame, that contains JScrollPane. When transparency is on, the scrolling in that pane is very slow and laggy, without it is not. Trying this on Windows 7 and JDK 6.
public class MainFrame extends JFrame {
super();
setUndecorated(true);
AWTUtilities.setWindowOpaque(this, false); //this turns JScrollPane inside of this JFrame slow and laggy
}
Have anyone issued this? Thanks!
I can't see any scrolling issue, nor to create testing scenario for code that is based on good Swing rules, this code is quite too hard for processor(s) and GPU, Java6, Win7 64b
from code
import com.sun.awt.AWTUtilities;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableModel;
public class ViewPortFlickeringOriginal {
private JFrame frame = new JFrame("Table");
private JViewport viewport = new JViewport();
private Rectangle RECT = new Rectangle();
private Rectangle RECT1 = new Rectangle();
private JTable table = new JTable(50, 3);
private javax.swing.Timer timer;
private int count = 0;
private GradientViewPortOriginal tableViewPort;
private static boolean loggerOpacity;
private JPanel panel = new JPanel();
private static JButton button;
public ViewPortFlickeringOriginal() {
tableViewPort = new GradientViewPortOriginal(table);
viewport = tableViewPort.getViewport();
viewport.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (tableViewPort.bolStart) {
RECT = table.getCellRect(0, 0, true);
RECT1 = table.getCellRect(table.getRowCount() - 1, 0, true);
Rectangle viewRect = viewport.getViewRect();
if (viewRect.intersects(RECT)) {
System.out.println("Visible RECT -> " + RECT);
tableViewPort.paintBackGround(new Color(250, 150, 150));
} else if (viewRect.intersects(RECT1)) {
System.out.println("Visible RECT1 -> " + RECT1);
tableViewPort.paintBackGround(new Color(150, 250, 150));
} else {
System.out.println("Visible RECT1 -> ???? ");
tableViewPort.paintBackGround(new Color(150, 150, 250));
}
}
}
});
frame.add(tableViewPort);
button = new JButton("Change Opacity for Java6 / Win7");
button.setBounds(100, 100, 50, 50);
button.setVisible(true);
panel.add(button);
loggerOpacity = true;
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == button && loggerOpacity) {
AWTUtilities.setWindowOpacity(frame, 0.80f);
}
}
});
frame.add(panel, BorderLayout.SOUTH);
frame.setPreferredSize(new Dimension(600, 300));
frame.pack();
frame.setLocation(50, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RepaintManager.setCurrentManager(new RepaintManager() {
#Override
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
Container con = c.getParent();
while (con instanceof JComponent) {
if (!con.isVisible()) {
return;
}
if (con instanceof GradientViewPortOriginal) {
c = (JComponent) con;
x = 0;
y = 0;
w = con.getWidth();
h = con.getHeight();
}
con = con.getParent();
}
super.addDirtyRegion(c, x, y, w, h);
}
});
frame.setVisible(true);
start();
}
private void start() {
timer = new javax.swing.Timer(100, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("updating row " + (count + 1));
TableModel model = table.getModel();
int cols = model.getColumnCount();
int row = 0;
for (int j = 0; j < cols; j++) {
row = count;
table.changeSelection(row, 0, false, false);
timer.setDelay(100);
Object value = "row " + (count + 1) + " item " + (j + 1);
model.setValueAt(value, count, j);
}
count++;
if (count >= table.getRowCount()) {
timer.stop();
table.changeSelection(0, 0, false, false);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
table.clearSelection();
tableViewPort.bolStart = true;
}
});
}
}
};
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ViewPortFlickeringOriginal viewPortFlickering = new ViewPortFlickeringOriginal();
}
});
}
}
class GradientViewPortOriginal extends JScrollPane {
private static final long serialVersionUID = 1L;
private final int h = 50;
private BufferedImage img = null;
private BufferedImage shadow = new BufferedImage(1, h, BufferedImage.TYPE_INT_ARGB);
private JViewport viewPort;
public boolean bolStart = false;
public GradientViewPortOriginal(JComponent com) {
super(com);
viewPort = this.getViewport();
viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE);
viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
paintBackGround(new Color(250, 150, 150));
}
public void paintBackGround(Color g) {
Graphics2D g2 = shadow.createGraphics();
g2.setPaint(g);
g2.fillRect(0, 0, 1, h);
g2.setComposite(AlphaComposite.DstIn);
g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h,
new Color(0.1f, 0.8f, 0.8f, 0.5f)));
g2.fillRect(0, 0, 1, h);
g2.dispose();
}
#Override
public void paint(Graphics g) {
if (img == null || img.getWidth() != getWidth() || img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
super.paint(g2);
Rectangle bounds = getViewport().getVisibleRect();
g2.scale(bounds.getWidth(), -1);
int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight();
g2.drawImage(shadow, bounds.x, -bounds.y - y - h, null);
g2.scale(1, -1);
g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h + y, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
}
}
but I'm able to demonstrating lazy scrolling for JScrollPane contains others JComponents as is JTable or JList or JTextArea or JTextPane
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
public class ListPanel extends JFrame {
private static final long serialVersionUID = 1L;
public ListPanel() {
setLayout(new GridLayout(0, 2, 10, 10));
DefaultListModel model = new DefaultListModel();
model.addElement(createButtons("one"));
model.addElement(createButtons("two"));
model.addElement(createButtons("three"));
model.addElement(createButtons("four"));
model.addElement(createButtons("five"));
model.addElement(createButtons("six"));
model.addElement(createButtons("seven"));
model.addElement(createButtons("eight"));
model.addElement(createButtons("nine"));
model.addElement(createButtons("ten"));
model.addElement(createButtons("eleven"));
model.addElement(createButtons("twelwe"));
JList list = new JList(model);
list.setCellRenderer(new PanelRenderer());
JScrollPane scroll1 = new JScrollPane(list);
final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar.getValue());
}
});
add(scroll1);
JScrollPane scroll2 = new JScrollPane(createPanel());
add(scroll2);
final JScrollBar scrollBar1 = scroll2.getVerticalScrollBar();
scrollBar1.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar1.getValue());
}
});
}
public static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 1, 1));
panel.add(createButtons("one"));
panel.add(createButtons("two"));
panel.add(createButtons("three"));
panel.add(createButtons("four"));
panel.add(createButtons("five"));
panel.add(createButtons("six"));
panel.add(createButtons("seven"));
panel.add(createButtons("eight"));
panel.add(createButtons("nine"));
panel.add(createButtons("ten"));
panel.add(createButtons("eleven"));
panel.add(createButtons("twelwe"));
return panel;
}
public static JButton createButtons(String text) {
JButton button = new JButton(text);
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ListPanel frame = new ListPanel();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//frame.pack();
frame.setSize(270, 200);
frame.setVisible(true);
}
});
}
class PanelRenderer implements ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JButton renderer = (JButton) value;
renderer.setBackground(isSelected ? Color.red : list.getBackground());
return renderer;
}
}
}

Creating a custom button in Java with JButton

I am trying to create a button that has a custom shape (hexagon), but otherwise acts like a normal JButton would (that is, works with an ActionListener).
I have created a class that extends AbstractButton, but it doesn't seem to be sending events to the ActionListener when I click it. If I change the class to extend JButton it works perfectly, but it screws up the way the button is displayed. I'm assuming that there is a method that I need to override to get it to fire events, but I can't figure out what it is.
If you want to create a CustomButtonUI then you have to look
deepest to the BasicXxxUI.
overide List of Colors from JButton
Note there isn't paintComponent(). It's wrong, just use the paint() method,
Below is just a simple example if that is possible (for Metal JButton). Note just for Metal LaF, I'm so lazy and there isn't something about override paintText, paintIcon, paintFocus, paintBorder (for all funcionalities you have to check available methods from BasicButtonUI), and something I put to the ButtonModel, just for my enjoyment.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.metal.MetalButtonUI;
public class TextAreaInButton {
private JFrame frame = new JFrame("sssssssss");
private JButton tip1Null = new JButton(" test button ");
public TextAreaInButton() {
Border line, raisedbevel, loweredbevel, title, empty;
line = BorderFactory.createLineBorder(Color.black);
raisedbevel = BorderFactory.createRaisedBevelBorder();
loweredbevel = BorderFactory.createLoweredBevelBorder();
title = BorderFactory.createTitledBorder("");
empty = BorderFactory.createEmptyBorder(1, 1, 1, 1);
final Border compound;
Color crl = (Color.blue);
compound = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl));
Color crl1 = (Color.red);
final Border compound1;
compound1 = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl1));
Color crl2 = (Color.black);
final Border compound2;
compound2 = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl2));
tip1Null.setFont(new Font("Serif", Font.BOLD, 14));
tip1Null.setForeground(Color.darkGray);
tip1Null.setPreferredSize(new Dimension(50, 30));
tip1Null.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
tip1Null.setBorderPainted(true);
tip1Null.setFocusPainted(false);
tip1Null.setBorder(compound);
tip1Null.setHorizontalTextPosition(SwingConstants.CENTER);
tip1Null.setVerticalTextPosition(SwingConstants.BOTTOM);
tip1Null.setUI(new ModifButtonUI());
tip1Null.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isRollover()) {
tip1Null.setBorder(compound1);
} else {
tip1Null.setBorder(compound);
}
if (model.isPressed()) {
tip1Null.setBorder(compound2);
}
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tip1Null, BorderLayout.CENTER);
frame.setLocation(150, 150);
frame.setPreferredSize(new Dimension(310, 75));
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TextAreaInButton taib = new TextAreaInButton();
}
});
}
}
class OldRoundedBorderLine extends AbstractBorder {
private final static int MARGIN = 5;
private static final long serialVersionUID = 1L;
private Color color;
OldRoundedBorderLine(Color clr) {
color = clr;
}
public void setColor(Color clr) {
color = clr;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(color);
g.drawRoundRect(x, y, width, height, MARGIN, MARGIN);
}
#Override
public Insets getBorderInsets(Component c) {
return new Insets(MARGIN, MARGIN, MARGIN, MARGIN);
}
#Override
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = MARGIN;
insets.top = MARGIN;
insets.right = MARGIN;
insets.bottom = MARGIN;
return insets;
}
}
class ModifButtonUI extends MetalButtonUI {
private static final ModifButtonUI buttonUI = new ModifButtonUI();
ModifButtonUI() {
}
public static ComponentUI createUI(JComponent c) {
return new ModifButtonUI();
}
#Override
public void paint(Graphics g, JComponent c) {
final Color color1 = new Color(230, 255, 255, 0);
final Color color2 = new Color(255, 230, 255, 64);
final Color alphaColor = new Color(200, 200, 230, 64);
final Color color3 = new Color(
alphaColor.getRed(), alphaColor.getGreen(), alphaColor.getBlue(), 0);
final Color color4 = new Color(
alphaColor.getRed(), alphaColor.getGreen(), alphaColor.getBlue(), 64);
super.paint(g, c);
Graphics2D g2D = (Graphics2D) g;
GradientPaint gradient1 = new GradientPaint(
0.0F, (float) c.getHeight() / (float) 2, color1, 0.0F, 0.0F, color2);
Rectangle rec1 = new Rectangle(0, 0, c.getWidth(), c.getHeight() / 2);
g2D.setPaint(gradient1);
g2D.fill(rec1);
GradientPaint gradient2 = new GradientPaint(
0.0F, (float) c.getHeight() / (float) 2, color3, 0.0F, c.getHeight(), color4);
Rectangle rec2 = new Rectangle(0, c.getHeight() / 2, c.getWidth(), c.getHeight());
g2D.setPaint(gradient2);
g2D.fill(rec2);
}
#Override
public void paintButtonPressed(Graphics g, AbstractButton b) {
paintText(g, b, b.getBounds(), b.getText());
g.setColor(Color.red.brighter());
g.fillRect(0, 0, b.getSize().width, b.getSize().height);
}
public void paintBorder(Graphics g) {
}
#Override
protected void paintFocus(Graphics g, AbstractButton b,
Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {
}
}
You will have to extend JButton class not AbstractButton. Try the following things and you will get idea.
The first move is to subclass JButton.
Then, in your subclass, start by redefining the paintComponent(Graphics) method. If you want any changes.
Then, override paintBorder(Graphics) to give it a shape of hexagon.
I know this question has been answered, but you might want to look at using the built-in methods, and using images to draw your button in different states.
Here is a bit of code I used to generate a custom button.
BufferedImage startButton = ImageIO.read(getClass().getResource("/icons/standard/buttons/start_backup.png"));
BufferedImage startButtonHover = ImageIO.read(getClass().getResource("/icons/standard/buttons/start_backup_hover.png"));
BufferedImage startButtonActive = ImageIO.read(getClass().getResource("/icons/standard/buttons/start_backup_active.png"));
JButton startBackupButton = new JButton(new ImageIcon(startButton));
startBackupButton.setRolloverIcon(new ImageIcon(startButtonHover));
startBackupButton.setPressedIcon(new ImageIcon(startButtonActive));
startBackupButton.setBorder(BorderFactory.createEmptyBorder());
startBackupButton.setContentAreaFilled(false);
startBackupButton.setFocusable(false);
You can then add an action listener to it as normal.
try a Jlabel and use an image for any shape!!
JLabel lbl = new JLabel("");
lbl.setIcon(new ImageIcon("shape.png"));
lbl.setBounds(548, 11, 66, 20);
contentPane.add(lbl);
lbl.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
System.exit(0);
}
});

Categories