Adding background image to JPanel on button action - java

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

Related

Adding KeyAdapter to JComponent

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

Prevent JButton repaint() after click

I have a button. I want to change the background after I click on it. My problem here is the button auto call paintComponent(). How can prevent this? I expect after clicking the button the button will be blue, but it will still be red.
package test;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonDemo extends JButton implements ActionListener{
public ButtonDemo() {
this.setText("BUTTON TEXT");
this.addActionListener(this);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.RED);
}
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
frame.setContentPane(contentPane);
contentPane.add(new ButtonDemo());
frame.setSize(500, 500);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
this.setBackground(Color.BLUE);
}
}
My personal gut feeling is that JButton is probably not suited to your desired goal.
Essentially, you want to control when and how the "selected" state of the piece is changed.
Personally, I would have some kind of controller which monitored the mouse events in some way (probably having the piece component delegate the event back to the controller) and some kind of model which control when pieces become selected, this would then notify the controller of the state change and it would make appropriate updates to the UI.
But that's a long process to setup. Instead, I'm demonstrating a simple concept where a component can be selected with the mouse, but only the controller can de-select. In this example, this will allow only a single piece to be selected
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
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() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(5, 5));
ChangeListener listener = new ChangeListener() {
private PiecePane selectedPiece;
#Override
public void stateChanged(ChangeEvent e) {
if (!(e.getSource() instanceof PiecePane)) { return; }
PiecePane piece = (PiecePane) e.getSource();
// Want to ignore events from the selected piece, as this
// might interfer with the changing of the pieces
if (selectedPiece == piece) { return; }
if (selectedPiece != null) {
selectedPiece.setSelecetd(false);
selectedPiece = null;
}
selectedPiece = piece;
}
};
for (int index = 0; index < 5 * 5; index++) {
PiecePane pane = new PiecePane();
pane.addChangeListener(listener);
add(pane);
}
}
}
public class PiecePane extends JPanel {
private boolean selecetd;
private Color selectedBackground;
private Color normalBackground;
private MouseListener mouseListener;
public PiecePane() {
setBorder(new LineBorder(Color.DARK_GRAY));
mouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
setSelecetd(true);
}
};
setNormalBackground(Color.BLUE);
setSelectedBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
#Override
public void addNotify() {
super.addNotify();
addMouseListener(mouseListener);
}
#Override
public void removeNotify() {
super.removeNotify();
removeMouseListener(mouseListener);
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(ChangeListener.class, listener);
}
protected void fireSelectionChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners.length == 0) {
return;
}
ChangeEvent evt = new ChangeEvent(this);
for (int index = listeners.length - 1; index >= 0; index--) {
listeners[index].stateChanged(evt);
}
}
public boolean isSelected() {
return selecetd;
}
public void setSelecetd(boolean selecetd) {
if (selecetd == this.selecetd) { return; }
this.selecetd = selecetd;
updateSelectedState();
fireSelectionChanged();
}
public Color getSelectedBackground() {
return selectedBackground;
}
public void setSelectedBackground(Color selectedBackground) {
this.selectedBackground = selectedBackground;
updateSelectedState();
}
public Color getNormalBackground() {
return normalBackground;
}
public void setNormalBackground(Color normalBackground) {
this.normalBackground = normalBackground;
updateSelectedState();
}
protected void updateSelectedState() {
if (isSelected()) {
setBackground(getSelectedBackground());
} else {
setBackground(getNormalBackground());
}
}
}
}
I created a toggle button.
You set the primary color and the alternate color in the class constructor.
When you call the switchColors method, the JButton background changes from the primary color to the alternate color. When you call the switchColors method again, the JButton background changes from the alternate color to the primary color.
In the following example, I put the switchColors method in the actionListener so you can see the color change. Each time you left-click on the JButton, the background color changes.
You would call the switchColors method when you want the JButton background to change from blue to red, and again when you want the JButton background to change from red to blue. It's under your control.
import java.awt.BorderLayout;
import java.awt.Color;
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.SwingUtilities;
public class ButtonDemo extends JButton
implements ActionListener {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Button Demo");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
frame.setContentPane(contentPane);
contentPane.add(new ButtonDemo(Color.BLUE,
Color.RED));
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
private boolean primaryBackground;
private Color primaryColor;
private Color alternateColor;
public ButtonDemo(Color primaryColor,
Color alternateColor) {
this.primaryColor = primaryColor;
this.alternateColor = alternateColor;
this.primaryBackground = true;
this.setText("BUTTON TEXT");
this.setBackground(primaryColor);
this.addActionListener(this);
}
public void switchColors() {
primaryBackground = !primaryBackground;
Color color = primaryBackground ? primaryColor :
alternateColor;
this.setBackground(color);
}
#Override
public void actionPerformed(ActionEvent e) {
switchColors();
}
}
If you want to change the background for a short while you can do it with swing Timer:
import java.awt.Color;
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.Timer;
public class ButtonDemo extends JButton implements ActionListener{
private static final int DELAY = 600; //milliseconds
private final Timer timer;
public ButtonDemo() {
this.setText("BUTTON TEXT");
this.addActionListener(this);
Color defaultCloor = getBackground();
timer = new Timer(DELAY, e-> setBackground(defaultCloor));
timer.setRepeats(false);
}
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
frame.setContentPane(contentPane);
contentPane.add(new ButtonDemo());
frame.setSize(300, 200);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
this.setBackground(Color.RED);
timer.start();
}
}

Repeated clicks of JButton automatically

How to make a JButton to be clicked automatically after every second?
I've tried editing the button action performed but that doesn't work.
You can use swing's Timer class and
doClick method with AbstractButton.
Here is a full source code.
package stackoverflow;
import java.awt.Dimension;
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.SwingUtilities;
import javax.swing.Timer;
public class JButtonTimer extends JPanel {
private static final long serialVersionUID = 1L;
private static final int SCREEN_WIDTH = 500;
private static final int SCREEN_HEIGHT = 500;
public JButtonTimer() {
final JButton clickBtn = new JButton("clickMe");
clickBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand());
}
});
add(clickBtn);
Timer timer = new Timer(1 * 1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clickBtn.doClick();
}
});
timer.start();
}
public Dimension getPreferredSize() {
return new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT);
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new JButtonTimer());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Use a SwingTimer and call doClick on the button
import javax.swing.JButton;
import javax.swing.Timer;
public class ButtonClicker implements ActionListener {
private JButton btn;
private Timer timer;
public ButtonClicker(JButton btn) {
this.btn = btn;
timer = new Timer(1000, this);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
#Override
public void actionPerformed(ActionEvent e) {
btn.doClick();
}
}
See How to use Swing Timers for more details
You can put it into WindowOpened Frame event
Timer t = new Timer(1000, jButton.doClick());
t.start();

How to change background in JFrame consisting of JPanels?

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

Keylistener not working with fullscreen

I have created a program in which a window opens which says click to start.When we press start button it opens another window and make it fullscreen. I have add keylistener to this fullscreen window to move an image.But its not working. If you wanna see the code please ask me .
public g1(){
panel = new JPanel();
cake = new ImageIcon("G:\\naman1.jpg").getImage();
start = new JButton("Start");
restart = new JButton("Restart");
exit = new JButton("EXIT");
panel.add(start);
panel.setFocusable(true);
start.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new g1().run(); //this method is from superclass it calls init }
}
);
panel.setBackground(Color.GRAY);
}
public void init(){
super.init(); //it makes the window fullscreen
Window w = s.getFullScreenWindow();
w.setFocusable(true);
w.addKeyListener(this);}
Try this:
The MainFrame
package moveimages;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
JButton startBtn;
public MainFrame() {
this.setTitle("Moving Images");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(initComponents());
this.setSize(new Dimension(1024, 768));
this.setVisible(true);
}
private JPanel initComponents() {
JPanel jPanel = new JPanel();
startBtn = new JButton("start");
startBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final ImageWindow imageWindow = new ImageWindow();
}
});
jPanel.add(startBtn);
return jPanel;
}
}
This is the ImageWindow
package moveimages;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class ImageWindow extends JFrame {
public ImageWindow() {
this.add(new JLabel("Window"));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize.width, screenSize.height);
final ImagePanel imagePanel = new ImagePanel();
this.getContentPane().add(imagePanel);
this.setVisible(true);
}
class ImagePanel extends JPanel {
URL url;
int panelX;
int panelY;
boolean isDragged;
ImagePanel() {
this.panelX = this.getWidth();
this.panelY = this.getHeight();
try {
this.url = new URL("http://i.stack.imgur.com/XZ4V5.jpg");
final ImageIcon icon = new ImageIcon(url);
final JLabel imageLabel = new JLabel(icon);
Action moveLeft = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(imageLabel.getX() - 1 > 0)
imageLabel.setLocation(imageLabel.getX()-1, imageLabel.getY());
}
};
Action moveUp = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(imageLabel.getY() - 1 > 0) {
imageLabel.setLocation(imageLabel.getX(), imageLabel.getY()-1);
}
}
};
Action moveDown = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(getParent().getHeight()-icon.getIconHeight() > imageLabel.getY() + 1) {
imageLabel.setLocation(imageLabel.getX(), imageLabel.getY()+1);
}
}
};
Action moveRight = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(getParent().getWidth()-icon.getIconWidth() > imageLabel.getX()+1) {
imageLabel.setLocation(imageLabel.getX()+1, imageLabel.getY());
}
}
};
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("A"), "moveLeft");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("W"), "moveUp");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("S"), "moveDown");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("D"), "moveRight");
imageLabel.getActionMap().put("moveLeft", moveLeft);
imageLabel.getActionMap().put("moveUp", moveUp);
imageLabel.getActionMap().put("moveDown", moveDown);
imageLabel.getActionMap().put("moveRight", moveRight);
this.add(imageLabel);
} catch (MalformedURLException ex) {
Logger.getLogger(ImageWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Start the App
package moveimages;
import javax.swing.SwingUtilities;
public class MoveImages {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MainFrame frame = new MainFrame();
});
}
}
Maybe it helps you to refactor your current app.

Categories

Resources