Make JButton clickable instead of JLabel - java

I have a case where I put the JLabel inside JButton and adapts the JButton size.
The issue here is everytime I click the button, the JLabel catches most of the events.
When I tried to add ActionListener to the JButton, it didn't work.
But when I tried to add MouseListener to JLabel, all the event handlers work.
I want the ActionListener for the JButton to work. I don't want the JLabel to catches all of the events without destroying my default configuration on them.
I tried setting the JLabel focusable property to false but it didn't work also.
So what should I do then?

I have a case where I put the JLabel inside JButton and adapts the
JButton size.
this is basic property, by default top layed JComponent consume all events came from Mouse & Keyboard
there are two ways
(no idea why is there JLabel) if is possible to use plain JButton with implemented methods in API instead
add MouseListener (maybe there no reason to override all MouseEvents add only MouseAdapter) to JLabel and from mouseClicked to call JButton.doClick()
EDIT
#Mad,
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;
public class JButtonAndIcon {
private JLabel label = new JLabel();
private Random random = new Random();
private ImageIcon image1; // returns null don't worry about in Swing
private ImageIcon image2; // returns null don't worry about in Swing
private Timer backTtimer;
private int HEIGHT = 300, WEIGHT = 200;
public JButtonAndIcon() {
label.setPreferredSize(new Dimension(HEIGHT, WEIGHT));
final JButton button = new JButton("Push");
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setLayout(new BorderLayout());
button.add(label);
button.setMultiClickThreshhold(1000);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button.getIcon() == image1) {
label.setIcon(image2);
} else {
label.setIcon(image1);
if(backTtimer.isRunning()){
backTtimer.restart();
}
}
}
});
JFrame frame = new JFrame("Test");
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
startBackground();
frame.setVisible(true);
}
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JButtonAndIcon t = new JButtonAndIcon();
}
});
}
private void startBackground() {
backTtimer = new javax.swing.Timer(1500, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private Action updateBackground() {
return new AbstractAction("Background action") {
private final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
public BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
}

Related

Repaint Isn't doing anything

I am trying to make a rectangle change color with GUI sliders. I know this can be done by changing the background but I'm trying to use repaint.
I know that repaint holds the requests and executes at will almost. I'm trying to find a workaround because I'm stuck.
I've read up on repaint(); and repaintManager and tried manipulating my code but I'm still unable to get my desired output.
Any help would be appreciated.
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
*
*/
public class MyColorChooser2 extends JPanel {
private JFrame frame;
private JLabel redLabel, greenLabel, blueLabel;
private JSlider redSlider, greenSlider, blueSlider;
private JTextField redTextField, greenTextField, blueTextField;
private JPanel redPanel, greenPanel, bluePanel, colorPanel, paintPanel;
private int holdNbr1, holdNbr2, holdNbr3;
DrawPanel rect = new DrawPanel();
public MyColorChooser2() {
JFrame frame = new JFrame();
frame.setTitle("Color Chooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set up labels
redLabel = new JLabel("Red:");
greenLabel = new JLabel("Green:");
blueLabel = new JLabel("Blue:");
// set up sliders and register their event handler:
redSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 50);
redSlider.setMajorTickSpacing(10); // create tick every 10
redSlider.setPaintTicks(true); // paint ticks on slider
greenSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 100);
greenSlider.setMajorTickSpacing(10); // create tick every 10
greenSlider.setPaintTicks(true); // paint ticks on slider
blueSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 200);
blueSlider.setMajorTickSpacing(10); // create tick every 10
blueSlider.setPaintTicks(true); // paint ticks on slider
//slider event handling:
SliderHandler sliderHandler = new SliderHandler();
redSlider.addChangeListener(sliderHandler);
greenSlider.addChangeListener(sliderHandler);
blueSlider.addChangeListener(sliderHandler);
//set up textFields and register their event handler:
redTextField = new JTextField(3);
redTextField.setText("50"); //initialize
redTextField.setEditable(false);
redTextField.setText("" + redSlider.getValue());
greenTextField = new JTextField(3);
greenTextField.setText("100"); //initialize
greenTextField.setEditable(false);
greenTextField.setText("" + greenSlider.getValue());
blueTextField = new JTextField(3);
blueTextField.setText("200"); //initialize
blueTextField.setEditable(false);
blueTextField.setText("" + blueSlider.getValue());
// build colorPanel:
// build redPanel:
redPanel = new JPanel();
redPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
redPanel.add(redLabel);
redPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
redPanel.add(redSlider);
redPanel.add(redTextField);
// build greenPanel:
greenPanel = new JPanel();
greenPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
greenPanel.add(greenLabel);
greenPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
greenPanel.add(greenSlider);
greenPanel.add(greenTextField);
// build bluePanel:
bluePanel = new JPanel();
bluePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
bluePanel.add(blueLabel);
bluePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
bluePanel.add(blueSlider);
bluePanel.add(blueTextField);
colorPanel = new JPanel();
colorPanel.add(redPanel);
colorPanel.add(greenPanel);
colorPanel.add(bluePanel);
frame.setLayout(new BorderLayout());
frame.add(rect, BorderLayout.CENTER);
frame.add(colorPanel, BorderLayout.SOUTH);
frame.setPreferredSize(new Dimension(900, 300));
frame.setVisible(true);
frame.pack();
}
public class DrawPanel extends JPanel {
private Color color;
private int red = 50, blue = 100, green = 200;
private Graphics g;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
changeColor();
g.setColor(color);
g.fillRect(10, 10, 880, 200);
g.dispose();
}
public void DrawPanel(Color c) {
color = c;
red = color.getRed();
green = color.getGreen();
blue = color.getBlue();
}
void changeColor() {
color = new Color(red, green, blue);
this.color = color;
}
public void setRed(int r) {
red = r;
changeColor();
}
public void setBlue(int b) {
blue = b;
changeColor();
}
public void setGreen(int g) {
green = g;
changeColor();
}
}
private class SliderHandler implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
JSlider change = (JSlider) e.getSource();
DrawPanel draw = new DrawPanel();
int value;
if (change == redSlider) {
value = change.getValue();
redTextField.setText(String.valueOf(value));
draw.setRed(value);
} else if (change == greenSlider) {
value = change.getValue();
greenTextField.setText(String.valueOf(value));
draw.setGreen(value);
} else if (change == blueSlider) {
value = change.getValue();
blueTextField.setText(String.valueOf(value));
draw.setBlue(value);
}
draw.changeColor();
draw.repaint();
}
}
public static void main(String args[]) {
MyColorChooser2 color = new MyColorChooser2();
}
}
It's not that it isn't doing anything. The problem is that you're stuck, because every time you make a change you're trying to update a different component. You're recreating multiple panels in your state changed.
I've added comments about the changes I've done to make it work properly. If you need more help, just ask. Cheers!
Would you care trying this code:
public class MyColorChooser2 extends JPanel {
private JFrame frame;
private DrawPanel drawPanel;
private JLabel redLabel, greenLabel, blueLabel;
private JSlider redSlider, greenSlider, blueSlider;
private JTextField redTextField, greenTextField, blueTextField;
private JPanel redPanel, greenPanel, bluePanel, colorPanel, paintPanel;
private int holdNbr1, holdNbr2, holdNbr3;
private Color initialColor = Color.RED;
public MyColorChooser2() {
JFrame frame = new JFrame();
frame.setTitle("Color Chooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Let DrawPanel choose the initial color. I don't care.
drawPanel = new DrawPanel();
// This way I control what is the initial color
//drawPanel = new DrawPanel(initialColor);
// set up labels
redLabel = new JLabel("Red:");
greenLabel = new JLabel("Green:");
blueLabel = new JLabel("Blue:");
// set up sliders and register their event handler:
redSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, initialColor.getRed());
redSlider.setMajorTickSpacing(10); // create tick every 10
redSlider.setPaintTicks(true); // paint ticks on slider
greenSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, initialColor.getGreen());
greenSlider.setMajorTickSpacing(10); // create tick every 10
greenSlider.setPaintTicks(true); // paint ticks on slider
blueSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, initialColor.getBlue());
blueSlider.setMajorTickSpacing(10); // create tick every 10
blueSlider.setPaintTicks(true); // paint ticks on slider
// slider event handling:
SliderHandler sliderHandler = new SliderHandler();
redSlider.addChangeListener(sliderHandler);
greenSlider.addChangeListener(sliderHandler);
blueSlider.addChangeListener(sliderHandler);
// set up textFields and register their event handler:
redTextField = new JTextField(3);
redTextField.setText("50"); // initialize
redTextField.setEditable(false);
redTextField.setText("" + redSlider.getValue());
greenTextField = new JTextField(3);
greenTextField.setText("100"); // initialize
greenTextField.setEditable(false);
greenTextField.setText("" + greenSlider.getValue());
blueTextField = new JTextField(3);
blueTextField.setText("200"); // initialize
blueTextField.setEditable(false);
blueTextField.setText("" + blueSlider.getValue());
// build colorPanel:
// build redPanel:
redPanel = new JPanel();
redPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
redPanel.add(redLabel);
redPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
redPanel.add(redSlider);
redPanel.add(redTextField);
// build greenPanel:
greenPanel = new JPanel();
greenPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
greenPanel.add(greenLabel);
greenPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
greenPanel.add(greenSlider);
greenPanel.add(greenTextField);
// build bluePanel:
bluePanel = new JPanel();
bluePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
bluePanel.add(blueLabel);
bluePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
bluePanel.add(blueSlider);
bluePanel.add(blueTextField);
colorPanel = new JPanel();
colorPanel.add(redPanel);
colorPanel.add(greenPanel);
colorPanel.add(bluePanel);
frame.setLayout(new BorderLayout());
frame.add(drawPanel, BorderLayout.CENTER);
frame.add(colorPanel, BorderLayout.SOUTH);
frame.setPreferredSize(new Dimension(900, 300));
frame.setVisible(true);
frame.pack();
}
private class DrawPanel extends JPanel {
private Color color;
private int red = 255, blue = 0, green = 0;
#Override
protected void paintComponent(Graphics g) {
// I've removed the call to changeColor because it was creating
// an infinite loop of revalidates and repaints.
// Now, the paintComponent just finishes the job it was required to.
super.paintComponent(g);
g.setColor(color);
g.fillRect(10, 10, 880, 200);
}
public DrawPanel() {
this(Color.BLUE);
}
public DrawPanel(Color c) {
color = c;
red = color.getRed();
green = color.getGreen();
blue = color.getBlue();
// I'm calling this first repaint here just to make
// sure the panel is initiated the way we want with
// the given Color
repaint();
}
void changeColor() {
color = new Color(red, green, blue);
// We just need to change the color and call this repaint here
// so that the paintComponent can do its job
repaint();
}
public void setRed(int r) {
red = r;
changeColor();
}
public void setBlue(int b) {
blue = b;
changeColor();
}
public void setGreen(int g) {
green = g;
changeColor();
}
}
private class SliderHandler implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
JSlider change = (JSlider) e.getSource();
int value;
// I've removed this line of code because you were
// recreating the drawingPanel. That's not what you want.
// You want to reuse the same panel.
// DrawPanel draw = new DrawPanel();
if (change == redSlider) {
value = change.getValue();
redTextField.setText(String.valueOf(value));
drawPanel.setRed(value);
} else if (change == greenSlider) {
value = change.getValue();
greenTextField.setText(String.valueOf(value));
drawPanel.setGreen(value);
} else if (change == blueSlider) {
value = change.getValue();
blueTextField.setText(String.valueOf(value));
drawPanel.setBlue(value);
}
// You don't need to call those methods, because the
// changeColor will be called by the settings
// of Red, Green and Blue
// draw.changeColor();
// draw.repaint();
}
}
public static void main(String args[]) {
MyColorChooser2 color = new MyColorChooser2();
}
}

how to maintain transparency for JButtons (java)

i'm making a tank game. in my menu i want to use pictures as jbuttons, they are partly transparent and when they appear on screen the transparent parts become white.
i tried using .setOpaque but this doesn't work. i can't think of any other method to get rid of the white parts. i've been looking all over stack overflow but none of the methods seem to help. anyone who has an idea?
Thanks!
package menu;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class MenuPanel extends JPanel implements ActionListener
{
private Button playKnop, highScoreKnop, quitKnop, HTPKnop;
private JTextField naam;
private Image achtergrond;
private Tanks mainVenster;
public static String naam_input;
int x = 95, width = 200, height = 50;
public MenuPanel(Tanks mainVenster)
{
this.mainVenster = mainVenster;
this.setLayout(null);
playKnop = new Button("/buttons/PLAY.png", 350, this);
highScoreKnop = new Button("/buttons/HS.png", 460, this);
HTPKnop = new Button("/buttons/HTP.png", 515, this);
quitKnop = new Button("/buttons/QUIT.png", 570, this);
this.add(playKnop);
this.add(quitKnop);
this.add(HTPKnop);
this.add(highScoreKnop);
validate();
}
public class Button extends JButton
{
JButton button;
ImageIcon buttonImage;
String backgroundPath;
int y;
public Button(String backgroundPath, int y, MenuPanel menuPanel)
{
super();
this.backgroundPath = backgroundPath;
this.y = y;
buttonImage = new
ImageIcon(PlayPanel.class.getResource(backgroundPath));
this.setIcon(buttonImage);
this.setBounds(x, y, width, height);;
this.addActionListener(menuPanel);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(achtergrond, 0, 0, this.getWidth(), this.getHeight(),
this);
}
}
Remove some of the default rendering properties of the JButton including
contentAreaFilled
borderPainted
focusPainted
Which will reduce the button to, well, nothing. JButton already supports the painting of icons (and can do so for a verity of states), so there should be no need to override it's paintComponent method...
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
try {
BufferedImage img = ImageIO.read(getClass().getResource("/1xaN3.png"));
JButton btn = new JButton(new ImageIcon(img));
btn.setOpaque(false);
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
btn.setFocusPainted(false);
add(btn);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Personally, I prefer to load my images using ImageIO instead of ImageIcon (or other methods), mostly because it will throw an IOException if something goes wrong (rather the failing silently) and won't return until the image is loaded (and supports progress feedback if you do it right)
Have a look at Reading/Loading an Image for more details

Place image at random grid point on button click

I'm using Java with Window builder
I've created a 4x4 grid out of jlabels (each grid point is a different jlabel) on my jframe.
I also have a button called btnPlace.
What I want to do is have an image appear at a random grid point on button click. The image file is called red.png which is a red circle. The image can appear at any grid point except the grid point number 1.
Sort of like this: http://i.stack.imgur.com/bBn6D.png
Here's my code:
public class grid {
public static void main (String[] args)
{
JFrame grid =new JFrame();
grid.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
JPanel set = new JPanel();
set.setBounds(10, 11, 307, 287);
grid.getContentPane().add(set);
set.setLayout(new GridLayout(4, 4, 0, 0));
JLabel a = new JLabel("");
set.add(a);
JLabel b = new JLabel("");
set.add(b);
JLabel c = new JLabel("");
set.add(c);
^^ this repeats up to JLabel p. just to save time.
JButton btnPlace = new JButton("Place");
grid.getContentPane().add(btnPlace);
grid.setVisible(true);
} }
Here is fully working example:
On pressing button it'll draw Image on randomly selected JLabel
package stackoverflow;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DummyColor {
private JFrame frame;
private JLabel[] labels = new JLabel[4];
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DummyColor window = new DummyColor();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public DummyColor() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 657, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lbl1 = new JLabel("First BOX");
lbl1.setBounds(10, 11, 273, 194);
frame.getContentPane().add(lbl1);
JLabel label = new JLabel("Second BOX");
label.setBounds(336, 11, 273, 194);
frame.getContentPane().add(label);
JLabel label_1 = new JLabel("Third BOX");
label_1.setBounds(10, 251, 273, 194);
frame.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Fourth BOX");
label_2.setBounds(347, 251, 273, 194);
frame.getContentPane().add(label_2);
labels[0] = lbl1;
labels[1] = label;
labels[2] = label_1;
labels[3] = label_2;
JButton btnPick = new JButton("Place");
btnPick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon imageIcon = new ImageIcon(DummyColor.class.getResource("/red.jpg"));
int randInt = randInt(1, 4);
System.out.println(randInt);
for (int i = 0; i < labels.length; i++) {
JLabel jLabel = labels[i];
if (i == randInt - 1) {
jLabel.setIcon(imageIcon);
} else {
jLabel.setIcon(null);
}
}
}
});
btnPick.setBounds(10, 439, 57, 23);
frame.getContentPane().add(btnPick);
}
private static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
I would create a custom JPanel and add a MouseListener. Whenever the Panel is clicked, an image will be draw at that point clicked on the panel
public class grid{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.add(new MyPanel());
}
}
class MyPanel extends JPanel{
Point p;
BufferedImage img;
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
p = e.getLocationOnScreen();
repaint();
}
});
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
try{
img = ImageIO.read("someImage.png");
}catch(Exception e){e.printStackTrace();}
g.drawImage(img, p.getX(), p.getY(), width, height, this);
}
}

Layering a button over a painting

There is a window in which I want to place a button, and then paint the whole area beneath it. In other words, button should cover a piece of painting.
import java.awt.*;
import javax.swing.*;
class Window
{
private JFrame frame;
private JButton launchButton;
private JPanel pnllaunchButton;
private JPanel paintingPanel;
//width and height of client area
private Rectangle dim;
//w,h - width and height of the whole window
public Window(String title,int w,int h)
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(0,0);
frame.setMinimumSize( new Dimension(110,110));
frame.setSize(w, h);
frame.setVisible(true);
frame.setTitle(title);
frame.setResizable(false);
addLaunchButton();
}
private void addLaunchButton()
{
pnllaunchButton = new JPanel();
launchButton = new JButton("Plot!");
dim = new Rectangle();
frame.getContentPane().getBounds(dim);
pnllaunchButton.setBounds(dim.width-100,dim.height-25,100,25);
launchButton.setBounds(dim.width-100,dim.height-25,100,25);
pnllaunchButton.setLayout(null);
pnllaunchButton.add(launchButton);
frame.getContentPane().add(pnllaunchButton);
frame.getContentPane().setComponentZOrder(pnllaunchButton, new Integer(2));
}
public void drawCoordinateSystem()
{
paintingPanel = new JPanel();
paintingPanel.add(new CoordinateSystem());
frame.getContentPane().add(paintingPanel);
frame.getContentPane().setComponentZOrder(paintingPanel,new Integer(3));
}
}
class CoordinateSystem extends JPanel
{
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Dimension size = this.getSize();
g.setColor(Color.BLACK);
g.drawLine(0,size.height/2,size.width, size.height/2);
g.drawLine(size.width/2, 0, size.width/2, size.height);
}
}
public class GC {
public static void main(String[] args)
{
Window h = new Window("GC",800,600);
h.drawCoordinateSystem();
}
}
This code doesn't fulfill the specification. Program creates an empty window and outputs:
run:
Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
at java.awt.Container.checkAdding(Container.java:504)
at java.awt.Container.setComponentZOrder(Container.java:759)
at Window.addLaunchButton(Window.java:46)
at Window.<init>(Window.java:26)
at GC.main(GC.java:10)
Could you point out my mistake? setComponentZOrder() method doesn't seem to be described precisely in javadoc.
Rename your class. The Window class is already part of the standard core Java libraries, and your class name could cause present or future problems.
Don't us null layouts and setBounds(...). This is bad, bad, bad, and will make it very difficult to maintain or upgrade your application. Instead, learn about and use the layout managers.
Consider making a JLabel the contentPane, make it opaque, give it a layout and an ImageIcon and add your components to it.
The ImageIcon can hold a BufferedImage with a grid.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class MyWindow {
private static final int PREF_W = 800;
private static final int PREF_H = 600;
private static final Color COLOR0 = Color.red;
private static final Color COLOR1 = Color.blue;
private static final float COLOR_REPEAT_DIST = 30f;
private JLabel backGroundLabel = new JLabel();
public MyWindow() {
backGroundLabel.setOpaque(true);
backGroundLabel.setLayout(new BorderLayout());
int eb = 15;
BufferedImage bkgrndImg = createBkgrndImage();
ImageIcon icon = new ImageIcon(bkgrndImg);
backGroundLabel.setIcon(icon);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(SwingConstants.RIGHT, eb, eb));
bottomPanel.setOpaque(false);
bottomPanel.add(new JButton("Plot"));
backGroundLabel.add(bottomPanel, BorderLayout.PAGE_END);
}
private BufferedImage createBkgrndImage() {
BufferedImage img = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setPaint(new GradientPaint(0f, 0f, COLOR0, COLOR_REPEAT_DIST, COLOR_REPEAT_DIST, COLOR1, true));
g2.fillRect(0, 0, PREF_W, PREF_H);
g2.dispose();
return img;
}
public JComponent getMainPane() {
return backGroundLabel;
}
private static void createAndShowGui() {
MyWindow mainPanel = new MyWindow();
JFrame frame = new JFrame("MyWindow");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel.getMainPane());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which looks like so:
Pass an int instead of an Integer to the setComponentZOrder method.
private void addLaunchButton()
{
pnllaunchButton = new JPanel();
launchButton = new JButton("Plot!");
dim = new Rectangle();
frame.getContentPane().getBounds(dim);
pnllaunchButton.setBounds(dim.width-100,dim.height-25,100,25);
launchButton.setBounds(dim.width-100,dim.height-25,100,25);
pnllaunchButton.setLayout(null);
pnllaunchButton.add(launchButton);
frame.getContentPane().add(pnllaunchButton);
frame.getContentPane().setComponentZOrder(pnllaunchButton, 2);
}

how can i put a JButton on an image?

I am trying to fix a JFrame where there will be a background image and on the image JButtons which will do some commands. I try to do it without layout because i want to put small buttons in some specific locations on the JFrame but every time i do it, the background image comes to the front or the JFrame has size equal to the JFrame size. With the following code, the JButton has the same size to JFrame. I have tried to change the size and location of the JButton but nothing. Can you help me please?
here is the code
public final class Test extends JComponent
{
private Image background;
private JFrame frame;
private Dimension dimension;
public Test()
{
dimension = new Dimension(15, 15);
frame = new JFrame("Iphone");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(this);
frame.setBounds(641, 0, 344, 655);
frame.setVisible(true);
test = displayButton("tigka");
frame.getContentPane().add(test);
}
public void update(Graphics g)
{
paint(g);
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(background, 0, 25, null); // draw background
// label();
test = displayButton("test");
}
public JButton displayButton(String name)
{
JButton button = new JButton(name);
button.setSize(100, 100);
button.setPreferredSize(dimension);
return button;
}
You need to change the content pane to get a background for your Frame.
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Test");
frame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 300, 300, this);
}
});
frame.add(new JButton("Test Button"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
Output:
Have you tried using a JLabel with HTML in the label? Something like this:
import javax.swing.*;
public class SwingImage1
{
public static void main( String args[] )
{
JFrame frm = new JFrame( "Swing Image 1" );
JLabel lbl = new JLabel( "<html><body><img src=\"http://liv.liviutudor.com/images/liv.gif\"></body></html>" );
frm.getContentPane().add( lbl );
frm.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frm.pack();
frm.setVisible( true );
}
}
then on top of your label you can add your button?
You should swap those two lines:
super.paintComponents(g); //paints the children, like the button
g.drawImage(background, 0, 25, null); // draw background later possibly overwriting the button
Thus it should be this order:
g.drawImage(background, 0, 25, null);
super.paintComponents(g);
Additionally, note that the content pane's default layout is BorderLayout. Thus you'd set the layout of your content pane to null explicitly.
/*it is simple to put button on image first set image by making object then make button object & add the button object direct to image object rather then add to frame.*/
package frame;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class frame
{
public frame()
{
JFrame obj = new JFrame("Banking Software");
JButton b1 = new JButton("Opening Account");
JLabel image = new JLabel(new ImageIcon("money.jpg"));
image.setBounds(0,0, 1600, 1400);
obj.setExtendedState(JFrame.MAXIMIZED_BOTH);
obj.add(image);
b1.setBounds(500,400, 100, 40);
image.add(b1);
obj.setVisible(true);
}
public static void main(String args[])
{
new frame();
}
}

Categories

Resources