JFrame和ActionListener;等待用户输入

时间:2015-04-16 11:01:34

标签: java swing jframe actionlistener

我正在用Java扩展图像编辑应用程序。我想创建一个可以调整图像对比度的课程。主类调用apply方法并传递必须修改的图像。我设法创建了JFrame和算法用于计算,但是我遇到了Action Listener的问题,因为我不知道如何使我的apply方法等待用户输入,然后才计算和编辑图像。以下是对比类的代码:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

lic class ContrastFilter extends Filter implements ActionListener {

private JFrame contFr;
private JButton ok;
private JTextField textF;
private String s;
private int contV;
private int factor;


public ContrastFilter(String name){
    super(name);

}

public void makeFrame(){
    contFr = new JFrame("contrast window");
    Container contentPane = contFr.getContentPane();
    contentPane.setLayout(new FlowLayout());
    JLabel label = new JLabel("Enter contrast");
    contentPane.add(label, BorderLayout.PAGE_START);
    textF = new JTextField(5);
    contentPane.add(textF, BorderLayout.PAGE_START);
    ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event)
        {
            if (event.getSource() == ok){
                s = textF.getText();
                contV = Integer.parseInt(s);
                factor = Math.round((259*(contV+255))/(255*(259 - contV)));


        }}
    });      
    contentPane.add(ok, BorderLayout.PAGE_START);
    contFr.pack();
    contFr.setVisible(true);
}


public void apply(OFImage image) {
    makeFrame();


    int height = image.getHeight();
    int width = image.getWidth();

    for(int y = 0; y < height; y++) {
        for(int x = 0; x < width; x++) {
            Color pix = image.getPixel(x, y);
            image.setPixel(x, y, new Color(trunC(factor*(pix.getRed()-128)+128),
                                           trunC(factor*(pix.getGreen()-128)+128),
                                           trunC(factor*(pix.getBlue()-128)+128)));
        } } }




public int trunC(int a){
    if (a>255){
        return 255;
    }

    return a;
}

}

1 个答案:

答案 0 :(得分:0)

如果您希望apply()方法在按钮后工作,那么#34; OK&#34;单击(用户输入内容,然后单击确定),然后您需要将apply()调用放入ActionListener的actionPerformed()方法体。