Изображения не отображаются в приложении Java - PullRequest
0 голосов
/ 26 февраля 2011

Может кто-нибудь указать мне правильное направление?Я пытаюсь отобразить графические изображения в зависимости от того, какая кнопка нажата, но ничего не отображается.Я не получаю никаких ошибок, поэтому я предполагаю, что файлы изображений читаются правильно, и что проблема, скорее всего, связана с моим кодом Jpanel.

//import all needed functionality
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.*;
public class Calculator extends JApplet implements ActionListener{

private static final long serialVersionUID = 1L;

    // Declare variables and put code application logic here

    String userInput = null;
    JLabel loanAmountLabel = new JLabel("Loan Amount: ");
    JTextField loanAmount = new JTextField();
    double[] ratesList = {0.0535, 0.055, 0.0575};
    JLabel rateLabel=new JLabel("Interest Rate: ");
    JTextField rate=new JTextField();
    String[] yearsList = {"7","15","30"};
    JLabel yearsLabel=new JLabel("Years of Payment: ");
    JTextField years=new JTextField();
    JLabel chooseLabel=new JLabel("Choose a yearly term: ");
    JRadioButton sevenButton = new JRadioButton("7 years at 5.35%");
    JRadioButton fifteenButton = new JRadioButton("15 years at 5.5%");
    JRadioButton thirtyButton = new JRadioButton("30 years at 5.75%");
    JLabel pictureLabel=new JLabel("Graph:");
    JLabel picture;
    JLabel payLabel=new JLabel("Monthly Payment: ");
    JLabel payment=new JLabel();
    JButton calculate=new JButton("Calculate");
    JButton clear=new JButton("Clear");
    JButton quit=new JButton("Quit");
    JTextArea payments=new JTextArea();
    JScrollPane iterations=new JScrollPane(payments);
    Container mortCalc = getContentPane();


    public void init() {
//Configure the radio buttons to input data into fields
    sevenButton.setActionCommand("Radio1");
    fifteenButton.setActionCommand("Radio2");
    thirtyButton.setActionCommand("Radio3");

    ButtonGroup chooseYears = new ButtonGroup();
    chooseYears.add(sevenButton);
    chooseYears.add(fifteenButton);
    chooseYears.add(thirtyButton);

    //Register a listener for the radio buttons.
    sevenButton.addActionListener(this);
    fifteenButton.addActionListener(this);
    thirtyButton.addActionListener(this);

  //Set up the picture label.
    picture = new JLabel(createImageIcon("images/"
                                         + years.getText()
                                         + ".gif"));
    picture.setPreferredSize(new Dimension(356, 290));

     //Config GUI
    JPanel panelMort=new JPanel();
    panelMort.setLayout(new GridLayout(1,2));
    panelMort.add(loanAmountLabel);
    panelMort.add(loanAmount);  

    JPanel panelMort0=new JPanel();
    panelMort0.setLayout(new GridLayout(1,2));
    panelMort0.add(chooseLabel);
    panelMort0.add(sevenButton);
    panelMort0.add(fifteenButton);
    panelMort0.add(thirtyButton);

    JPanel panelMort1=new JPanel();
    panelMort1.setLayout(new GridLayout(3,2));
    panelMort1.add(yearsLabel);
    panelMort1.add(years);
    panelMort1.add(rateLabel);
    panelMort1.add(rate);
    panelMort1.add(payLabel);
    panelMort1.add(payment);

    JPanel panelMort3=new JPanel();
    panelMort3.setLayout(new GridLayout(1,2));
    panelMort3.add(pictureLabel);
    panelMort3.add(picture);

    JPanel buttons=new JPanel();
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
    buttons.add(calculate);
    buttons.add(clear);
    buttons.add(quit);

    JPanel panelMort2=new JPanel();
    panelMort2.setLayout(new BoxLayout(panelMort2, BoxLayout.Y_AXIS));
    panelMort2.add(panelMort);
    panelMort2.add(panelMort0);
    panelMort2.add(panelMort1);
    panelMort2.add(panelMort3);
    panelMort2.add(buttons);

    mortCalc.add(BorderLayout.NORTH, panelMort2);
    mortCalc.add(BorderLayout.CENTER, iterations);

    }

    private Icon createImageIcon(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    public void actionPerformed(ActionEvent e) {
        if ("Radio1".equals(e.getActionCommand())) {
            years.setText("7");
            rate.setText("0.0535");   
        }
        if ("Radio2".equals(e.getActionCommand())) {
            years.setText("15");
            rate.setText("0.055");   
        }
        if ("Radio3".equals(e.getActionCommand())) {
            years.setText("30");
            rate.setText("0.0575");   
        } 
        {
            picture.setIcon(createImageIcon("images/"
                    + e.getActionCommand()
                    + ".png"));
        }


    calculate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {    
                // Perform the calculation

                double principalCalc=Double.parseDouble(loanAmount.getText());
                double rateCalc=Double.parseDouble(rate.getText())/12;
                double yearsCalc=Integer.parseInt(years.getText())*12;

                double monthlyPayment=principalCalc*Math.pow(1+rateCalc,yearsCalc)*rateCalc/(Math.pow(1+rateCalc,yearsCalc)-1);

                DecimalFormat df = new DecimalFormat("$###,###.00");
                payment.setText(df.format(monthlyPayment));

                // Perform extra calculations to show the loan amount after each subsequent payoff
                double principal=principalCalc;
                int month;
                StringBuffer buffer=new StringBuffer();
                buffer.append("Month\tAmount\tInterest\tBalance\n");
                for (int f=0; f<yearsCalc; f++) {
                month=f+1;
                double interest=principal*rateCalc;
                double balance=principal+interest-monthlyPayment;                   
                buffer.append(month+"\t"); buffer.append(new String(df.format(principal))+"\t");
                buffer.append(new String(df.format(interest))+"\t");buffer.append(new String(df.format(balance))+"\n");
                principal=balance;
                }
                payments.setText(buffer.toString());
                } catch(Exception ex) {
                System.out.println(ex);
            }
        }
    });
    clear.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loanAmount.setText(""); payment.setText(""); payments.setText("");
        }
    });
    quit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(1);
        }
    });     



    }
public static void main(String[] args) {
    JApplet applet = new Calculator();
    JFrame frameMort = new JFrame("Calculator");
    frameMort.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frameMort.getContentPane().add(applet);
    frameMort.setSize(550,800);

    frameMort.setResizable(true);
    frameMort.setVisible(true);

    applet.init();
    applet.start();

}
}

1 Ответ

3 голосов
/ 26 февраля 2011

Это должен быть большой намек ..

private Icon createImageIcon(String string) {
    // TODO Auto-generated method stub
    return null;
}

OTOH, учитывая, что это апплет, вы должны избегать любых основанных на String конструкторов для изображений. Вместо этого используйте URL, получите URL от ..

URL urlToImageOnClassPath = this.getClass().getResource("path/to/image.png");

Редактировать 1: Метод getResource () будет работать, если изображение находится в пути класса времени выполнения апплета. То есть он находится в Jar апплета или в одном из других Jar, перечисленных в атрибуте архива манифеста или апплета.

Если это не так, и вместо этого изображение является свободным ресурсом на сервере, другие способы формирования URL-адресов могут быть найдены из относительного URL-адреса или из базы кодов или из базы документов. Е.Г.

URL urlToImageOnServer = new URL(applet.getDocumentBase(), "../files/image.png");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...