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
}
} );
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 Want to capture Image from screen and draw it in JPanel , it works but it is displayed one more time like entering in a loop , I am confused by this , How can I fix it ,Please?
Varibles Iwidth,Ihieght ares above initiaized, but I take the block of code that cause the problem
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Image img;
ImageIcon i = null;
Rectangle screenRect=new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
try {
BufferedImage capture=new Robot().createScreenCapture(screenRect);
capture.getHeight();
capture.getWidth();
i=new ImageIcon(capture);
} catch (AWTException ex) {
Logger.getLogger(TestDrawing.class.getName()).log(Level.SEVERE, null, ex);
}
img = i.getImage();
g.drawImage(img,Iwidth,Ihieght,null);
super.repaint();
}
Never have code like that inside of paintComponent. That method should be reserved for painting and painting only, and is a method that you don't really have full control over since it is called by the JVM in response to both your request, and to requests from the OS, and even if you request a repaint, there's no guarantee that it will be complied with, especially if the requests are stacking up. Also, your GUI's perceived responsiveness will often depend on how quick painting is done, which is while file reading and image capturing should never be done inside of paintComponent.
Instead, you should read the image in as a reaction to some event, perhaps a Timer, then after the image is read, call repaint() and in paintComponent draw the obtained image.
Never call repaint() inside of paintComponent either.
Something like in pseudo code
// inside of the ActionListener of a Swing Timer (if you want to do this repeatedly)
get screen image from robot and feed it into the capture BufferedImage field
consider doing this in a SwingWorker
call repaint() when SwingWorker is done (via a PropertyChangeListener)
Inside of paintComponent:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (capture != null) {
g.drawImage(capture, capture.getWidth(), capture.getHeight());
}
}
Edit
For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
import javax.swing.SwingWorker.StateValue;
public class ScreenCaptureTest extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 400;
private JButton btn = new JButton(new ScreenCaptureAction(this,
"Capture Screen", KeyEvent.VK_C));
private ImagePanel imagePanel = new ImagePanel();
public ScreenCaptureTest() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(btn);
setLayout(new BorderLayout());
add(new JScrollPane(imagePanel), BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
public void setImagePanelImage(BufferedImage img) {
imagePanel.setImage(img);
revalidate();
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
ScreenCaptureTest mainPanel = new ScreenCaptureTest();
JFrame frame = new JFrame("ScreenCaptureTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class ImagePanel extends JPanel {
private BufferedImage image;
public void setImage(BufferedImage image) {
this.image = image;
revalidate();
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, null);
}
}
#Override
public Dimension getPreferredSize() {
if (image != null) {
return new Dimension(image.getWidth(), image.getHeight());
}
return super.getPreferredSize();
}
}
class ScreenCaptureAction extends AbstractAction {
private ScreenCaptureTest screenCaptureTest;
public ScreenCaptureAction(ScreenCaptureTest screenCaptureTest, String name,
int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.screenCaptureTest = screenCaptureTest;
}
#Override
public void actionPerformed(ActionEvent e) {
setEnabled(false);
final SwingWorker<BufferedImage, Void> mySwingWorker = new SwingWorker<BufferedImage, Void>() {
#Override
protected BufferedImage doInBackground() throws Exception {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Robot robot = new Robot();
BufferedImage capture = robot.createScreenCapture(new Rectangle(
screenSize));
return capture;
}
};
mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if ("state".equals(pcEvt.getPropertyName())
&& pcEvt.getNewValue() == StateValue.DONE) {
setEnabled(true);
try {
screenCaptureTest.setImagePanelImage(mySwingWorker.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
});
mySwingWorker.execute();
}
}
Edit
Note, that if this were my program, I'd display the image as an ImageIcon in a JLabel as it is much simpler to code. Then you could do away with the ImagePanel class and its paintComponent method, and simply code the main as:
public class ScreenCaptureTest extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 400;
private JButton btn = new JButton(new ScreenCaptureAction(this,
"Capture Screen", KeyEvent.VK_C));
//!! private ImagePanel imagePanel = new ImagePanel();
private JLabel screenLabel = new JLabel(); //!!
public ScreenCaptureTest() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(btn);
setLayout(new BorderLayout());
//!! add(new JScrollPane(imagePanel), BorderLayout.CENTER);
add(new JScrollPane(screenLabel), BorderLayout.CENTER); //!!
add(buttonPanel, BorderLayout.SOUTH);
}
public void setImagePanelImage(BufferedImage img) {
//!! imagePanel.setImage(img);
Icon icon = new ImageIcon(img);
screenLabel.setIcon(icon);
//!! revalidate();
//!! repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
ScreenCaptureTest mainPanel = new ScreenCaptureTest();
JFrame frame = new JFrame("ScreenCaptureTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
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 am trying to make an applet run as a JFrame. The code I have below is simple but should work. It will run as an JApplet but when I go to RUN AS --> nothing appears.
import java.awt.*;
import java.applet.Applet;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LifeCycle extends Applet
{
private static final long serialVersionUID = 1L;
String output = "test";
String event;
public void init()
{
gui(); //I am not certain if this needs to be there.
event = "\nInitializing...";
printOutput();
}
public void start()
{
event = "\nStarting...";
printOutput();
}
public void stop()
{
event = "\nStopping...";
printOutput();
}
public void destroy()
{
event = "\nDestroying...";
printOutput();
}
private void printOutput()
{
System.out.println(event);
output += event;
repaint();
}
private void gui() {
JFrame f = new JFrame("Not resizable");
JPanel d = new JPanel();
// LifeCycle a = new LifeCycle();
// a.init();//not working
d.setLayout(new BorderLayout());
d.add(new JButton("a"));
d.add(new JButton("b"));
d.setBackground(Color.RED);
//f.add(new LifeCycle());
f.add(d);
f.setSize(545,340);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setTitle("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//a.destroy();
}
public void paint(Graphics g)
{
System.out.println("Graphics Paint Method!");
g.drawString(output, 100, 100);
}
public static void main(String[] args) {
LifeCycle l = new LifeCycle();
l.gui();
}
}
I would like to see the code that should be changed, but I cannot seem to find why this will not work. I have added to buttons to the panel to be displayed.
Don't mix AWT (Applet) with Swing components. Stick with just Swing.
Gear your class towards creating JPanels. Then you can place it in a JApplet if you want an applet or a JFrame if you want a JFrame.
Read up on use of BorderLayout -- you're adding multiple components to the default BorderLayout.CENTER position, and only one component, the last one added, will show.
For example ...
LifeCycle2.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
class LifeCycle2 {
private static final int GAP = 5;
private static final int PREF_W = 545;
private static final int PREF_H = 340;
private JPanel mainPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return LifeCycle2.this.getPreferredSize();
}
};
public LifeCycle2() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
buttonPanel.add(new JButton("A"));
buttonPanel.add(new JButton("B"));
buttonPanel.setOpaque(false);
JPanel flowLayoutPanel = new JPanel();
flowLayoutPanel.setOpaque(false);
flowLayoutPanel.add(buttonPanel);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.setBackground(Color.red);
mainPanel.add(flowLayoutPanel, BorderLayout.NORTH);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public JComponent getMainPanel() {
return mainPanel;
}
}
Show as a JFrame,
LifeCycleFrame.java
import javax.swing.*;
public class LifeCycleFrame {
private static void createAndShowGui() {
LifeCycle2 lifeCycle2 = new LifeCycle2();
JFrame frame = new JFrame("LifeCycleTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(lifeCycle2.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Show as an applet,
LifeCycleApplet.java
import java.lang.reflect.InvocationTargetException;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
public class LifeCycleApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
LifeCycle2 lifeCycle2 = new LifeCycle2();
getContentPane().add(lifeCycle2.getMainPanel());
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}
Add f.setVisible(true); to the end of the gui() method. Without this call your frame won't be shown.
Please read the "How to Make Frames" Tutorial
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();
}
}