White spots appear with text in JFrame - java

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

Related

Change color of drawing by clicking on it AWT JAVA

I want to add to this code the functionality to change color of drawing by clicking on it, but i don't know if this will code support that
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
public class TestGraphic {
public static void main(String[] args) {
new TestGraphic();
}
public TestGraphic() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Frame frame = new Frame();
frame.add(new Composants());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.addWindowListener((WindowListener) new WindowAdapter() {
#Override
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
});
}
public class Composants extends Container {
private Color color = Color.BLACK;
private List<Color> avaliableColors = new ArrayList<>(16);
public Composants() {
setLayout(new BorderLayout());
avaliableColors.add(Color.BLACK);
avaliableColors.add(Color.BLUE);
avaliableColors.add(Color.CYAN);
avaliableColors.add(Color.DARK_GRAY);
avaliableColors.add(Color.GRAY);
avaliableColors.add(Color.GREEN);
avaliableColors.add(Color.LIGHT_GRAY);
avaliableColors.add(Color.MAGENTA);
avaliableColors.add(Color.ORANGE);
avaliableColors.add(Color.PINK);
avaliableColors.add(Color.RED);
avaliableColors.add(Color.WHITE);
avaliableColors.add(Color.YELLOW);
JButton btn = new JButton("Change color");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Randomise the colors
Collections.shuffle(avaliableColors);
color = avaliableColors.get(0);
repaint();
}
});
add(btn, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
public void close() {
addComponentListener((ComponentListener) new WindowAdapter() {
#Override
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
#Override
public void paint(Graphics gui) {
super.paint(gui);
Graphics2D g2d = (Graphics2D) gui.create();
g2d.setColor(color);
g2d.drawOval(108, 110, 200, 200);
g2d.drawOval(160, 150, 20, 20);
g2d.drawOval(240, 150, 20, 20);
g2d.drawRect(160, 220, 100, 40);
g2d.dispose();
}
}
}
What i found on the internet is to create Rectangle class and Circle , but if i could do it just here it will be great, thank you.
What i found on the internet is to create Rectangle class and Circle , but if i could do it just here it will be great, thank you.(duplicate for submitting)
See How to Write a Mouse Listener and Working with Geometry
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
public class TestGraphic {
public static void main(String[] args) {
new TestGraphic();
}
public TestGraphic() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Frame frame = new Frame();
frame.add(new Composants());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.addWindowListener((WindowListener) new WindowAdapter() {
#Override
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
}
});
}
public class Composants extends Container {
private Color color = Color.BLACK;
private List<Color> avaliableColors = new ArrayList<>(16);
private Shape face;
public Composants() {
setLayout(new BorderLayout());
Area area = new Area();
area.add(new Area(new Ellipse2D.Double(108, 110, 200, 200)));
area.add(new Area(new Ellipse2D.Double(160, 150, 20, 20)));
area.add(new Area(new Ellipse2D.Double(240, 150, 20, 20)));
area.add(new Area(new Rectangle2D.Double(160, 220, 100, 40)));
face = area;
avaliableColors.add(Color.BLACK);
avaliableColors.add(Color.BLUE);
avaliableColors.add(Color.CYAN);
avaliableColors.add(Color.DARK_GRAY);
avaliableColors.add(Color.GRAY);
avaliableColors.add(Color.GREEN);
avaliableColors.add(Color.LIGHT_GRAY);
avaliableColors.add(Color.MAGENTA);
avaliableColors.add(Color.ORANGE);
avaliableColors.add(Color.PINK);
avaliableColors.add(Color.RED);
avaliableColors.add(Color.WHITE);
avaliableColors.add(Color.YELLOW);
JButton btn = new JButton("Change color");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
changeColor();
}
});
add(btn, BorderLayout.SOUTH);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (face.contains(e.getPoint())) {
changeColor();
}
}
});
}
protected void changeColor() {
// Randomise the colors
Collections.shuffle(avaliableColors);
color = avaliableColors.get(0);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
public void close() {
addComponentListener((ComponentListener) new WindowAdapter() {
#Override
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
}
#Override
public void paint(Graphics gui) {
super.paint(gui);
Graphics2D g2d = (Graphics2D) gui.create();
g2d.setColor(color);
g2d.drawOval(108, 110, 200, 200);
g2d.drawOval(160, 150, 20, 20);
g2d.drawOval(240, 150, 20, 20);
g2d.drawRect(160, 220, 100, 40);
g2d.dispose();
}
}
}
You should try to make your question clearer. Are you asking if the code will change the color of the circles and rectangle?
If you run this code, you should get an error on line 76 because you can't cast an 'anonymous java.awt.event.WindowAdapter' to 'java.awt.event.ComponentListener'. If you remove the close() method, the color of the circles and rectangle will change.

Image not appearing in jbutton with wordGen

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

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

java draw image over another

Hey I am trying to make a basic launcher and for the design I got an image. I want to make the exit button to be shown over the launcher image so you can see it. I dont know how I do it so I need help with it. Here is my code:
package launcher;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
*
* #author Daniel <Skype: daniel.gusdal>
*
* Current Date: 2. feb. 2014 Current Time: 21:46:52
* Project: 742 client. File Name: Launcher.java
*
*/
public class Launcher extends JFrame {
/**
* Generated serialVersionUID
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
static Point mouseDownCompCoords;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mouseDownCompCoords = null;
final Launcher frame = new Launcher();
frame.setResizable(true);
frame.setUndecorated(true);
frame.setBackground(new Color(0, 255, 0, 0));
frame.setVisible(true);
frame.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
});
frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x
- mouseDownCompCoords.x, currCoords.y
- mouseDownCompCoords.y);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Launcher() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 593);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel Design = new JLabel("New label");
Design.setIcon(new ImageIcon(getClass().getResource("Launcher3.png")));
Design.setBounds(-158, -22, 1047, 592);
contentPane.add(Design);
ImageIcon img = new ImageIcon(getClass().getResource(
"Playnow.png"));
final JButton Playnow = new JButton(img);
Playnow.setBackground(null);
Playnow.setOpaque(false);
Playnow.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"PlaynowHover.png")));
}
#Override
public void mouseClicked(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"PlaynowHover.png")));
System.out.println(Playnow.getIcon());
}
#Override
public void mouseExited(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"Playnow.png")));
}
});
Playnow.setBounds(258, 442, 301, 46);
contentPane.add(Playnow);
final JButton Exit = new JButton();
Exit.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(Exit.getIcon());
System.exit(0);
}
});
Exit.setIcon(new ImageIcon(Launcher.class.getResource("Exit.png")));
Exit.setOpaque(false);
Exit.setBounds(766, 59, 21, 21);
contentPane.add(Exit);
}
}
Don't set bounds. Learn to use Layout Managers.
Paint the image on a JPanel instead of using a JLabel
Put the JButton on the JPanel. Give that JPanel a GridBadLayout
Override the getPreferredSize() of the JPanel.
To switch between images you can use a flag like boolean icon1, icon2, icon3;. and repaint the JPanel the mouseXxx. Something like this
public void mouseClicked(MouseEvent e) {
icon1 = true;
icon2 = false;
icon3 = false;
imagePanel.repaint();
}
....
protected void paintComponent(Graphics g) {
if (icon1) {
g.drawImage(image1, .....);
}
if (icon2) { ... }
if (icon3) { ... }
}
pack() your frame.
Use Java naming convention. variables start with lower case letters.
Here's an example
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.*;
import java.util.logging.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestButtonOverImage {
public TestButtonOverImage() {
JFrame frame = new JFrame("Test Card");
frame.add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestButtonOverImage();
}
});
}
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel() {
setLayout(new GridBagLayout());
add(new JButton("StackOverflow Button"));
try {
img = ImageIO.read(new URL("http://d8u1nmttd4enu.cloudfront.net/designs/logo-stackoverflow-logo-design-99designs_447080~36d200d82d83d7b2e738cebd2a48de07180cef3a_largecrop"));
} catch (MalformedURLException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 100, 100, 300, 300, this);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
}

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

Categories