I am trying to create a JTextField with an image and a hint. The function of the textfield is a search field to search some books. Now, I like to go a little bit further. I would like to give the image a function. For example, if I click on the image the text in the textfield should be cleared.
To achieve this implementation I created a new class and extended it with JTextField.
This is the code:
public class JSearchTextField extends JTextField implements FocusListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private String textWhenNotFocused;
private Icon icon;
private Insets dummyInsets;
private JTextField dummy;
public JSearchTextField() {
super();
Border border = UIManager.getBorder("TextField.border");
dummy = new JTextField("Suchen...");
this.dummyInsets = border.getBorderInsets(dummy);
icon = new ImageIcon(JSearchTextField.class.getResource("/images/clearsearch.png"));
this.addFocusListener(this);
}
public JSearchTextField(String textWhenNotFocused) {
this();
this.textWhenNotFocused = textWhenNotFocused;
}
public void setIcon(ImageIcon newIcon){
this.icon = newIcon;
}
public String getTextWhenNotFocused() {
return this.textWhenNotFocused;
}
public void setTextWhenNotFocused(String newText) {
this.textWhenNotFocused = newText;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int textX = 2;
if(!this.hasFocus() && this.getText().equals("")) {
int height = this.getHeight();
Font prev = this.getFont();
Font italic = prev.deriveFont(Font.ITALIC);
Color prevColor = g.getColor();
g.setFont(italic);
g.setColor(UIManager.getColor("textInactiveText"));
int h = g.getFontMetrics().getHeight();
int textBottom = (height - h) / 2 + h - 4;
int x = this.getInsets().left;
Graphics2D g2d = (Graphics2D) g;
RenderingHints hints = g2d.getRenderingHints();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.drawString(textWhenNotFocused, x, textBottom);
g2d.setRenderingHints(hints);
g.setFont(prev);
g.setColor(prevColor);
} else {
int iconWidth = icon.getIconWidth();
int iconHeight = icon.getIconHeight();
int x = dummy.getWidth() + dummyInsets.right;
textX = x - 420;
int y = (this.getHeight() - iconHeight)/2;
icon.paintIcon(this, g, x, y);
}
setMargin(new Insets(2, textX, 2, 2));
}
#Override
public void focusGained(FocusEvent arg0) {
this.repaint();
}
#Override
public void focusLost(FocusEvent arg0) {
this.repaint();
}
}
And this is where I create the fields;
txtSearchBooks = new JSearchTextField("Buch suchen...");
Now back to my question. Do you have any idea how I can give the image a function where the text will be automatically cleared? I tried to implement a MouseListener and set the text of "txtSearchBooks" to null but it hasn't worked.
I hope I didn't go off in the wrong direction.
Sorry for the long post but I would really appreciate to get some advice.
A JTextField is a JComponent, meaning it is also a container for other components. You can use the add(Component c) method to add other components to it. BUT A JTextField won't show its added components unless you provide a LayoutManager to it. Then it behaves just like a normal JPanel.
I made a small example how you can manage what you need. The label is showed to the right, and clicking it will clear the field. You can use a button as well, instead of label.
Please note you don't need to create the Image object from scratch as I do, you can load it from a file. I create it this way so that the example doesn't rely on other files.
public class TextFieldWithLabel {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textField = new JTextField("Search...");
textField.setLayout(new BorderLayout());
//creating dummy image...
Image image = new BufferedImage(25, 25, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, 25, 25);
graphics.setColor(Color.RED);
graphics.fillRect(2, 11, 21, 3);
graphics.fillRect(11, 2, 3, 21);
JLabel label = new JLabel(new ImageIcon(image));
textField.add(label, BorderLayout.EAST);
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField.setText("");
}
});
frame.add(textField);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Related
Huy guys, I have a weird problem.
I'm kinda new to swing and java applications.
I'm trying to make a custom UI jslider that changes a jlabel text when you move the thumb.
My problem is: when I use the addChangeListener(), it creates a weird glitch when moving the thumb.
If I don't use it, it works perfectly fine.
How can I update the JLabel without using the change listener or how can I fix this graphic bug?
Most of this code comes from stackoverflow since I don't know much about painting components.
See pictures at the button to better understand the problem
Thanks!
The code in my jpanel
JSlider slider = new JSlider(SwingConstants.HORIZONTAL, 1, 10, 1) {
#Override
public void updateUI() {
setUI(new CustomSliderUI(this));
}
};
// If I comment this line the visual glitch is gone when moving the thumb, but the value doesnt update
slider.addChangeListener((event) -> RAM_LABEL.setText(slider.getValue() + " Gb"));
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(10);
slider.setSnapToTicks(true);
slider.setBounds(96, 317, 300, 35);
slider.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
slider.setOpaque(false);
this.add(slider);
The custom slider ui class
private static class CustomSliderUI extends BasicSliderUI
{
private static final int TRACK_HEIGHT = 8;
private static final int TRACK_ARC = 5;
private static final Dimension THUMB_SIZE = new Dimension(22, 20);
private final RoundRectangle2D.Float trackShape = new RoundRectangle2D.Float();
private final Image knob;
public CustomSliderUI(final JSlider b)
{
super(b);
knob = Swinger.getResource("knob.png");
}
#Override
protected void calculateTrackRect() {
super.calculateTrackRect();
trackRect.y = trackRect.y + (trackRect.height - TRACK_HEIGHT) / 2;
trackRect.height = TRACK_HEIGHT;
trackShape.setRoundRect(trackRect.x, trackRect.y, trackRect.width, trackRect.height, TRACK_ARC, TRACK_ARC);
}
#Override
protected void calculateThumbLocation() {
super.calculateThumbLocation();
thumbRect.y = trackRect.y + (trackRect.height - thumbRect.height) / 2;
}
#Override
protected Dimension getThumbSize() {
return THUMB_SIZE;
}
#Override
public void paint(final Graphics g, final JComponent c) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paint(g, c);
}
#Override
public void paintTrack(final Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Shape clip = g2.getClip();
boolean inverted = slider.getInverted();
// Paint shadow.
g2.setColor(new Color(170, 170 ,170));
g2.fill(trackShape);
// Paint track background.
g2.setColor(new Color(200, 200 ,200));
g2.setClip(trackShape);
trackShape.y += 1;
g2.fill(trackShape);
trackShape.y = trackRect.y;
g2.setClip(clip);
// Paint selected track.
boolean ltr = slider.getComponentOrientation().isLeftToRight();
if (ltr) inverted = !inverted;
int thumbPos = thumbRect.x + thumbRect.width / 2;
if (inverted) {
g2.clipRect(0, 0, thumbPos, slider.getHeight());
} else {
g2.clipRect(thumbPos, 0, slider.getWidth() - thumbPos, slider.getHeight());
}
g2.setColor(Swinger.getTransparentWhite(0));
g2.fill(trackShape);
g2.setClip(clip);
}
#Override
public void paintThumb(final Graphics g)
{
g.drawImage(knob, thumbRect.x, thumbRect.y, null);
}
#Override
public void paintFocus(final Graphics g) {}
}
Visual glitch when you are moving the cursor, as soon as you stop pressing the mouse it goes back to normal
Regular cursor / when I move it without the change listener
Solved. I went with drawing my own background it was simplier.
private static class CustomSliderUI extends BasicSliderUI
{
private static final Dimension THUMB_SIZE = new Dimension(22, 20);
private final Image thumb, background;
private final JSlider slider;
public CustomSliderUI(final JSlider b)
{
super(b);
slider = b;
thumb = Swinger.getResource("thumb.png");
background = Swinger.getResource("slider.png");
}
#Override
protected Dimension getThumbSize() {
return THUMB_SIZE;
}
#Override
public void paintTrack(final Graphics g) {
g.drawImage(background, 10, 11, 280, 10, null);
}
#Override
public void paintThumb(final Graphics g)
{
g.drawImage(thumb, thumbRect.x, thumbRect.y, null);
slider.repaint();
}
#Override
public void paintFocus(final Graphics g) {}
}
JSlider slider = new JSlider(SwingConstants.HORIZONTAL, 1, 10, 1) {
#Override
public void updateUI() {
setUI(new CustomSliderUI(this));
}
};
slider.addChangeListener((event) -> RAM_LABEL.setText(slider.getValue() + " Gb"));
slider.setBounds(96, 317, 300, 35);
slider.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
slider.setOpaque(false);
this.add(slider);
I have a simple game of pong where when the user clicks a JButton which is displayed on the JPanel it should reset the game. How can I do this? I was thinking just remove the JPanel and add a new one (the JPanel contains all of the necessary code/class references for the game) I tried writing this however, and it didn't work, nothing happens. Here is my code:
JFrame Class:
public class Window extends JFrame implements ActionListener {
static int length = 1000;
static int height = 1000;
Display display = new Display();
Window() {
setTitle("Program Display");
setSize(length + 22, height + 40);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton restart = new JButton("Start New Game");
add(display);
display.add(restart);
restart.addActionListener(this);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
remove(display);
Display display2 = new Display();
JButton restart = new JButton("Start New Game");
add(display2);
display2.add(restart);
restart.addActionListener(this);
revalidate();
repaint();
}
}
JPanel Class:
public class Display extends JPanel implements ActionListener {
int up = 0;
int down = 500;
double ballx = 500;
double bally = 500;
char ballDirection;
Rectangle border;
static Rectangle borderEast;
static Rectangle borderNorth;
static Rectangle borderSouth;
static Rectangle borderWest;
static boolean gameOver;
Timer timer;
Paddle p;
Ball b;
Display() {
p = new Paddle();
b = new Ball();
up = p.up;
down = p.down;
ballx = b.ballx;
bally = b.bally;
ballDirection = b.ballDirection;
initTimer();
b.startBall();
addKeyListener(p);
setFocusable(true);
}
public void initTimer() {
timer = new Timer(10, this);
timer.start();
}
public void setUpBorders(Graphics2D g2d) {
border = new Rectangle(0, 0, Window.length, Window.height);
borderEast = new Rectangle(Window.length, 0, 2, Window.height);
borderWest = new Rectangle(0, 0, 2, Window.height);
borderSouth = new Rectangle(0, Window.height, Window.length, 2);
borderNorth = new Rectangle(0, 0, Window.length, 2);
g2d.setColor(Color.RED);
g2d.draw(border);
}
public void paintPaddle(Graphics2D g2d) {
g2d.setColor(new Color(0, 130, 130));
g2d.fill(p.paddle);
}
public void paintBall(Graphics2D g2d) {
g2d.setColor(new Color(0, 130, 130));
g2d.fillOval((int) ballx, (int) bally, 20, 20);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.BLACK);
Graphics2D g2d = (Graphics2D) g;
setUpBorders(g2d);
paintPaddle(g2d);
paintBall(g2d);
if(gameOver == true) {
Font custom = new Font("Dialog", Font.BOLD, 60);
g2d.setColor(Color.RED);
g2d.setFont(custom);
g2d.drawString("Game Over. Your score was: " + Ball.score + "!", 50, 500);
}
}
public void checkBorderHit() {
b.checkBorderHit();
p.checkBorderHit();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
up = p.up;
down = p.down;
ballx = b.ballx;
bally = b.bally;
ballDirection = b.ballDirection;
b.moveBall();
checkBorderHit();
repaint();
}
}
You didn't say what exactly doesn't work, but you forgot to call revalidate() and repaint() after adding display2. If your problem was that after pressing the button nothing happens, this will probably solve it.
Edit:
We still can't run you code, because the Ball and Paddle class are missing (my mistake for not mentioning that), but try to set important variables like gameOver false when first "mentioning them" (I don't know the proper term, just do static boolean gameOver = false; instead of static boolean gameOver;). Do this in all other classes also. Sorry for not saying which variables you exactly must change, but I'm not saying anything I'm not 100% sure about without being able to test it :P (maybe a more experienced person can help you more)
I have to programm a Shikaku-Game and I have no the problem that I can not use one of the setLine-Methods from the ViewIcon-Class in the mouseReleased-Method of the class MyMouseAdapter.
Do you know a way how to use one of the methods?
Thanks and Cheers,
Me
Class MouseMain and Class MyMouseAdapter:
class MouseMain extends JFrame{
Container cont;
public MouseMain () {
super("Test");
cont = getContentPane();
p1 = new defaultPaterns(2);
p1.setLayout(new GridLayout(2, 2, 1, 1));
for (int i = 0; i < gameSize; i++) {
for (int j = 0; j < gameSize; j++) {
JLabel label = new JLabel(new ViewIcon());
label.setName (j + ";" + i);
label.addMouseListener(new MyMouseAdapter());
p1.add(label);
myLabels[j][i] = label;
}
}
cont.add(p1, BorderLayout.CENTER );
JPanel p2 = new JPanel();
cont.add(p2, BorderLayout.SOUTH);
setVisible(true);
}
public class MyMouseAdapter extends MouseAdapter {
public void mouseEntered(MouseEvent e) {
lastEntered = e.getComponent();
}
public void mousePressed(MouseEvent e) {
mousePressed = e.getComponent();
coordPressed = new Coordinate(mousePressed.getName());
System.out.println("mousePressed " + mousePressed.getName());
}
public void mouseReleased(MouseEvent e) {
mouseReleased = lastEntered;
coordReleased = new Coordinate(mouseReleased.getName());
System.out.println("mouseReleased " + mouseReleased.getName());
if (mouseReleased.getName().equals("0;0")) {
mouseReleased.setForeground(Color.RED);
mouseReleased.repaint();
}
}
}
Class ViewIcon:
class ViewIcon extends JLabel implements Icon {
Graphics2D g2;
int width;
int height;
public void paintIcon(Component c, Graphics g, int x, int y) {
g2 = (Graphics2D) g;
width = c.getWidth();
height = c.getHeight();
g2.setColor(Color.LIGHT_GRAY);
g2.fillRect(0, 0, width, height);
}
public void setLeftLine() {
g2.setStroke (new BasicStroke (10));
g2.setColor(Color.RED);
g2.drawLine(0, 0, 0, height);
}
}
class ViewIcon extends JLabel implements Icon {
Don't extend JLabel. All your code is doing is implementing the Icon interface.
I can not use one of the setLine-Methods from the ViewIcon-Class
Custom painting should only be done in the paintIcon(...) method. You should NEVER invoke a painting method directly.
If you want to change the appearance of your painting then you need to set properties of the Icon. For example to paint the top line you rename and change your setTopLine(...) method to look something like:
public void setTopLinePainted(boolean topLinePainted)
{
this.topLinePainted = topLinePainted;
}
Then in the paintIcon(...) method you have code like:
g2.fillRect(0, 0, width, height);
if (topLinePainted)
{
g2.setStroke (new BasicStroke (10));
g2.setColor(Color.RED);
g2.drawLine(0, 0, width, 0);
}
Then in your mouseReleased(...) code you do something like:
JLabel label = (JLabel)lastEntered;
ViewIcon icon = (ViewIcon)label.getIcon();
icon.setTopLinePainted( true );
label.repaint();
In my code after i added code to paintComponent() when i run it, all the JLabel, textfields, and buttons disappear the textfields and buttons reappear when i click on them while the program is running but i still can't see any of the JLabels.
I hope it is something silly i have commented out the code in the paintComponent() method that seems to cause this error.
public class snowBoarding extends JFrame {
private JButton getReset() {
if (Reset == null) {
Reset = new JButton();
Reset.setBounds(new Rectangle(162, 411, 131, 39));
Reset.setFont(new Font("Dialog", Font.BOLD, 18));
Reset.setText("Reset");
Reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e){
textField_1.setText("0");
textField_2.setText("0");
textField_3.setText("0");
textField_4.setText("0");
textField_5.setText("0");
textField_6.setText("0");
textField_7.setText("0");
textField_8.setText("0");
textField_9.setText("0");
textField_10.setText("0");
textField_11.setText("0");
textField.setText("0");
total_1.setText("0");
total_2.setText("0");
Overall.setText("0");
DrawPanel.clear(DrawPanel.getGraphics());
DrawPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
}
});
}
return Reset;
}
public JButton getButton_calc_draw() {
if (Button_calc_draw == null) {
Button_calc_draw = new JButton();
Button_calc_draw.setBounds(303, 411, 131, 39);
Button_calc_draw.setFont(new Font ("Dialog", Font.BOLD, 18));
Button_calc_draw.setText("Draw");
Button_calc_draw.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
// Get values from the text fields
run_1[0] = Integer.parseInt(textField.getText());
run_1[1] = Integer.parseInt(textField_1.getText());
run_1[2] = Integer.parseInt(textField_2.getText());
run_1[3] = Integer.parseInt(textField_3.getText());
run_1[4] = Integer.parseInt(textField_4.getText());
run_1[5] = Integer.parseInt(textField_5.getText());
for (int i = 0; i < run_1.length; i++) {
temp[i] = run_1[i];
}
Arrays.sort(temp);
for (int i = 1; i < (temp.length -1) ; i++){
avg1+=temp[i];
}
avg1 = avg1/4;
run_2[0] = Integer.parseInt(textField_6.getText());
run_2[1] = Integer.parseInt(textField_7.getText());
run_2[2] = Integer.parseInt(textField_8.getText());
run_2[3] = Integer.parseInt(textField_9.getText());
run_2[4] = Integer.parseInt(textField_10.getText());
run_2[5] = Integer.parseInt(textField_11.getText());
for (int i = 0; i < run_2.length; i++) {
temp[i] = run_2[i];
}
Arrays.sort(temp);
for (int i = 1; i < (temp.length -1) ; i++){
avg2+=temp[i];
}
avg2 = avg2/4;
if (avg1 > avg2){
OverallScore = avg1;
}
else {
OverallScore = avg2;
}
total_1.setText(Integer.toString(avg1));
total_2.setText(Integer.toString(avg2));
Overall.setText(Integer.toString(OverallScore));
DrawPanel.repaint();
}
// Transfer the image from the BufferedImage to the JPanel to make it visible.
;
});
}
return Button_calc_draw;
}
}
});
}
return Reset;
}
private myJPanel getDrawPanel() {
if (DrawPanel == null) {
DrawPanel = new myJPanel();
DrawPanel.setLayout(new GridBagLayout());
DrawPanel.setBounds(new Rectangle(258, 39, 326, 361));
DrawPanel.setBackground(Color.white);
DrawPanel.setEnabled(true);
DrawPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
//Instantiate the BufferedImage object and give it the same width
// and height as that of the drawing area JPanel
img = new BufferedImage(DrawPanel.getWidth(),
DrawPanel.getHeight(),
BufferedImage.TYPE_INT_RGB);
//Get its graphics context. A graphics context of a particular object allows us to draw on it.
g2dImg = (Graphics2D)img.getGraphics();
//Draw a filled white coloured rectangle on the entire area to clear it.
g2dImg.setPaint(Color.WHITE);
g2dImg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
}
return DrawPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
snowBoarding thisClass = new snowBoarding();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}
public snowBoarding() {
super();
setResizable(false);
getContentPane().setLayout(null);
initialize();
}
private void initialize() {
this.setSize(600, 500);
this.setContentPane(getJContentPane());
this.setTitle("Snowboarding Score Calculator");
this.setResizable(false);
this.setVisible(true);
}
}
class myJPanel extends JPanel {
BufferedImage img;
Graphics2D g2dImg;
private static final long serialVersionUID = 1L;
private Rectangle2D.Double rectangle;
public void paintComponent(Graphics g) {
//Must be called to draw the JPanel control.
// As a side effect, it also clears it.
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
rectangle = new Rectangle2D.Double(0, 260-score[0] * 2, 25, score[0] * 2);
g2D.setPaint(Color.blue);
g2D.fill(rectangle);
g2D.draw(rectangle);
}
protected void clear(Graphics g) {
super.paintComponent(g);
// Also clear the BufferedImage object by drawing a white coloured filled rectangle all over.
g2dImg.setPaint(Color.WHITE);
g2dImg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
}
}
edit: removing unnecessary code
i need the repaint to draw rectangles using the run_1 and the run_2 array as the x or y values after i click draw and the reset to return the painted image back to a white slate.
draw button --> draws the graph
reset button --> removes the graph so that a new graph can be created.
You shall not use g2dImg in paintComponent(), but g instead (the parameter received by method paintComponent()). More precisely, ((Grpahics2D)g) instead of g2dImg.
g2dImg doesn't seem to be initialized in your code posted here, maybe you have done it somewhere...
More generally, you shall always use the Graphics instance you received in paint methods (casting it to Graphics2D if needed). You shall not try to reuse/share/store instances of Graphics.
The same applies for the clear() method.
Here is an example of how to rewrite this paintComponent() method:
private boolean shallPaint = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (shallPaint) {
Graphics2D g2D = (Graphics2D) g;
rectangle = new Rectangle2D.Double(0, 260-score1 * 2, 25, score1 * 2);
g2D.setPaint(Color.blue);
g2D.fill(rectangle);
g2D.draw(rectangle);
}
}
public void setShallPaint(boolean pShallPaint) {
shallPaint = pShallPaint;
}
Then simply call myJPanel.repaint() to repaint it.
You shall replace, in your reset button:
DrawPanel.clear(DrawPanel.getGraphics());
with:
DrawPanel.setShallPaint(false);
DrawPanel.repaint();
And in Button_calc_draw:
DrawPanel.setShallPaint(true);
DrawPanel.repaint();
Currently i m making a java program using netbeans based on changing image in a button....
Actually my requirement is to change the Image icon of a button as i click another button (Say A).....
i came out with the following program........
// Following function is included inside the button's (Here A) ActionListener........
public void change_image()
{
if(sex==0)
{
ic=new ImageIcon("E:\\java_images\\female_profile.jpg");
sex=1;
}
else if(sex==1)
{
ic = new ImageIcon("E:\\java_images\\male_profile.png");
sex=0;
}
// To resize the image into the size of the button...
labelicon.setImage(ic.getImage().getScaledInstance(image_btn.getWidth(),image_btn.getHeight(), Image.SCALE_DEFAULT));
img_btn.setIcon(labelicon);
}
The Variables i've included are
private int sex; // 0 - female, 1 - male
private ImageIcon ic,labelicon; // variables meant for storing ImageIcons.....
private JButton img_btn; // the button at which the image is to be displayed....
Now the Weird Behaviour i observed is.......
The image gets displayed on the button click, only when i click the minimize button.
i.e when the i click the button A, the code specified in the ActionListener is getting executed. But the effect of the image change appears only when i minimize the window and again make it appear on the screen.... Can anyone tell why this is occuring and how can i remove the problem ??
All i want is to change the image the moment i click the A Button.....
Well..i haven't included for the code for creating button since they are easily done by netbeans swing GUI builder......
load Icon / ImageIcon as local variable once time, there no reason to re_loading image from ActionListener
in the API is description that Image#ScaledInstance is pretty asynchronous
otherwise you have to call
.
labelicon.getImage().flush();
img_btn.setIcon(labelicon);
EDIT
#akp wrote but..how would you resize the icon image..??
there are two or three another ways how to put Icon /ImageIcon and will be resiziable with its parent, JLabelcould be easiest of ways
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 static JLabel label = new JLabel();
private static Random random = new Random();
private static ImageIcon image1; // returns null don't worry about
private static ImageIcon image2; // returns null don't worry about
private static Timer backTtimer;
private static int HEIGHT = 300, WEIGHT = 200;
public static void main(String[] args) throws IOException {
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.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button.getIcon() == image1) {
label.setIcon(image2);
} else {
label.setIcon(image1);
}
}
});
JFrame frame = new JFrame("Test");
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
startBackground();
frame.setVisible(true);
}
private static void startBackground() {
backTtimer = new javax.swing.Timer(750, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private static Action updateBackground() {
return new AbstractAction("Background action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
public static 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;
}
}
The problem here is that you are updating the internals of an Icon. The setIcon method will think that it's the same icon that the button already has. I would recommend you to do two different Icon objects that to use to update the icon with. That will fix the problems.
Example (with two different icons):
public static void main(String[] args) throws IOException {
final ImageIcon redIcon = createImageIcon(10, 10, Color.RED);
final ImageIcon blueIcon = createImageIcon(10, 10, Color.BLUE);
final JButton button = new JButton("Push", blueIcon);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button.getIcon() == redIcon)
button.setIcon(blueIcon);
else
button.setIcon(redIcon);
}
});
JFrame frame = new JFrame("Test");
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private static ImageIcon createImageIcon(int w, int h, Color color) {
Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(color);
g.fillRect(0, 0, w, h);
g.dispose();
return new ImageIcon(image);
}
Background:
Looking at the source of AbstractButton.setIcon, you can see that it won't know about the update if the reference "isn't updated":
.....
if (defaultIcon != oldValue) {
if (defaultIcon == null || oldValue == null ||
defaultIcon.getIconWidth() != oldValue.getIconWidth() ||
defaultIcon.getIconHeight() != oldValue.getIconHeight()) {
revalidate();
}
repaint();
}
Note to #HarryJoy, you actually had a point even though you didn't know why... :) Sorry! +1 again!
//Call img_btn.revalidate() and img_btn.repaint()
Correction, setIcon should already do this. I use the hacky way of img_btn.setText("<HTML><BODY><IMG SRC=\"/path/to/img.jpg\"/></BODY</HTML>"); personally.