Java:在动作侦听器中使用图形组件

red*_*maj 0 java swing jframe jbutton

我用不同的JButtons制作了一个JFrame,我想从另一个类中获取一个图像.有任何想法吗?或者如何在同一个类上绘制但是在执行的操作上?因为它不允许我做任何图纸......我的编译器总是给我错误信息

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.*;

public class red extends JFrame {

    public JButton b;
    public JButton b1;
    public JButton b2;
    public JButton b3;
    public JButton b4;

    public static Image p;
    public static Graphics g;
    public red() throws IOException {
        gui1 x = new gui1();
        setTitle(" ");
        setSize(1200,700);
        setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        b= new JButton("click");
        b1= new JButton();
        b.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e0){    
                b1.setBounds(0, 0, 200, 200);
                b.show(false);
                add(x);
            }       
        });
        b.setBounds(0, 0, 100, 100);
        add(b1);
        add(b);

        setVisible(true);
    }

    public static void main(String[] args) throws IOException  {
        red k = new red();
    }
}
Run Code Online (Sandbox Code Playgroud)
import java.awt.*;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

public class gui1 extends Canvas {

    public static Image p;

    public void paint(Graphics g){
        g.drawImage(p, 700, 200, 100, 100, this);
    }

    {
        try {
            p= ImageIO.read(new File("Lighthouse.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*ool 5

唷!我在代码中看到了很多错误(即使在我更正了编译错误之后):

  1. 您没有遵循Java命名约定:

    类名应该是名词,大小写混合,每个内部单词的首字母大写

    虽然red是名词,但它应该更具描述性并且是大写的.同样的道理gui1

  2. 你正在扩展JFrame,用简单的英语说:red 是的 JFrame,你应该真的避免这种情况并基于JPanels 创建你的GUI ...参见Java Swing使用扩展JFrame vs callint它在类里面

  3. 您正在设置尺寸(对于JButton您正在使用的尺寸而言,这是一个非常大的窗口),而是使用pack()

  4. 您正在使用null-layout,而像素完美的GUI似乎是为Swing新手创建复杂GUI的最简单方法,您使用它们的次数越多,您将来会发现的与此相关的问题越多,它们难以维护并导致随机问题,他们没有调整大小等.请阅读Null布局是邪恶的,为什么不赞成在Swing中使用空布局?有关为什么要避免使用它的更多信息,以及为什么要更改GUI以使用布局管理器以及空边框以获得组件之间的额外间距.

  5. 您正在使用JFrame#show()您应该使用的弃用方法JFrame#setVisible(...).

  6. 与第4点相关,您不应该调用setBounds(...)方法,而是让计算到布局管理器.

  7. 您没有将程序放在事件调度线程(EDT)上,Swing不是线程安全的,您可以通过更改main()方法来解决此问题,如下所示:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                //Your constructor here
            }
        });
    }
    
    Run Code Online (Sandbox Code Playgroud)
  8. 您正在混合使用AWT和Swing组件,而不是使用AWT Canvas使用JPanel具有更多功能和支持的Swing .

  9. 一旦将图像打包到JAR文件中,图像将成为嵌入式资源,因此开始将它们视为已经存在,而不是embedded-resource标记中显示的外部文件.

  10. 一旦你改变了Canvas,JPanel你应该覆盖它的paintComponent(...)方法,而不是paint(...)把它super.paintComponent(g)作为第一行调用它的方法,也不要忘记添加@Overrides注释.请参阅Swing自定义绘画教程.

  11. 您滥用static关键字的使用,请看静态关键字的工作原理是什么?

在看到上述所有错误之后,我建议您在开始使用图形环境之前返回并学习该语言的基础知识,这只会给您的学习带来更多困难.


根据我的理解,你想在点击按钮上绘制图像,如果是这种情况,那么你可以将你的图像包装在一个JLabel并将其添加JLabel到一个JPanel然后被添加到父项中JPanel,然后将其添加到JFrame:

在此输入图像描述

正如您在上面的GIF中所看到的,用户按下按钮后会显示图标.

显然,如前所述,使用布局管理器和空边框的组合,GUI可以更加"吸引人".

这是通过以下代码完成的:

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImageDrawingFromOneClassToAnother {

    private JFrame frame;

    private JPanel pane;
    private JPanel leftPane;
    private JPanel rightPane;

    private ImageIcon icon;

    private JButton button;

    private JLabel label;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ImageDrawingFromOneClassToAnother().createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());

        icon = new ImageIcon(this.getClass().getResource("king.png")); //Read images as if they were already embedded resources

        button = new JButton("Draw image");

        label = new JLabel(""); //Create an empty label

        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setIcon(icon); //On button click, we set the icon for the empty label
            }
        });

        pane = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 200); //Set a size for the main panel
            }
        };

        pane.setLayout(new GridLayout(1, 2)); //The main panel

        leftPane = new JPanel(); //The button panel
        leftPane.setLayout(new BoxLayout(leftPane, BoxLayout.PAGE_AXIS));

        leftPane.add(button);

        rightPane = new JPanel(); //The panel where the image will be drawn
        rightPane.add(label);

        //We add both (button and image) panels to the main panel
        pane.add(leftPane);
        pane.add(rightPane);

        frame.add(pane); //Add the main panel to the frame
        frame.pack(); //Calculate its preferred size
        frame.setVisible(true); //Set it to be visible
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
Run Code Online (Sandbox Code Playgroud)