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;
}
}
Related
The image isn't being painted when this is run with WordGen, how do i fix this?
When I run this without wordgen I can get the image to appear. I'm not sure what i'm doing wrong since i'm not getting any errors.
Any help is appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tfot extends JComponent{
private static final long serialVersionUID = 1L;
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI(args);
}
});
}
public static void showGUI(String[] args) {
JPanel displayPanel = new JPanel();
JButton okButton = new JButton("Did You Know?");
okButton.setFont(new Font("Times", Font.TRUETYPE_FONT, 100));
final JLabel jLab = new JLabel();
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jLab.setText(wordGen());
}
});
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
content.add(jLab, BorderLayout.NORTH);
JFrame window = new JFrame("Window");
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(Toolkit.getDefaultToolkit().getImage("Pictures/background1.png"), 0, 0, this);
}
public static String wordGen() {
String[] wordListOne = {"generic text","hi",};
int oneLength = wordListOne.length;
int rand1 = (int) (Math.random() * oneLength);
String phrase = wordListOne[rand1] + " ";
return phrase;
}
}
First...
Don't load resources or perform long running tasks within the paint methods, these may be called a number of times in quick succession. Instead, load the images before hand and paint them as needed...
public Tfot() {
setLayout(new BorderLayout());
try {
background = ImageIO.read(new File("pictures/background1.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
g.drawImage(background, 0, 0, this);
}
}
Generally, you are discouraged from overriding paint and instead should use paintComponent, lots of reasons, but generally, this is where the background is painted...
Second...
You need to add Tfot to something that is displayable, otherwise it will never be painted
JFrame window = new JFrame("Window");
window.setContentPane(new Tfot());
window.add(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
Thrid...
JPanel by default is not transparent, you need to set it's opaque property to false
JPanel displayPanel = new JPanel();
displayPanel.setOpaque(false);
//...
JPanel content = new JPanel();
content.setOpaque(false);
Then it will allow what ever is below it to show up (ie, the background image)
Take a look at Painting in AWT and Swing, Performing Custom Painting and Reading/Loading an Image for more details
Fourth...
You need to learn the language basics for embarking on advance topics like GUI and custom painting, without this basic knowledge, this topics will bite you hard.
You need to declare background as a instance field of the class Tfot
private BufferedImage background;
public Tfot() {
Updated - Fully runnable example
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Tfot extends JComponent {
private static final long serialVersionUID = 1L;
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI(args);
}
});
}
public static void showGUI(String[] args) {
JPanel displayPanel = new JPanel();
displayPanel.setOpaque(false);
JButton okButton = new JButton("Did You Know?");
okButton.setFont(new Font("Times", Font.TRUETYPE_FONT, 100));
final JLabel jLab = new JLabel();
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jLab.setText(wordGen());
}
});
JPanel content = new JPanel();
content.setOpaque(false);
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
content.add(jLab, BorderLayout.NORTH);
Tfot tfot = new Tfot();
tfot.setLayout(new BorderLayout());
tfot.add(content);
JFrame window = new JFrame("Window");
window.setContentPane(tfot);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
}
private BufferedImage background;
public Tfot() {
try {
background = ImageIO.read(new File("Pictures/background1.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, this);
}
public static String wordGen() {
String[] wordListOne = {"generic text", "hi",};
int oneLength = wordListOne.length;
int rand1 = (int) (Math.random() * oneLength);
String phrase = wordListOne[rand1] + " ";
return phrase;
}
}
I've made a Jpanel with a background image and a Jbutton also with its background. The problem is that background sometimes is loaded sometimes no.
public class Window extends JFrame {
public static JFrame createwindow() {//fare singleton
JFrame frame = new JFrame("Battaglia navale");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(740, 740);
frame.setVisible(true);
frame.setResizable( false );
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(((int)dim.getWidth()-(int)frame.getWidth())/2, ((int)dim.getHeight()-(int)frame.getHeight())/2);
return frame;
}
}
public class StartWindow {
JFrame frame;
private JButton button;
private JButton button2;
final String button_start = "img/start.png";
ImageIcon start = new ImageIcon(button_start);
public void CreateStartWindow() {
frame = Window.createwindow();
Container container = frame.getContentPane();
JpanelStart panel = new JpanelStart();
container.add(panel);
this.button = new JButton(start);
button.setActionCommand("start");
button.setHideActionText(true);
button.setOpaque(false);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
this.button2 = new JButton("Classifica");
panel.add(button);
panel.add(button2);
frame.setVisible(true);
}
public void addActionListener(ActionListener al) {
this.button.addActionListener(al);
this.button2.addActionListener(al);
}
public void chiudi() {
frame.dispose();
}
}
class JpanelStart extends JPanel {
private Image img;
private String path_img = "img/sfondo.jpg";
public JpanelStart() {
img = Toolkit.getDefaultToolkit().createImage(path_img);
loadImage(img);
}
private void loadImage(Image img) {
try {
MediaTracker track = new MediaTracker(this);
track.addImage(img, 0);
track.waitForID(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
setOpaque(false);
g.drawImage(img, 0, 0, this);
super.paintComponent(g);
}
}
super.paintComponet should go right after the method signature.
you set the button opacity to false, so it won't be seen.
Run your program from the Event Dispatch Thread.
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new StartWindow().CreateStartWindow();
}
});
}
In your method, you're making the frame visible before adding anything. Leave that out in the method
Don't set the size of the frame. Instead override the getPrefereedSize() of the JPanel and call pack() on the frame.
IMO, I see no use at all for this so-called helper method. I would toss it out the window
You should load your image as an embedded resource, and not from the file system.
img = ImageIO.read(StartWindow.class.getResource(path_img));
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class StartWindow {
JFrame frame;
private JButton button;
private JButton button2;
final String button_start = "img/start.png";
ImageIcon start = new ImageIcon(button_start);
public void CreateStartWindow() throws IOException {
frame = Window.createwindow();
Container container = frame.getContentPane();
JpanelStart panel = new JpanelStart();
container.add(panel);
this.button = new JButton(start);
button.setActionCommand("start");
button.setHideActionText(true);
button.setOpaque(false);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
this.button2 = new JButton("Classifica");
panel.add(button);
panel.add(button2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run() {
try {
new StartWindow().CreateStartWindow();
} catch (IOException ex) {
Logger.getLogger(StartWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public void addActionListener(ActionListener al) {
this.button.addActionListener(al);
this.button2.addActionListener(al);
}
public void chiudi() {
frame.dispose();
}
}
class Window {
public static JFrame createwindow() {//fare singleton
JFrame frame = new JFrame("Battaglia navale");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
return frame;
}
}
class JpanelStart extends JPanel {
private static final int D_W = 700;
private static final int D_H = 700;
private Image img;
private String path_img = "/images/logo.gif";
public JpanelStart() throws IOException {
img = ImageIO.read(StartWindow.class.getResource(path_img));
loadImage(img);
}
private void loadImage(Image img) {
try {
MediaTracker track = new MediaTracker(this);
track.addImage(img, 0);
track.waitForID(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, D_W, D_W, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
}
**Shows Up Every time **
draw the image after super.paintComponent(g) (which draws the component that you want to draw on top of)
call repaint() in loadImage() after the image is set (so that it redraws it)
loadImage() doesn't seem to be setting the img variable does it need to?
(not essential but recommended) you should also move UI changes into the EDT (Event Dispatch Thread).
Example of running a UI task on EDT
This puts UI operations on a queue so that all UI changes are made from the same thread and avoid interference.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
//UI Operations
}
} );
I want to color some JButtons, some other questions here showed me, that it would be easier
to paint a little image (did it with gimp) and set it as icon for the JButton.
The number and size of the buttons should be variable (they're in a grid), so I want a high res image that I can scale how i need it.
The problem now is, I don't know how to 'cut the edges' of the icon, because the buttons have rounded edges.
Here you can see that the image is not inside of the button border.
And here is my method in the class that extends JButton.
public void setYellow() {
URL u = getClass().getResource("/img/yellow.png");
ImageIcon i = new javax.swing.ImageIcon(u);
//Image img = i.getImage();
//img = img.getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
//i = new ImageIcon(img);
setIcon(i);
}
EDIT
package test;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import control.Control;
import view.Field;
import view.View;
public class HelloWorldSwing {
/**
* #param args
*/
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestView.initialize();
}
});
}
}
class TestView {
private static TestView view = new TestView();
public static TestView getView() {
return view;
}
private TestView() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setLayout(new GridLayout(0,3));
int buttonSize = 40;
frame.getContentPane().add(new MyButton(buttonSize));
frame.getContentPane().add(new MyButton(buttonSize));
frame.getContentPane().add(new MyButton(buttonSize));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void initialize() {
}
}
class MyButton extends JButton {
int size;
public MyButton(int size) {
this.size = size;
setPreferredSize(new Dimension(size, size));
this.addActionListener(new ButtonHandler());
setBorder(LineBorder.createGrayLineBorder());
setOpaque(true);
}
public void setYellow() {
//URL u = getClass().getResource("/img/test.png"); // 64x64 png pic
URL u1 = null;
try {
u1 = new URL("http://assets1.qypecdn.net/uploads/users/0195/7210"
+ "/calvin_yellow_original_thumb.jpg");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageIcon i = new javax.swing.ImageIcon(u1);
// Image img = i.getImage();
// img = img.getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
// i = new ImageIcon(img);
setIcon(i);
// setBorderPainted(false);
// setContentAreaFilled(false); did not help
}
}
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MyButton mb = (MyButton) e.getSource();
mb.setYellow();
}
}
EDIT 2
Here are the pictures where the lines in setYellow()
setBorderPainted(false);
setContentAreaFilled(false);
are not commented out (unfortunately there is no difference)
Before button is clicked:
After button is clicked:
UPDATE
I added Borders to the MyButton constructor
setBorder(LineBorder.createGrayLineBorder());
and now the icons are inside the button borders. I added pictures.
But as you can see, we don't have these rounded button edges anymore.
button.setBorderPainted(false);
button.setContentAreaFilled(false);
As seen in this answer.
Update
I do not quite get what you are trying to achieve if not this.
I made the rollover icon to be orange so that we could easily see the size of one button, but otherwise I put 4 in a row to ensure the minimum frame width did not insert extra space between the buttons in a row.
import java.awt.*;
import java.awt.Image;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestView.getView();
}
});
}
}
class TestView {
private static TestView view = new TestView();
public static TestView getView() {
return view;
}
private TestView() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setLayout(new GridLayout(3,4));
int buttonSize = 40;
for (int i=0; i<12; i++) {
frame.getContentPane().add(new MyButton(buttonSize));
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void initialize() {
}
}
class MyButton extends JButton {
int size;
public MyButton(int size) {
this.size = size;
setPreferredSize(new Dimension(size, size));
this.addActionListener(new ButtonHandler());
setOpaque(true);
setYellow();
}
public Image getImage(int sz, Color color) {
BufferedImage bi = new BufferedImage(sz,sz,BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setColor(color);
g.fillRect(0, 0, sz, sz);
g.dispose();
return bi;
}
public void setYellow() {
Image img = getImage(64, Color.YELLOW).getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
setIcon(new ImageIcon(img));
Image rollover = getImage(64, Color.ORANGE).getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
setRolloverIcon(new ImageIcon(rollover));
setBorderPainted(false);
setContentAreaFilled(false);
}
}
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MyButton mb = (MyButton) e.getSource();
mb.setYellow();
}
}
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));
}
}
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