how to paint images on clicking button in frame? - java

I've made two buttons in frame .I want to know how to display different images on clicking different buttons?
is there another way out or i have to make panel?I am at beginner stage
package prac;
import java.awt.*;
import java.awt.event.*;
public class b extends Frame implements ActionListener{
String msg;
Button one,two;
b()
{ setSize(1000,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
one=new Button("1");
two=new Button("2");
add(one);
add(two);
one.addActionListener(this);
two.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
msg=e.getActionCommand();
if(msg.equals("1"))
{
msg="Pressed 1";
}
else
msg="pressed 2";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,300);
}
public static void main(String s[])
{
new b();
}
}

Use JLabel and change the icon when button is clicked.
Some points:
call setVisible(true) in the end after adding all the component.
use JFrame#pack() method that automatically fit the components in the JFrame based on component's preferred dimension instead of calling JFrame#setSize() method.
sample code:
final JLabel jlabel = new JLabel();
add(jlabel);
final Image image1 = ImageIO.read(new File("resources/1.png"));
final Image image2 = ImageIO.read(new File("resources/2.png"));
JPanel panel = new JPanel();
JButton jbutton1 = new JButton("Show first image");
jbutton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image1));
}
});
JButton jbutton2 = new JButton("Show second image");
jbutton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image2));
}
});
panel.add(jbutton1);
panel.add(jbutton2);
add(panel, BorderLayout.NORTH);

Related

How do I put a Background Image in this Specific Code? :) JAVA [duplicate]

This question already has answers here:
Simplest way to set image as JPanel background
(7 answers)
Closed 7 years ago.
HI THERE :) I'm trying to figure out what proper code to use so that I can add a background image to this :) HERE ARE THE CODES, what it does is it only displays JLABELs and JBUTTONs, What I need is to put a background image :O
but whenever I try it, it either COVERS the entire thing, or it doesnt display :(
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainFrame
{
JFrame mainFrame = new JFrame("Main Frame");
JPanel mainPanel = new JPanel();
JLabel label1 = new JLabel("A SECOND OF LIFE");
JButton button1 = new JButton("START");
JButton button2 = new JButton("EXIT");
Font font = new Font ("Impact", Font.PLAIN, 40);
JLabel label2 = new JLabel("Do you have what it takes? ");
//JLabel background = new JLabel(new ImageIcon("C:\\Users\\Master Boat\\Desktop\\PH\\horror bg jisha.png"));
//FlowLayout poli = new FlowLayout();
public MainFrame()
{
label1.setAlignmentX(Component.CENTER_ALIGNMENT);
label2.setAlignmentX(Component.CENTER_ALIGNMENT);
button1.setAlignmentX(Component.CENTER_ALIGNMENT);
button2.setAlignmentX(Component.CENTER_ALIGNMENT);
button1.setFont(font);
button2.setFont(font);
label1.setFont(font);
//mainFrame.add(background);
//background.setLayout(poli);
button2.addActionListener(new btnFunc());
button1.addActionListener(new btnFunc2());
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(label1);
mainPanel.add(label2);
mainPanel.add(button1);
mainPanel.add(button2);
mainFrame.setSize(500, 500);
mainFrame.setLocation(500, 100);
mainFrame.add(mainPanel);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
public class btnFunc implements ActionListener {
public void actionPerformed (ActionEvent e) {
JOptionPane.showMessageDialog(null,"YOU ARE A COWARD !", " WAAAAA!",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
}
public class btnFunc2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
new gamesamplingbeta();
}
}
}
You Can add Image in Label on Like :
ImageIcon background;
background = new ImageIcon("/image/image.png");
label= new JLabel() {
public void paintComponent(Graphics g) {
g.drawImage(icon.getImage(), 0, 0, null);
super.paintComponent(g);
}
};

How do i add an action to a JFrame JButton?

I have a JFrame gui im making and I need help.
Im trying to find out how to add a action to my button.
as in using it in a "if" statement or make i print something out when you push it.
thanks!
code:
package agui;
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
JButton button = new JButton("click me");
JPanel panel = new JPanel();
panel.add(button);
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
You want the "addActionListener" method, something like:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You clicked the button");
}
});

How to declare just one

I have the following working code with two buttons as event listeners. One button to get and display a Panel panel1 and the other to get and display another Panel panel2 removing the existing displayed panel. I created two actionPerformed methods for each button to carry out each other's tasks. I just want to make one to shorten the code but I don't know how to detect which button in a panel is displaying at compile time. Any help will be appreciated.
//Switching between panels (screens)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScreenDemo extends JFrame {
private JPanel panel1, panel2;
private JButton btn1, btn2;
JLabel label1 = new JLabel("Screen 1");
JLabel label2 = new JLabel("Screen 2");
public ScreenDemo() {
createPanel(); //Created at Line 14
addPanel(); //Created at Line 28
}
private void createPanel() {
//Panel for first screen
panel1 = new JPanel(new FlowLayout());
btn1 = new JButton("Move to Screen 2");
btn1.addActionListener(new addScreen1ButtonListener());
//Panel for second screen
panel2 = new JPanel(new FlowLayout());
btn2 = new JButton("Move to Screen 1");
btn2.addActionListener(new addScreen2ButtonListener());
}
private void addPanel() {
panel1.add(label1);
panel1.add(btn1);
panel2.add(label2);
panel2.add(btn2);
add(panel1); //Add the first screen panel
}
class addScreen1ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
getContentPane().removeAll();
getContentPane().add(panel2);
repaint();
printAll(getGraphics()); //Prints all content
}
}
class addScreen2ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ea) {
getContentPane().removeAll();
getContentPane().add(panel1);
repaint();
printAll(getGraphics()); //Prints all content
}
}
public static void main(String[] args) {
ScreenDemo screen = new ScreenDemo();
screen.setTitle("Switching Screens");
screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
screen.setSize(500, 500);
screen.setVisible(true);
}
}
implement ActionListener for your class, and try this code
ScreenDemo extends JFrame implements ActionListener
...
btn1.addActionListener(this);
btn2.addActionListener(this);
...
#override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource().equals(btn1)) {
...
}
else if(ae.getSource().equals(btn1)) {
...
}
}
you have to implements the class from ActionListener
than register JButton like : btn.addActionListener(this);
so close now, You just need to capture the event and get the source from where it is called like:
public void actionPerformed(ActionEvent ae) {
if(ae.getSource == btn1){
//shuffle panel from btn1
}
if(ae.getSource == btn2) {
//shuffle panel from btn2
}
}

Add JComponent to applet's pane

I am trying to add an JComponent (label, for instance) to the applet pane when the button is pressed. I have the following piece of code:
public class TestApplet extends JApplet
{
#Override
public void init()
{
setLayout(new FlowLayout());
JButton bt = new JButton("hit it");
bt.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
// getContentPane().setFont(null);
getContentPane().add(new JLabel("to the right"));
}
});
add(bt);
}
}
This does not make the label visible, unless I uncomment getContentPane().setFont(null);
Please advise how should I display the label properly. Thanks in advance.
getContentPane().add(new JLabel("to the right"));
this.revalidate();

Set JLabel Visible when JButton is clicked in actionPerformed

I am trying to get a JLabel to appear when a JButton is clicked. I have added an action listener and added the component to the layout. I am using the label1.setVisible(true) when the JButton is clicked in actionPerformed. I still can't get it work. Can some look at my code?
public class LearnAppMain extends JFrame implements ActionListener {
// Define variables
public JButton button1;
public JLabel label1;
public JTextField field1;
private Image image1;
private String apple = "apple.jpg";
public LearnAppMain() {
ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
JLabel label1 = new JLabel(image1);
button1 = new JButton("A");
button1.addActionListener(this);
field1 = new JTextField(10);
// Create layout
setLayout(new FlowLayout());
// create Container
final Container cn = getContentPane();
cn.add(button1);
cn.add(field1);
cn.add(label1);
// setLayout(new FlowLayout());
setSize(250, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (e.getSource() == button1) {
label1.setVisible(true);
field1.setText("Apple");
}
}
}
I have my main method in another class file. The error I get leads me to the label1.setVisible(true);
Every question I've seen they say to do this, but I'm wondering if there is something else that needs to be added.
There were a couple of issues here:
Your label1 was hidden by doing JLabel label in the constructor. You basically declared another variable called label1 in your constructor that hid the one in the class itself.
Your label was visible on the startup - I used label.setVisible(false) for the test, but you might want otherwise
I also put the creation of Image aside as I did not have an image, so uncomment that and change as appropriate.
Here's a complete working version:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LearnAppMain extends JFrame implements ActionListener {
// Define variables
public JButton button1;
public JLabel label1;
public JTextField field1;
private Image image1;
private String apple = "apple.jpg";
public LearnAppMain() {
//ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
//JLabel label1 = new JLabel(image1);
label1 = new JLabel("hello");
label1.setVisible(false);
button1 = new JButton("A");
button1.addActionListener(this);
field1 = new JTextField(10);
// Create layout
setLayout(new FlowLayout());
// create Container
final Container cn = getContentPane();
cn.add(button1);
cn.add(field1);
cn.add(label1);
// setLayout(new FlowLayout());
setSize(250, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (e.getSource() == button1) {
label1.setVisible(true);
field1.setText("Apple");
}
}
public static void main(String[] args) {
new LearnAppMain();
}
}
I'd suggest using separate (usually inner-class) ActionListener instances instead of overriding actionPerformed. See e.g. this for a similar example if you are interested:
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/events/BeeperProject/src/events/Beeper.java
Also, if you are using this in a bigger application (i.e. not just experimenting or for prototyping), make sure all Swing code is run on EDT.
You typically use SwingUtilities.invokeLater for that purpose.
Hope this helps.
first you don't add the image first itself to JLabel.
just create the object and leave it like..
ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
JLabel label1 = new JLabel("");
label1.setVisible(true);
then do the modification in the action performed
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1)
{
field1.seticon(image1);
field1.revalidate();
}
it will definitely works
clientDetail.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
d.getContentPane().removeAll();
g = new GridBagLayout();
gc = new GridBagConstraints();
d.setLayout(g);
JLabel message= new JLabel(" Message");
addComponent(message,5,1,1,2);
JTextArea Message = new JTextArea();
addComponent(Message,5,1,1,2);
d.setVisible(true);
d.setVisible(true);
d.pack();
}
private void addComponent(Component component, int i, int i0, int i1, int i2) {
gc.gridx=i;
gc.gridy=i0;
gc.gridheight=i1;
gc.gridwidth=i2;
g.setConstraints(component, gc);
add(component);
}
});
Recep.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});

Categories

Resources