Swing - przekazywanie stringów

0

Witam wszystkich,

Mój problem jest zapewne dosyć trywialny, ale jestem początkującym dlatego proszę o wyrozumiałość. Jednocześnie z góry dziękuję za każdą sugestię i uwagę.

Mam dwie klasy, pierwsza GUI.java zawiera interfejs graficzny, ot zwykły JFrame z jednym Panelem i dwoma buttonami. Drugą pobrałem ze strony oracle'a (http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html) - to ta o nazwie CustomComboBox.java. Klasa ta, wyświetla zdjęcia zwierzątek. Dodałem ją na JPanel i wszystko działa poprawnie. Wygląda tak:

user image

Problem w tym, że chciałbym za pomocą buttonów zmieniać ścieżkę dostępu do tych obrazków. W klasie CustomComboBox tworzę scieżkę tak:

String path = "images/";
(...)
images[i] = createImageIcon(path + petStrings[i] + ".gif");

I właśnie w klasie GUI, w metodach obsługujących buttony chciałbym zmieniać wartość tego stringa path. Jak to poprawnie zrobić? Poniżej zamieszczam kod źródłowy dla obydwu klas.

pozdrawiam,
Remi

CustomComboBox.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class CustomComboBoxDemo extends JPanel {
    ImageIcon[] images;
    String[] petStrings = {"1", "2", "3"};
    String path = "images/";


    public CustomComboBoxDemo() {
        super(new BorderLayout());

        //Load the pet images and create an array of indexes.
        images = new ImageIcon[petStrings.length];
        Integer[] intArray = new Integer[petStrings.length];
        for (int i = 0; i < petStrings.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = createImageIcon(path + petStrings[i] + ".gif");
            if (images[i] != null) {
                images[i].setDescription(petStrings[i]);
            }
        }

        //Create the combo box.
        JComboBox FacePartList = new JComboBox(intArray);
        ComboBoxRenderer renderer= new ComboBoxRenderer();
        renderer.setPreferredSize(new Dimension(250, 250));
        FacePartList.setRenderer(renderer);
        FacePartList.setMaximumRowCount(3);
     
        

        //Lay out the demo.
        add(FacePartList, BorderLayout.PAGE_START);
        setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = CustomComboBoxDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
                return null;
        }
    }




class ComboBoxRenderer extends JLabel
                           implements ListCellRenderer {
        private Font uhOhFont;

        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
        }

        /*
         * This method finds the image and text corresponding
         * to the selected value and returns the label, set up
         * to display the text and image.
         */
        public Component getListCellRendererComponent(
                                           JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
            //Get the selected index. (The index param isn't
            //always valid, so just use the value.)
            int selectedIndex = ((Integer)value).intValue();

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }

            //Set the icon and text.  If icon was null, say so.
            ImageIcon icon = images[selectedIndex];
            String pet = petStrings[selectedIndex];
            setIcon(icon);
            if (icon != null) {
                setText(pet);
                setFont(list.getFont());
            } else {
                setUhOhText(pet + " (no image available)",
                            list.getFont());
            }

            return this;
        }

        //Set the font and text when no image was found.
        protected void setUhOhText(String uhOhText, Font normalFont) {
            if (uhOhFont == null) { //lazily create this font
                uhOhFont = normalFont.deriveFont(Font.ITALIC);
            }
            setFont(uhOhFont);
            setText(uhOhText);
        }
    }
}

GUI.java

import javax.swing.ComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class GUI extends JFrame {

	 
	/** Constructor */
	public GUI() {
		initComponents();
	}


	private void initComponents() {

		jPanel1 = new javax.swing.JPanel();
		jButton1 = new javax.swing.JButton();
		jButton2 = new javax.swing.JButton();

		setDefaultCloseOperation(3);
		
		
		// combobox layout
		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 266,
				Short.MAX_VALUE).addComponent(combobox));
		jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 274,
				Short.MAX_VALUE).addComponent(combobox));
		// end combobox layout
		

		jButton1.setText("jButton1");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		jButton2.setText("jButton2");
		jButton2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton2ActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						javax.swing.GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
							.addContainerGap()
							.addComponent(jPanel1,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,										javax.swing.GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,49, Short.MAX_VALUE)
							.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
												.addComponent(jButton1)
												.addComponent(jButton2))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGap(67, 67, 67)
								.addComponent(jButton1)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
										94, Short.MAX_VALUE)
								.addComponent(jButton2).addGap(89, 89, 89))
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jPanel1,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE).addContainerGap()));

		pack();
	}// end:initComponents

	private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	//main
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new GUI().setVisible(true);
			}
		});
	}


	// Variables declaration
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton2;
	private javax.swing.JPanel jPanel1;
	// End of variables

}
1
      private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
                // TODO add your handling code here:
        }
 
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
                // TODO add your handling code here:
        }

W tym miejscu musisz zaprogramować obsługę przycisków. Jeżeli chodzi o wybór ścieżki to poszukaj informacji o JFileChooser.

1 użytkowników online, w tym zalogowanych: 0, gości: 1