how to paint images on clicking button in frame?

試著忘記壹切 提交于 2020-01-05 12:32:09

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/24716597/how-to-paint-images-on-clicking-button-in-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!