如何在Java中更改帧大小

时间:2017-12-11 17:34:06

标签: java

我在NetBeans上写作,在我的代码中,图片在整个帧中延伸,因此稍微扭曲,如何获得图像大小来设置它的帧大小? 我试图将图像大小分配给框架,但我没有成功:( 我怎么能完成我的程序? 附:对不起,我的英语不好。 这是代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;

public class MyJPanel extends JPanel implements ActionListener {

    public static int i = 0;

    ArrayList<Image> images = new ArrayList<>();
    JButton button = new JButton("Next image"),
            button2 = new JButton("previous image");
    JFrame frame = new JFrame();
    JPanel panel = new JPanel(),
            panel2 = new JPanel();

    public static void main(String[] args) {
        MyJPanel gui = new MyJPanel();
        gui.go();
    }

    class Inner implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (i > 0) {
                if (i == 3) {
                    i = i - 3;
                } else {
                    --i;
                }
                button2.setText("previous image");
                frame.repaint();
            }
        }
    }

    public void go() {
        panel.setLayout(new FlowLayout());
        panel.setBackground(Color.darkGray);
        panel.add(button2);
        panel.add(button);

        button.addActionListener(this);
        button2.addActionListener(new Inner());
        frame.getContentPane().add(panel, BorderLayout.SOUTH);
        frame.getContentPane().add(this);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        File[] files = new File(Path).listFiles();
        for (File f : files) {
            System.out.println(f.canRead() + " " + f.renameTo(f));
            images.add(new ImageIcon(f.getAbsolutePath()).getImage());
        }
        if (i < images.size()) {
            g.drawImage(images.get(i), 0, 0, getWidth(), getHeight(), this);//here stretches the picture
        }
        System.out.print("hello world");
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (i < 3) {
            i = i + 3;
        } else {
            i++;
        }
        button.setText("Next image");
        this.repaint();
    }
}

0 个答案:

没有答案