My text field is local to main so I cannot access it from actionPerformed, I believe I need to make it a instance variable but I'm not sure how to because my frame is also in main so I'm not sure how I would then add it to the frame.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.sql.*;
import java.lang.Object;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
* This class demonstrates how to load an Image from an external file
*/
public class Test extends JPanel {
int x=77, y=441, w=23, h=10;
BufferedImage img =
new BufferedImage(100, 50,
BufferedImage.TYPE_INT_ARGB);
// BufferedImage img;
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
// g.fillRect(10,10,10,10);
}
public Test() {
try {
img = ImageIO.read(new File("sales-goal.png"));
} catch (IOException e) {}
Graphics2D g = img.createGraphics();
Color myColor = Color.decode("#32004b");
g.setColor(myColor);
g.fillRect(x,y,w,h);
//77,441,23,10
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
//return new Dimension(img.getWidth(null), img.getHeight(null));
return new Dimension(300,600);
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
JTextField textField=new JTextField();
f.add(textField);
textField.setBounds(10,10,40,30);
textField.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new Test());
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//if (e.getSource() == textField) {}
}
}
I think that you should not set up your swing application this way. Instead of creating everything in the main method you should create a subclass of JFrame and do the initialization in its constructor (or something like that). This class can then hold references to the components it contains. Example:
public class TestFrame extends JFrame {
private JTextField textField;
public TestFrame() {
super("Load Image Sample");
textField = new JTextField();
this.add(textField);
textField.setBounds(10,10,40,30);
textField.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.add(new Test());
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == textField) {
// ...
}
}
}
create your frame and initialize it inside constructor.
public static void main(String[] args) {
new Test();
}
The event handling method actionPerformed must be registered by an ActionListener interface. As both textField and Test are components of the JFrame a logical place would be the JFrame, or a separate controller class that wires everything together.
I have rewritten your code with a more conventional approach on some details. For that I introduced a new class MyFrame.
public class MyFrame extends JFrame implements ActionListener {
JTextField textField = new JTextField();
public MyFrame(String title) {
super(title); // Or constructor without parameters and:
setTitle("Load Image Sample");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(...); for instance with null for absolute positioning
add(textField);
textField.setBounds(10, 10, 40, 30);
textField.setVisible(true);
Test panel = new Test();
add(panel);
pack();
}
public static void main(String[] args) {
JFrame f = new MyFrame("Load Image Sample");
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Text: " + textField.getText());
}
}
And then your JPanel
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
/**
* This class demonstrates how to load an Image from an external file
*/
class Test extends JPanel {
int x = 77, y = 441, w = 23, h = 10;
BufferedImage img;
Color myColor = Color.decode("#32004b");
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(myColor);
g.fillRect(x, y, w, h);
g.drawImage(img, 0, 0, null);
// g.fillRect(10,10,10,10);
}
public Test() {
setBackground(Color.red);
try {
img = ImageIO.read(new File("sales-goal.png"));
} catch (IOException e) {
img = new BufferedImage(100, 50, BufferedImage.TYPE_INT_ARGB);
}
setPreferredSize(new Dimension(300, 600));
}
}
Related
It looks like :
As seen in the image there are white spots with the text.
My code is :
import javax.swing.*;
import java.awt.*;
public class SubsFrame extends JFrame {
private String text;
private JLabel label;
private byte mode;
private static SubsFrame instance;
public static void build(long mode) throws Exception{
if(instance == null) {
instance = new SubsFrame(mode);
}else{
throw new Exception("Another instance already exists!");
}
}
public static void buildSilent(long mode) throws Exception{
if(instance == null)
instance = new SubsFrame(mode);
}
public static void showFrame(){
instance.setVisible(true);
}
public static void hideFrame(){
instance.setVisible(false);
}
public static void destroy() {
instance.dispose();
instance = null;
}
public static void setOpacity(double opacity){
instance.setBackground(new Color(1.0f,1.0f,1.0f,(float)opacity));
}
private SubsFrame(long mode) throws Exception{
if(JSubsConstants.isValidMode(mode))
this.mode = (byte)mode;
else
throw new Exception("Invalid Mode Selected!");
if(!this.isAlwaysOnTopSupported()){
throw new Exception("Always on top is not supported!");
}
label = new JLabel("Hello World! Welcome to this app!");
label.setFont(new Font("Consolas", Font.PLAIN, 25));
this.setLayout(new FlowLayout());
this.add(label);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
this.setAlwaysOnTop(true);
this.setUndecorated(true);
if(this.mode == JSubsConstants.AUTO_SIZED_FRAME_AUTO_POSITIONED){
handleFrameSize();
handleFrameLocation();
}
else if(this.mode == JSubsConstants.AUTO_SIZED_FRAME_MANUAL_POSITIONED){
handleFrameSize();
}
}
private void handleFrameLocation() {
this.setLocation(250, 350);
}
private void handleFrameSize() {
this.pack();
this.setSize(this.getWidth() + 20, this.getHeight() + 10);
}
}
Why are these coming and how can I remove them?
I guess these are to do with the font itself and not Java but I am not sure of that. I tried with some other fonts as well same results.
If you need more information please ask me.
My "suspicion" is the algorithm trying to figure out how the composition should work is having trouble with the anti aliasing of the text.
Generally when I want to do these things, I make the window completely transparent and move the logic to another container instead, this seems to do a better job, generally and eliminates the "oddities" created by the platform and how it handles transparent windows - but that's me.
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TranscluentWindow {
public static void main(String[] args) {
new TranscluentWindow();
}
public TranscluentWindow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JWindow frame = new JWindow();
frame.setAlwaysOnTop(true);
frame.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
frame.setBackground(new Color(0, 0, 0, 0));
frame.add(new TranslucentPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TranslucentPane extends JPanel {
private float opacity = 1;
public TranslucentPane() {
setOpaque(false);
setLayout(new BorderLayout());
JLabel label = new JLabel("Hello World! Welcome to this app!");
label.setForeground(Color.RED);
label.setBorder(new EmptyBorder(8, 8, 8, 8));
add(label);
JSlider slider = new JSlider();
slider.setMinimum(0);
slider.setMaximum(100);
slider.setValue(100);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
setOpacity(slider.getValue() / 100f);
}
});
add(slider, BorderLayout.SOUTH);
}
public void setOpacity(float opacity) {
this.opacity = opacity;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(opacity));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
}
}
}
I'm trying to print a string that the user can enter to a textbox, to a JFrame.
My problem is that the paintComponent method is never being called. Why?
PNGCreatorWindow Class:
public class PNGCreatorWindow {
private JFrame frame;
private JTextField txtText;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PNGCreatorWindow window = new PNGCreatorWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PNGCreatorWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 678, 502);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtText = new JTextField();
txtText.setBounds(121, 13, 216, 22);
frame.getContentPane().add(txtText);
txtText.setColumns(10);
JButton btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnGenerate.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
GeneratePNGImage();
}
});
btnGenerate.setBounds(436, 6, 183, 36);
frame.getContentPane().add(btnGenerate);
JPanel panel = new JPanel();
panel.setBounds(107, 151, 338, 160);
frame.getContentPane().add(panel);
}
protected void GeneratePNGImage() {
PNGImage img = new PNGImage(txtText.getText());
frame.getContentPane().add(img);
frame.getContentPane().validate();
frame.getContentPane().setVisible(true);
frame.repaint();
}
}
PNGImage Class:
public class PNGImage extends JComponent {
private String text;
public PNGImage(String text){
this.text = text;
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.red);
g2.drawString(this.text, 100,100);
g2.fillRect(50, 50, 1000, 1000);
}
}
I made a few changes to your code to get it to draw the text on the JPanel.
I put the JTextField and the JButton inside of a control panel (JPanel) and set a layout manager (FlowLayout) for the control panel. You should always use a layout manager for laying out Swing components.
I defined the image panel (PNGImage) as part of the laying out of the Swing components. First, you lay all of the Swing components out. Then, you change their state.
I removed the mouse adapter and just used an action listener on the JButton. The action listener works with the mouse.
In the PNGImage class, I added a setter, so I could pass the text to the class later, after the user typed the text in the JTextField.
I added a call to setPreferredSize so that I could set the size of the drawing canvas. I removed all other sizing, and used the pack method of JFrame to make the JFrame the appropriate size to hold the Swing components.
I added a null test to paintComponent, so that the text would only be drawn when there was some text to draw.
Here's the code. I put all the code in one module to make it easier to paste.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class PNGCreatorWindow {
private JFrame frame;
private JTextField txtText;
private PNGImage imagePanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new PNGCreatorWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PNGCreatorWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
txtText = new JTextField(10);
controlPanel.add(txtText);
JButton btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
generatePNGImage();
}
});
controlPanel.add(btnGenerate);
imagePanel = new PNGImage();
frame.getContentPane().add(controlPanel, BorderLayout.NORTH);
frame.getContentPane().add(imagePanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
protected void generatePNGImage() {
imagePanel.setText(txtText.getText());
imagePanel.repaint();
}
public class PNGImage extends JPanel {
private static final long serialVersionUID = 602718701626241645L;
private String text;
public PNGImage() {
setPreferredSize(new Dimension(400, 300));
}
public void setText(String text) {
this.text = text;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.text != null) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.drawString(this.text, 100, 100);
}
}
}
}
Edited to add an action listener that saves the contents of a JPanel as a .png file:
package com.ggl.crossword.controller;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.ggl.crossword.view.CrosswordFrame;
public class CreateImageActionListener implements ActionListener {
private CrosswordFrame frame;
private JPanel panel;
public CreateImageActionListener(CrosswordFrame frame,
JPanel panel) {
this.frame = frame;
this.panel = panel;
}
#Override
public void actionPerformed(ActionEvent event) {
writeImage();
}
public void writeImage() {
FileFilter filter =
new FileNameExtensionFilter("PNG file", "png");
JFileChooser fc = new JFileChooser();
fc.setFileFilter(filter);
int returnValue = fc.showSaveDialog(frame.getFrame());
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (!file.getAbsolutePath().endsWith(".png")) {
file = new File(file.getAbsolutePath() + ".png");
}
RenderedImage image = createImage(panel);
try {
ImageIO.write(image, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private BufferedImage createImage(JPanel panel) {
int w = panel.getWidth();
int h = panel.getHeight();
BufferedImage bi = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
panel.paint(g);
g.dispose();
return bi;
}
}
I have Code where I can move image.
Everything works well.
here I have only one ImagePanel (children of JPanel) on the frame.
Questions:
I need to drag and drop image from one JPanel to another JPanel.
Then I need to move dragged image to current panel.
Can you give me an example code, please?
class ImagePanel extends JPanel {
int x, y;
BufferedImage image;
ImagePanel() {
setBackground(Color.white);
setSize(450, 400);
addMouseMotionListener(new MouseMotionHandler());
Image img = getToolkit().getImage("C:\\2.png");
MediaTracker mt = new MediaTracker(this);
mt.addImage(img, 1);
try {
mt.waitForAll();
} catch (Exception e) {
System.out.println("Image not found.");
}
image = new BufferedImage(img.getWidth(this), img.getHeight(this),BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.drawImage(img, 0, 0, this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(image, x, y, this);
}
class MouseMotionHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {
}
}
}
I need to do that code, with this following design. I need to add image with some layout (I don't need to done this with Point pixels). or how to add image with some layout? for example Grid bag layout. I don't need Points (x,y). because I need to add another components too.
public class DragAndDrop {
private JFrame frame;
/* .. another component here .. */
private JPanel leftPanel; // here is my image
public JPanel rightContentPanel; // destination of dragable image
public static void main(String[] args) {
DragAndDrop window = new DragAndDrop();
}
public DragAndDrop() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout(0, 0));
leftPanel = new leftPanel();
/* add components to left panel */
rightContentPanel = new rightPanel();
/* add component to right panel */
frame.getContentPane().add(rightContentPanel, BorderLayout.CENTER);
frame.getContentPane().add(leftPanel, BorderLayout.WEST);
frame.setVisible(true);
frame.setResizable(false);
}
}
class leftPanel extends JPanel {
/ ... /
}
class rightPanel extends JPanel{
/ ... /
}
There's probably any number of ways to achieve what you want. You could use the glass pane or JXLayer or you could stop treating the two panels as separate elements and more like they were just windows into a large virtual space.
This example basically treats the parent component as the "virtual space" into which the two image panes are windows.
They both share the same image and image location details. They, individual, convert the image location (which is in virtual coordinates) to local coordinates and draw as much of the image as would appear on them...
Mouse control is maintained by the parent. This greatly simplifies the process, as it can notify both the panels simultaneously
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CrossImage {
public static void main(String[] args) {
new CrossImage();
}
public CrossImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage img;
private ImagePane left;
private ImagePane right;
private Point imagePoint;
public TestPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridLayout(0, 2, 10, 10));
left = new ImagePane();
right = new ImagePane();
imagePoint = new Point(10, 10);
left.setImageLocation(imagePoint);
right.setImageLocation(imagePoint);
try {
img = ImageIO.read(new File("Background.jpg"));
left.setImage(img);
right.setImage(img);
} catch (IOException ex) {
ex.printStackTrace();
}
add(left);
add(right);
MouseAdapter mouseHandler = new MouseAdapter() {
private Point delta;
#Override
public void mousePressed(MouseEvent e) {
Point origin = e.getPoint();
Rectangle bounds = new Rectangle(imagePoint, new Dimension(img.getWidth(), img.getHeight()));
if (bounds.contains(origin)) {
delta = new Point(origin.x - imagePoint.x, origin.y - imagePoint.y);
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (delta != null) {
imagePoint = e.getPoint();
imagePoint.translate(-delta.x, -delta.y);
left.setImageLocation(imagePoint);
right.setImageLocation(imagePoint);
}
}
#Override
public void mouseReleased(MouseEvent e) {
delta = null;
}
};
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
}
}
public class ImagePane extends JPanel {
private Image image;
private Point imageLocation;
public ImagePane() {
setBorder(new LineBorder(Color.DARK_GRAY));
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this), image.getHeight(this));
}
public void setImage(Image image) {
this.image = image;
repaint();
}
public void setImageLocation(Point imageLocation) {
this.imageLocation = imageLocation;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null && imageLocation != null) {
Point p = SwingUtilities.convertPoint(getParent(), imageLocation, this);
g.drawImage(image, p.x, p.y, this);
}
}
}
}
I want to get the data from my textfield and set it to int h. and have that change the size of the rectangle im drawing, but im not sure how to go get the data from the textfield, I tired using e.getsource in actionperfomred but it cannot find my textfield. My code is below:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.sql.*;
import java.lang.Object;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
* This class demonstrates how to load an Image from an external file
*/
public class test extends Component {
int x=77, y=441, w=23, h=10;
BufferedImage img =
new BufferedImage(100, 50,
BufferedImage.TYPE_INT_ARGB);
// BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
// g.fillRect(10,10,10,10);
}
public test() {
try {
img = ImageIO.read(new File("sales-goal.png"));
} catch (IOException e) {}
Graphics2D g = img.createGraphics();
Color myColor = Color.decode("#32004b");
g.setColor(myColor);
g.fillRect(x,y,w,h);
//77,441,23,10
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
//return new Dimension(img.getWidth(null), img.getHeight(null));
return new Dimension(300,600);
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
JTextField textField=new JTextField();
f.add(textField);
textField.setBounds(10,10,40,30);
textField.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new test());
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// if (e.getSource() == textField) {}
}
}
The variable textField is local to main. If you want to access it from actionPerformed, you'll need to change it to an instance variable.
Yeah. I agree with #jpm. You need to declare it as an instance variable.
Do the following:-
public class test extends Component {
//Declare the variable here.
private static JTextField textfield;
public static void main(String[] args) {
//Whenever you use the textfield use like this. Remove the keyword 'JTextField'.
textfield = new JTextField();
}
}
My text Field is not being added to my Jframe, I want to have this textfield available so that I can use it to change the height of a rectangle im drawing in paint. In actionperfomred im trying to get the value from that field and hopefully it will repaint the image with the correct value
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.sql.*;
import java.lang.Object;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class Test extends JPanel implements ActionListener{
JTextField textField;
JFrame f=new JFrame();
int x=77, y=441, w=23, h=10, entry;
BufferedImage img=null;
public void init(){
JTextField textField=new JTextField();
f.add(textField);
textField.setBounds(10,10,40,30);
textField.setVisible(true);
textField.addActionListener(this);
}
// BufferedImage img;
public static void main(String[] args) {
BufferedImage img =new BufferedImage(100, 50,BufferedImage.TYPE_INT_ARGB);
//textField = new JTextField();
JFrame f = new JFrame("Load Image Sample");
/*textField=new JTextField();
textField.addActionListener(this);
f.add(textField);
textField.setBounds(10,10,40,30);
textField.setVisible(true);*/
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new Test());
f.pack();
f.setVisible(true);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
Graphics2D i = img.createGraphics();
Color myColor = Color.decode("#32004b");
i.setColor(myColor);
i.fillRect(x,y,w,h);
// g.fillRect(10,10,10,10);
}
public Test() {
try {
img = ImageIO.read(new File("sales-goal.png"));
} catch (IOException e) {}
//77,441,23,10
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
//return new Dimension(img.getWidth(null), img.getHeight(null));
return new Dimension(300,600);
}
}
public void actionPerformed(ActionEvent e) {
Graphics g= getGraphics();
if (e.getSource() == textField) {
entry= Integer.parseInt(textField.getText());
g.drawString("Test",50,50);
entry=h;
}
}
}
I would suppose it is because you never call the method init
call your init method and you will be fine