I'm trying to change the background of my JFrame.
I tried using the setBackground(Color) method to all the JPanel objects and only the area covered between Buttons and all other fields is covered. Can anyone help me here?
output img:
code :
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JOptionPane;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
public class calculator extends JFrame implements ActionListener, KeyListener
{
public JButton[] dig=new JButton[10];
public JButton sin,cos,tan,toNegative,add,subtract,divide,multiply,quad,clear,equals,result,back;
public JTextField txt,a,b,c;
public JPanel inputField,digits,quadSwitcher,eqCls,extras,zero,addSubt;
public int width=280,height=400;
public static String input="";
private ImageIcon img;
private Color color1=Color.ORANGE;
public calculator()
{
super("Calculator");try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}catch(Exception e){}
img=new ImageIcon("calc.png");
this.setIconImage(img.getImage());
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
setSize(width,height);
txt=new JTextField(null,20);
txt.setEditable(true);
inputField=new JPanel();
txt.setPreferredSize(new Dimension(width-50,30));
inputField.add(txt);
this.add(inputField);
txt.addKeyListener(this);
for(int i=0;i<10;i++)
dig[i]=new JButton(i+"");
sin=new JButton("sin");
cos=new JButton("cos");
tan=new JButton("tan");
toNegative=new JButton("+/-");
add=new JButton("add");
subtract=new JButton("Subtract");
add=new JButton("Add");
multiply=new JButton("Multiply");
quad=new JButton("Quadratic Equation");
quad.addActionListener(this);
divide=new JButton("Divide");
equals=new JButton("=");
quadSwitcher=new JPanel();
quadSwitcher.add(quad);
this.add(quadSwitcher);
digits=new JPanel();
digits.setLayout(new GridLayout(3,3,5,5));
for(int i=9;i>=1;i--)
digits.add(dig[i]);
extras=new JPanel();
extras.setLayout(new GridLayout(2,3,4,4));
extras.add(sin);
extras.add(cos);
extras.add(tan);
extras.add(toNegative);
extras.add(multiply);
extras.add(divide);
this.add(digits);
zero=new JPanel();
dig[0].setPreferredSize(new Dimension((width/2)-10,25));
zero.add(dig[0]);
this.add(zero);
this.add(extras);
addSubt=new JPanel();
addSubt.setLayout(new GridLayout(1,2,10,0));
addSubt.setPreferredSize(new Dimension(width-35,30));
addSubt.add(add);
addSubt.add(subtract);
this.add(addSubt);
eqCls=new JPanel();
eqCls.setLayout(new GridLayout(1,2,10,0));
eqCls.setPreferredSize(new Dimension(width-35,30));
clear=new JButton("clear");
eqCls.add(equals);
eqCls.add(clear);
clear.addActionListener(this);
this.add(eqCls);
for(int i=0;i<10;i++)
dig[i].addActionListener(this);
sin.addActionListener(this);
cos.addActionListener(this);
tan.addActionListener(this);
toNegative.addActionListener(this);
equals.addActionListener(this);
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
setVisible(true);
this.setBackground(Color.ORANGE);
inputField.setBackground(color1);
quadSwitcher.setBackground(color1);
eqCls.setBackground(color1);
addSubt.setBackground(color1);
digits.setBackground(color1);
extras.setBackground(color1);
zero.setBackground(color1);
inputField.setOpaque(true);
JOptionPane.showMessageDialog(this,"Developed By Saksham Puri.");
}
public static void main(String args[])
{
calculator ob=new calculator();
}
#Override
public void keyPressed(KeyEvent e)
{
int keyCode=e.getKeyCode();
if(keyCode==KeyEvent.VK_ENTER){
input=txt.getText();
txt.setText(performOperation(input));}
}
#Override
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
if(Character.isDigit(str.charAt(0))) txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("clear"))
txt.setText("");
else if(str.equalsIgnoreCase("tan")) txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("sin"))txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("cos"))txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("add"))txt.setText(txt.getText()+""+"+");
else if(str.equalsIgnoreCase("subtract"))txt.setText(txt.getText()+""+"-");
else if(str.equalsIgnoreCase("+/-"))txt.setText(txt.getText()+""+"-");
else if(str.equalsIgnoreCase("multiply"))txt.setText(txt.getText()+""+"*");
else if(str.equalsIgnoreCase("divide"))txt.setText(txt.getText()+""+"/");
else if(str.equalsIgnoreCase("=")){input=txt.getText(); txt.setText(performOperation(input));}
else if(str.equalsIgnoreCase("Quadratic Equation")) setQuad();
else if(str.equalsIgnoreCase("back"))back();
else if(str.equalsIgnoreCase("calculate")){back(); txt.setText(calcQuad()); revalidate(); repaint();}
}
public void back()
{
inputField.removeAll();
quadSwitcher.removeAll();
inputField.add(txt);
quadSwitcher.add(quad);
revalidate();
repaint();
}
public String calcQuad()
{
return Quad.solveQuad(Integer.parseInt(a.getText()),Integer.parseInt(b.getText()),Integer.parseInt(c.getText()));
}
public void setQuad()
{
inputField.removeAll();
quadSwitcher.removeAll();
a=new JTextField("a",4);
a.setEditable(true);
b=new JTextField("b",4);
b.setEditable(true);
c=new JTextField("c",4);
c.setEditable(true);
inputField.add(a);
inputField.add(new JLabel("x^2 + "));
inputField.add(b);
inputField.add(new JLabel("x + "));
inputField.add(c);
result=new JButton("Calculate");
back=new JButton("Back");
back.addActionListener(this);
result.addActionListener(this);
quadSwitcher.add(result);
quadSwitcher.add(back);
revalidate();
repaint();
}
#Override
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public String performOperation(String str)
{
return "Performed Operation";
}
}
just the color
getContentPane().setBackground(Color.LIGHT_GRAY); //for example
put an image on the background
//create a JComponent to store your image
class ImagePanel extends JComponent
{
private Image image;
public ImagePanel(String str) {
BufferedImage image=null;
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
//in your JFrame class
ImagePanel contentPane = new ImagePanel("./background.png");
this.setContentPane(contentPane);
getContentPane().setBackground(Color.LIGHT_GRAY);// just in case your image does not fit the entire view
Related
Trying to add a keyListener to this component, however I am getting no response. I want it to be respond whenever the component is displayed in the scroll Panel. I've been able to get it to work when adding it to JPanels. Is there something I should be doing differently for my component?
This the the Component I seek to implement Keylistener on.
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.event.MouseInputListener;
import java.awt.FontMetrics;
import java.awt.event.MouseEvent;
import java.awt.Point;
import java.util.ArrayList;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
public class PhotoComponent extends JComponent implements MouseInputListener{
private ImageIcon pic;
Boolean checkVac=false;
Boolean checkSchool=false;
Boolean checkFam= false;
Boolean checkWork = false;
Boolean flipped = false;
Boolean penButton=false;
boolean textButton=false;
public PhotoComponent(){
}
public PhotoComponent(ImageIcon p){
pic=p;
setRequestFocusEnabled(true);
requestFocus();
addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
System.out.println("hello");
}
});
}
#Override
public Dimension getPreferredSize(){
if(pic==null){
return new Dimension(0,0);
}
return new Dimension(pic.getIconWidth(), pic.getIconHeight());
}
#Override
protected void paintComponent(Graphics g){
pic.paintIcon(this, g, 0, 0);
}
}
This is the program I am calling it on.
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.event.MouseInputListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.io.*;
public class Base extends JFrame {
private JPanel statusContainer;
private JScrollPane scrollPane;
private JMenuBar jmb;
private JMenu file;
private JMenuItem importbutton;
private ArrayList<PhotoComponent> picList;
private int picIndex;
public static void main(String[] args) {
new Base();
}
public Base(){
setTitle("Placeholder");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setResizable(true);
mainProgram();
pack();
setVisible(true);
}
public void mainProgram(){
jmb = new JMenuBar();
setJMenuBar(jmb);
file=new JMenu("File");
statusContainer = new JPanel();
add(statusContainer, BorderLayout.SOUTH);
jmb.add(file);
importbutton = new JMenuItem("Import");
//currentPic= new PhotoComponent();
picList= new ArrayList<PhotoComponent>(5);
picIndex = 0;
scrollPane = new JScrollPane();
add(scrollPane);
importbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent fo){
JFileChooser chooser= new JFileChooser("");
FileFilter filter = new FileNameExtensionFilter("Graphics", "jpg","jpeg","png");
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setMultiSelectionEnabled(true);
int response = chooser.showOpenDialog(null);
if(response == JFileChooser.APPROVE_OPTION){
File[] chosen = chooser.getSelectedFiles();
for (File f:chosen) {
if(f.isDirectory()){
File[] temp=f.listFiles();
for (File x:temp){;
ImageIcon ii =new ImageIcon(x.getAbsolutePath());
picList.add(new PhotoComponent(ii));
}
}
else{
ImageIcon ii =new ImageIcon(f.getAbsolutePath());
picList.add(new PhotoComponent(ii));
}
}
scrollPane.setViewportView(picList.get(picIndex));
///mainScroll.addMouseListener(picList.get(pos));
scrollPane.setVisible(true);
validate();
}
else {
JOptionPane.showInputDialog("oops somethings wrong");
}
}
});
file.add(importbutton);
}
}
Ther're many ways how to solve this problem. One of them use KeyEventDispatcher if you need some global key mappings.
Another way is to add KeyListener to you parent JFrame to catch key pressed event and delegate it to the current component. Check this out!
P.S. I am not saying that this is an optimal solution, but I have checked it - it works. You can use it or it can be a start point for your own solution.
public class Base extends JFrame implements ActionListener, KeyListener {
private final JPanel statusContainer = new JPanel();
private final JScrollPane scrollPane = new JScrollPane();
private final JMenuBar menubar = new JMenuBar();
private final JMenu file = new JMenu("File");
private final JMenuItem importButton = new JMenuItem("Import");
private List<PhotoComponent> pictures = Collections.emptyList();
private int pictureIndex = -1;
public static void main(String... args) {
SwingUtilities.invokeLater(() -> new Base().setVisible(true));
}
public Base() {
init();
}
private void init() {
setTitle("Placeholder");
setJMenuBar(menubar);
add(statusContainer, BorderLayout.SOUTH);
add(scrollPane);
file.add(importButton);
menubar.add(file);
setResizable(true);
importButton.addActionListener(this);
addKeyListener(this);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == importButton)
onImportButton();
}
private void onImportButton() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Graphics", "jpg", "jpeg", "png"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.setMultiSelectionEnabled(true);
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
pictures = getPictures(fileChooser);
pictureIndex = pictures.isEmpty() ? -1 : 0;
scrollPane.setViewportView(pictureIndex == -1 ? null : pictures.get(pictureIndex));
scrollPane.setVisible(true);
validate();
} else
JOptionPane.showInputDialog("oops somethings wrong");
}
private static List<PhotoComponent> getPictures(JFileChooser fileChooser) {
List<PhotoComponent> pictures = new ArrayList<>();
for (File fileOrDir : fileChooser.getSelectedFiles())
for (File file : getFiles(fileOrDir))
pictures.add(new PhotoComponent(new ImageIcon(file.getAbsolutePath())));
return pictures;
}
private static List<File> getFiles(File fileOrDir) {
if (fileOrDir.isDirectory())
return Arrays.asList(Objects.requireNonNull(fileOrDir.listFiles()));
return Collections.singletonList(fileOrDir);
}
#Override
public void keyTyped(KeyEvent event) {
}
#Override
public void keyPressed(KeyEvent event) {
if (pictureIndex != -1)
pictures.get(pictureIndex).keyPressed(event);
}
#Override
public void keyReleased(KeyEvent event) {
}
}
public class PhotoComponent extends JComponent {
private final ImageIcon picture;
public PhotoComponent(ImageIcon picture) {
this.picture = picture;
}
public void keyPressed(KeyEvent event) {
System.out.println("keyPressed: " + event.getKeyCode());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(picture.getIconWidth(), picture.getIconHeight());
}
#Override
protected void paintComponent(Graphics g) {
picture.paintIcon(this, g, 0, 0);
}
}
With Swing, I've created a window and want a letter to flash on the screen depending on the BPM (Beats per minute) the user inputs, and I was wondering how I would go about timing the flashing accurately. I tried using a Swing Timer but it is not very accurate and I see a lot of pauses or lag. I've heard something about using System.nanoTime() and System.currentTimeMillis() but have no clue how to implement them to create a timer. Any help would be appreciated!
Note.java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.*;
import java.awt.*;
public class Note extends JFrame implements ActionListener {
JPanel mainScreen = new JPanel();
JPanel south = new JPanel();
JPanel north = new JPanel();
//emptyNumberMain = how many empty panels you want to use
public int emptyNumberMain = 2;
JPanel[] emptyMain = new JPanel[emptyNumberMain];
JLabel title = new JLabel("Fretboard Trainer!");
JButton start = new JButton("Start!");
public static void main(String[] args) {
new Note();
}
public Note() {
super("Random Note!");
setSize(300,300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//creates emptyNumberMain amount of empty panels
for (int i = 0; i < emptyNumberMain; i++) {
emptyMain[i] = new JPanel();
}
mainScreen.setLayout(new BorderLayout());
south.setLayout(new GridLayout(1,1));
south.add(emptyMain[0]);
south.add(start);
south.add(emptyMain[1]);
north.setLayout(new GridLayout(1,2));
north.add(title);
title.setHorizontalAlignment(JLabel.CENTER);
title.setFont(title.getFont().deriveFont(32f));
start.addActionListener(this);
mainScreen.add(north, BorderLayout.NORTH);
mainScreen.add(south, BorderLayout.SOUTH);
add(mainScreen);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) {
dispose();
new RandomNote();
}
}
}
RandomNote.java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.util.Random;
import javax.swing.Timer;
import javax.swing.JSlider;
import java.awt.event.*;
import java.awt.*;
public class RandomNote extends JFrame {
JPanel noteScreen = new JPanel();
JPanel center = new JPanel();
JPanel southSlider = new JPanel();
JLabel bpm = new JLabel();
//emptyNumber = how many empty panels you want to use
int emptyNumber = 2;
JPanel[] empty = new JPanel[emptyNumber];
JLabel rndNote = new JLabel();
JSlider slider = new JSlider(0,200,100);
Timer timer2 = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bpm.setText(Integer.toString(slider.getValue()));
timer.setDelay((int) ((60.0/slider.getValue()) * 1000));
}
});
public RandomNote() {
super("Random Notes!");
timer.start();
timer2.start();
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//creates variable emptyNumber amount of empty panels
for (int i = 0; i < emptyNumber; i++) {
empty[i] = new JPanel();
}
noteScreen.setLayout(new BorderLayout());
center.setLayout(new GridLayout(1,1));
center.add(rndNote);
southSlider.setLayout(new GridLayout(3,1));
slider.setLabelTable(slider.createStandardLabels(20));
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(20);
southSlider.add(slider);
southSlider.add(bpm);
rndNote.setHorizontalAlignment(JLabel.CENTER);
rndNote.setFont(rndNote.getFont().deriveFont(32f));
noteScreen.add(center, BorderLayout.CENTER);
noteScreen.add(southSlider, BorderLayout.SOUTH);
add(noteScreen);
setVisible(true);
}
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rndNote.setText(noteOutput());
}
});
public static String noteOutput() {
Random rand = new Random();
String[] note = {"A", "B", "C", "D", "E", "F", "G"};
int randNum = rand.nextInt(7);
return note[randNum];
}
}
The immediate thing that jumps out at me is this...
Timer timer2 = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bpm.setText(Integer.toString(slider.getValue()));
timer.setDelay((int) ((60.0/slider.getValue()) * 1000));
}
});
Why do you need to update the text and reset the timer every 100 milliseconds?
So, the simple answer would be to use a ChangeListener on the JSlider to determine when the slider's value changes. I'd recommend having a look at How to Use Sliders for more details
As a runnable concept...
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private AnimatableLabel label;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
label = new AnimatableLabel("BMP");
label.setHorizontalAlignment(JLabel.CENTER);
add(label, gbc);
label.start();
JSlider slider = new JSlider(10, 200);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
label.setBPM(slider.getValue());
}
});
slider.setValue(60);
add(slider, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class AnimatableLabel extends JLabel {
private Timer pulseTimer;
private Timer fadeTimer;
private double bpm = 60;
private double alpha = 0;
private Long pulsedAt;
public AnimatableLabel(String text, Icon icon, int horizontalAlignment) {
super(text, icon, horizontalAlignment);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel(String text) {
super(text);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel(Icon image, int horizontalAlignment) {
super(image, horizontalAlignment);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel(Icon image) {
super(image);
setBackground(Color.RED);
initTimer();
}
public AnimatableLabel() {
setBackground(Color.RED);
initTimer();
}
public void start() {
updateTimer();
}
public void stop() {
pulseTimer.stop();
fadeTimer.stop();
}
protected void initTimer() {
pulseTimer = new Timer((int)(getDuration()), new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pulsedAt = System.currentTimeMillis();
alpha = 1.0;
repaint();
}
});
pulseTimer.setInitialDelay(0);
pulseTimer.setCoalesce(true);
fadeTimer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pulsedAt == null) {
return;
}
long fadingDuration = System.currentTimeMillis() - pulsedAt;
alpha = 1.0 - (fadingDuration / getDuration());
if (alpha > 1.0) {
alpha = 1.0;
} else if (alpha < 0.0) {
alpha = 0.0;
}
repaint();
}
});
fadeTimer.setCoalesce(true);
}
protected double getDuration() {
return (60.0 / bpm) * 1000.0;
}
protected void updateTimer() {
fadeTimer.stop();
pulseTimer.stop();
pulseTimer.setDelay((int)getDuration());
pulseTimer.start();
fadeTimer.start();
}
public void setBPM(double bpm) {
this.bpm = bpm;
setText(Double.toString(bpm));
updateTimer();
}
public double getBPM() {
return bpm;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive((float)alpha));
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
}
}
I have developed a swing form which validates entries as the focus is lost from JTextComponent
and if the entry is correct ,the background is painted green Otherwise it is painted red.
Here is the code :-
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
public class Form extends JFrame implements FocusListener{
JTextField fname,lname,phone,email,address;
BufferedImage img;
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){public void run(){new Form();}});
}
public Form()
{
super("Form with Validation Capability");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
setLayout(new GridLayout(5,3));
try {
img=ImageIO.read(new File("src/warning.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
add(new JLabel("First Name :"));
add(fname=new JTextField(20));
add(new JLabel("Last Name :"));
add(lname=new JTextField(20));
add(new JLabel("Phone Number :"));
add(phone=new JTextField(10));
add(new JLabel("Email:"));
add(email=new JTextField(20));
add(new JLabel("Address :"));
add(address=new JTextField(20));
fname.addFocusListener(this);
lname.addFocusListener(this);
phone.addFocusListener(this);
email.addFocusListener(this);
address.addFocusListener(this);
setVisible(true);
}
public void focusGained(FocusEvent e)
{
((JTextComponent) e.getSource()).setBackground(Color.WHITE);
}
public void focusLost(FocusEvent e)
{
if(e.getSource().equals(fname))
{
validationForText(fname);
}
else if(e.getSource().equals(lname))
{
validationForText(lname);
}
else if(e.getSource().equals(email))
{
validationForEmail(email);
}
else if(e.getSource().equals(phone))
{
validationForNumber(phone);
}
else{
((JTextComponent) e.getSource()).setBackground(Color.GREEN);
}
}
public void validationForText(JTextComponent comp)
{
String temp=comp.getText();
if (temp.matches("^[A-Za-z]+$")) {
comp.setBackground(Color.GREEN);
}
else
comp.setBackground(Color.RED);
}
public void validationForNumber(JTextComponent comp)
{
String text=comp.getText();
if(text.matches("^[0-9]+$"))
comp.setBackground(Color.GREEN);
else
comp.setBackground(Color.RED);
}
public void validationForEmail(JTextComponent comp)
{
String text=comp.getText();
if(text.matches("[^#]+#([^.]+\\.)+[^.]+"))
comp.setBackground(Color.GREEN);
else
comp.setBackground(Color.RED);
}
}
Here is the output to my simple app :
Now I also want to draw a warning symbol (buffered image) at the lower left corner of incorrect field.Can anyone help me how to do this as i am not understanding where to paint the image.
(I would like to do it using JLayeredPane as I am learning its application,any code snippet will really help).
Why not simply add a JLabel (using an appropriate LayoutManager to position it) with the inbuilt Swing warning icon UIManager.getIcon("OptionPane.warningIcon")
like so:
JLabel label=new JLabel(UIManager.getIcon("OptionPane.warningIcon"));
see here for more.
UPDATE:
As per your comment I would rather use GlassPane (and add JLabel to glasspane) for this as opposed too JLayeredPane. See here for more on RootPanes
Some suggestions:
Dont extend JFrame unnecessarily
Dont call setSize on JFrame. Use a correct LayoutManager and/or override getPreferredSize() where necessary and replace setSize call with pack() just before setting JFrame visible.
Dont implement FocusListener on the class unless you want to share the functionality with other classes.
Also get into the habit of using FocusAdapter vs FocusListener this applies to a few with appended Listener i.e MouseListener can be replaced for MouseAdapter. This allows us to only override the methods we want. In this case listener is correct as we do something on both overridden methods, but as I said more about the habit
Also always call super.XXX implementation of overridden methods i.e focusGained(FocusEvent fe) unless you are ignoring it for a reason
Here is code with above fixes including glasspane to show warning icon when field is red:
And removes it when is corrected:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
/**
*
* #author David
*/
public class GlassValidationPane extends JComponent {
private static JTextField fname, lname, phone, email, address;
private static GlassValidationPane gvp = new GlassValidationPane();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Form with Validation Capability");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.setResizable(false);
f.setLayout(new GridLayout(5, 3));
f.add(new JLabel("First Name :"));
f.add(fname = new JTextField(20));
f.add(new JLabel("Last Name :"));
f.add(lname = new JTextField(20));
f.add(new JLabel("Phone Number :"));
f.add(phone = new JTextField(10));
f.add(new JLabel("Email:"));
f.add(email = new JTextField(20));
f.add(new JLabel("Address :"));
f.add(address = new JTextField(20));
f.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent ce) {
super.componentResized(ce);
gvp.refreshLocations();
}
});
FocusAdapter fl = new FocusAdapter() {
#Override
public void focusGained(FocusEvent fe) {
super.focusGained(fe);
((JTextComponent) fe.getSource()).setBackground(Color.WHITE);
}
#Override
public void focusLost(FocusEvent fe) {
super.focusLost(fe);
if (fe.getSource().equals(fname)) {
validationForText(fname);
} else if (fe.getSource().equals(lname)) {
validationForText(lname);
} else if (fe.getSource().equals(email)) {
validationForEmail(email);
} else if (fe.getSource().equals(phone)) {
validationForNumber(phone);
} else {
gvp.removeWarningIcon(((Component) fe.getSource()));
((JTextComponent) fe.getSource()).setBackground(Color.GREEN);
}
}
};
fname.addFocusListener(fl);
lname.addFocusListener(fl);
phone.addFocusListener(fl);
email.addFocusListener(fl);
address.addFocusListener(fl);
f.setGlassPane(gvp);
f.pack();
f.setVisible(true);
gvp.setVisible(true);
}
public void validationForText(JTextComponent comp) {
String temp = comp.getText();
if (temp.matches("^[A-Za-z]+$")) {
setGreen(comp);
} else {
setRed(comp);
}
}
public void validationForNumber(JTextComponent comp) {
String text = comp.getText();
if (text.matches("^[0-9]+$")) {
setGreen(comp);
} else {
setRed(comp);
}
}
public void validationForEmail(JTextComponent comp) {
String text = comp.getText();
if (text.matches("[^#]+#([^.]+\\.)+[^.]+")) {
setGreen(comp);
} else {
setRed(comp);
}
}
private void setRed(JTextComponent comp) {
comp.setBackground(Color.RED);
gvp.showWarningIcon(comp);
}
private void setGreen(JTextComponent comp) {
comp.setBackground(Color.GREEN);
gvp.removeWarningIcon(comp);
}
});
}
private HashMap<Component, JLabel> warningLabels = new HashMap<>();
private ImageIcon warningIcon;
public GlassValidationPane() {
setLayout(null);//this is the exception to the rule case a layoutmanager might make setting Jlabel co-ords harder
setOpaque(false);
Icon icon = UIManager.getIcon("OptionPane.warningIcon");
int imgW = icon.getIconWidth();
int imgH = icon.getIconHeight();
BufferedImage img = ImageUtilities.getBufferedImageOfIcon(icon, imgW, imgH);
warningIcon = new ImageIcon(ImageUtilities.resize(img, 24, 24));
}
void showWarningIcon(Component c) {
if (warningLabels.containsKey(c)) {
return;
}
JLabel label = new JLabel();
label.setIcon(warningIcon);
//int x=c.getX();//this will make it insode the component
int x = c.getWidth() - label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
add(label);
label.setVisible(true);
revalidate();
repaint();
warningLabels.put(c, label);
}
public void removeWarningIcon(Component c) {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component component = entry.getKey();
JLabel jLabel = entry.getValue();
if (component == c) {
remove(jLabel);
revalidate();
repaint();
break;
}
}
warningLabels.remove(c);
}
public void refreshLocations() {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component c = entry.getKey();
JLabel label = entry.getValue();
//int x=c.getX();//this will make it insode the component
int x = c.getWidth() - label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
revalidate();
repaint();
}
}
}
class ImageUtilities {
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
public static BufferedImage getBufferedImageOfIcon(Icon icon, int imgW, int imgH) {
BufferedImage img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
return img;
}
}
My problem here is,
after clicking Browse button it displays all files in a directory to choose,
then the chosen image is displayed in GUI correctly. But When i click Browse button
for the second time, it shows the old image only instead of showing the new one. Please help me in this.
For reference, i uploaded the UI.
package GUI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
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.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
#SuppressWarnings("serial")
public class MainAppFrame extends JFrame {
private JPanel contentPane;
File targetFile;
BufferedImage targetImg;
public JPanel panel,panel_1;
private static final int baseSize = 128;
private static final String basePath =
"C:\\Documents and Settings\\Administrator\\Desktop\\Images";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainAppFrame frame = new MainAppFrame();
frame.setVisible(true);
frame.setResizable(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainAppFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panel = new JPanel();
panel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
contentPane.add(panel, BorderLayout.WEST);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseButtonActionPerformed(e);
}
});
JLabel lblSelectTargetPicture = new JLabel("Select target picture..");
JButton btnDetect = new JButton("Detect");
btnDetect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton btnAddDigit = new JButton("Add Digit");
btnAddDigit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton button = new JButton("Recognize");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(6)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(lblSelectTargetPicture)
.addGap(6)
.addComponent(btnBrowse))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(btnDetect)
.addGap(18)
.addComponent(btnAddDigit))))
.addGroup(gl_panel.createSequentialGroup()
.addGap(50)
.addComponent(button))
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(7)
.addComponent(lblSelectTargetPicture))
.addGroup(gl_panel.createSequentialGroup()
.addGap(3)
.addComponent(btnBrowse)))
.addGap(18)
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE)
.addGap(22)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(btnDetect)
.addComponent(btnAddDigit))
.addGap(18)
.addComponent(button)
.addContainerGap())
);
panel.setLayout(gl_panel);
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch (IOException ex) {
Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
panel_1.setLayout(new BorderLayout(0, 0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
}
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
setTarget(file);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
}
}
//JPEGImageFileFilter.java
package GUI;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/*
* This class implements a generic file name filter that allows the listing/selection
* of JPEG files.
*/
public class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter
{
public boolean accept(File f)
{
if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
if (f.getName().toLowerCase().endsWith(".jpg")) return true;
if(f.isDirectory())return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}
Each time a new image is selected, you're creating components unnecessarily and in error here:
public void setTarget(File reference) {
//....
panel_1.setLayout(new BorderLayout(0, 0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
Instead I would recommend that you have all these components created from the get-go, before any file/image has been selected, and then in this method, create an ImageIcon from the Image, and then simply use this Icon to set the Icon of an already existng JLabel rather than a new JLabel. This is done simply by calling myLabel.setIcon(new ImageIcon(targetImg));
Create an ImageViewer with method like ImageViewer.setImage(Image), display the image in a JLabel.
ImageViewer
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;
public class ImageViewer {
JPanel gui;
/** Displays the image. */
JLabel imageCanvas;
/** Set the image as icon of the image canvas (display it). */
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui==null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5,5,5,5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300,100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
public static Image getRandomImage(Random random) {
int w = 100 + random.nextInt(400);
int h = 50 + random.nextInt(200);
BufferedImage bi = new BufferedImage(
w,h,BufferedImage.TYPE_INT_RGB);
return bi;
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Image Viewer");
// TODO Fix kludge to kill the Timer
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageViewer viewer = new ImageViewer();
f.setContentPane(viewer.getGui());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
ActionListener animate = new ActionListener() {
Random random = new Random();
#Override
public void actionPerformed(ActionEvent arg0) {
viewer.setImage(getRandomImage(random));
}
};
Timer timer = new Timer(1500,animate);
timer.start();
}
};
SwingUtilities.invokeLater(r);
}
}
I modified your code , I hope it will fulfill your requirement. I use MigLayout (it is a Layout manager) to arrange the component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
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.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
public class MyFileChooser
{
JFrame frame;
JPanel panel;
JButton btnBrowse;
JButton change;
JLabel imglabel;
File targetFile;
BufferedImage targetImg;
private static final int baseSize = 128;
private static final String basePath ="/images/fimage";
JPanel panel_1;
ImageIcon icon;
public MyFileChooser()
{
// TODO Auto-generated constructor stub
frame =new JFrame();
frame.setLayout(new MigLayout());
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel(new MigLayout());
panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(5, 5, 5), 1, true));
panel_1.setBackground(Color.pink);
btnBrowse=new JButton("browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseButtonActionPerformed(e);
}
});
change=new JButton("Delete");
change.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
changeButtonActionPerformed(e);
}
private void changeButtonActionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
imglabel.revalidate(); //ADD THIS AS WELL
imglabel.repaint(); //ADD THIS AS WELL
imglabel.setIcon(null);
System.out.println("delete button activated");
}
});
imglabel=new JLabel("Image");
imglabel.setSize(100, 100);
imglabel.setBackground(Color.yellow);
frame.add(panel_1,"span,pushx,pushy,growx,growy");
frame.add(btnBrowse);
frame.add(change,"");
//frame.pack();
}
protected void browseButtonActionPerformed(ActionEvent e)
{
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
imglabel.setIcon(null);
setTarget(file);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch (IOException ex) {
// Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
panel_1.setLayout(new BorderLayout(0, 0));
icon=new ImageIcon(targetImg);
imglabel=new JLabel(icon);
panel_1.add(imglabel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new MyFileChooser();
}
});
}
}
JPEGImageFileFilter class , you can keep this class in same pakage
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class JPEGImageFileFilter extends FileFilter implements FileFilter
{
public boolean accept(File f)
{
if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
if (f.getName().toLowerCase().endsWith(".jpg")) return true;
if(f.isDirectory())return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}
What is the best way to add a background image to a JPanel/JLabel when a JButton is called? I know how to get the JButton action and such. I just can't figure out or find a way to get the background image to change when that button is pressed.
Here is an example:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class ModifiableBackgroundFrame extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private ImageIcon image;
private JPanel pan;
private JButton btn;
private int count = 0;
private static final String[] images =
{"http://www.dvd-ppt-slideshow.com/images/ppt-background/background-3.jpg",
"http://www.psdgraphics.com/wp-content/uploads/2009/02/abstract-background.jpg",
"http://hdwallpaperpics.com/wallpaper/picture/image/background.jpg",
"http://www.highresolutionpics.info/wp-content/uploads/images/beautiful-on-green-backgrounds-for-powerpoint.jpg"};
public ModifiableBackgroundFrame()
{
super("The title");
image = new ImageIcon();
btn = new JButton("Change background");
btn.setFocusPainted(false);
btn.addActionListener(this);
pan = new JPanel()
{
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g)
{
g.drawImage(image.getImage(), 0, 0, null);
}
};
pan.setPreferredSize(new Dimension(400, 400));
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(pan, BorderLayout.CENTER);
contentPane.add(btn, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new ModifiableBackgroundFrame();
}
});
}
#Override
public void actionPerformed(ActionEvent e)
{
btn.setEnabled(false);
btn.setText("Loading...");
new SwingWorker<Image, Void>()
{
#Override
protected Image doInBackground() throws Exception
{
return ImageIO.read(new URL(images[count++ % 4]));
}
#Override
protected void done()
{
try
{
image.setImage(get());
pan.repaint();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
catch(ExecutionException e)
{
e.printStackTrace();
}
btn.setText("Change background");
btn.setEnabled(true);
}
}.execute();
}
}
In your JButton's actionPerformed, you can call JLabel.setIcon(Icon) to set a background image.
final JLabel label = new JLabel();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(SOME_IMAGE));
}
}