Im not sure how to get the data from my text field - java

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();
}
}

Related

Reload BufferImage Data when file changes

I been trying to figure out a way to re-load an image after it has suffer changes. For that I create a refresh button and my plan is, when clicking in this "reload" button re-load the original image so that we can see the new alterations that the file suffer(from an external software like W10 paint).
I tried quite a few things, one of them was using the flush method to attemp to reload the image, but to not avail.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageTest {
public static void main(String[] args) throws IOException {
new ApplicationView1();
}
static class ApplicationView1 extends JFrame{
JButton btnReload;
ImagePanel imagePanel;
public ApplicationView1() throws IOException {
initComponents();
addEventListeners();
setTitle("Pokemon Tile Creator");
setPreferredSize(new Dimension(200, 360));
setResizable(false);
setVisible(true);
pack();
}
private void initComponents() throws IOException {
btnReload = new JButton("Reload");
BufferedImage bufferedImage = ImageIO.read(new File("C:/Florest_PixelArt.png"));
imagePanel = new ImagePanel(bufferedImage);
setLayout(new BorderLayout());
add(btnReload, BorderLayout.PAGE_START);
add(imagePanel, BorderLayout.CENTER);
}
private void addEventListeners() {
btnReload.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
imagePanel.image = ImageIO.read(new File("C:/Florest_PixelArt.png"));
repaint();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
});
}
}
static class ImagePanel extends JPanel{
public BufferedImage image;
public ImagePanel(BufferedImage image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
}

Java - Creating PNG/Textlogo and drawing it to JFrame

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;
}
}

Im not sure how to get the data from my text field

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));
}
}

Not adding TextField to jFrame

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

Page is not refreshing or not getting the input from my text field [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Im not sure how to get the data from my text field
I am entering a number into a text field and using that input to change an int which will change the size of a rectangle, Im not sure if something is wrong, where im not getting that data from that textfield or the page is just not reloading after it gets that data.
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;
// 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");
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 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();
textField.addActionListener(this);
if (e.getSource() == textField) {
entry= Integer.parseInt(textField.getText());
g.drawString("Test",50,50);
entry=h;
}
}
}
You are doing
JTextField textField=new JTextField();
in the main method which is creating a new local variable but your global JTextField textField; is never assigned. In your actionPerformed, you are using the global textField which is never initialized.
Declare the variable as
private static JTextField textField;
Remove 'JTextField' and use it as
textField = new JTextField();
in your main method
I would replace this line in your main method:
JTextField textField=new JTextField();
With these:
textField=new JTextField();
textField.addActionListener(this);
Then I would remove this line from your actionPerformed method:
textField.addActionListener(this);

Categories