Sizing a jlist within a jpanel

Hi,
I'm writing a jpanel tjhat contains a jlist object at its center. Now, when I place the jpanel within a JFrame the panel grows to eat all the available space (I can see this thanks to the border of the panel), while the JList remains at a very small size regarding the jpanel. I'd like to have the jlist to resize itself to occupy all the
jpanel size. The following is the code that shows it. Any idea about how to achieve this?
Thanks,
Luca
public class ListPanel extends JPanel{
    protected JList myList;
public AgletListPanel(){
        super();
        this.setLayout(new FlowLayout(FlowLayout.CENTER));
        this.listModel = new DefaultListModel();
        this.myList = new JList(this.listModel);
        this.myList.setBackground(Color.WHITE);
        this.myist.setForeground(Color.BLUE);
        this.myList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        this.myList.setPreferredSize(getPreferredSize());
        this.add(new JScrollPane(this.myList));
        TitledBorder border = new TitledBorder("List"));
        border.setTitleColor(Color.BLUE);
        border.setTitleJustification(TitledBorder.CENTER);
        this.setBorder(border);
        this.setVisible(true);
    }

Thanks, using the borderlayout the panel now shows fine to me. However I removed the setPreferredSize line in order not ot have the jlist to use scrollbars even if empty.
By the way, can you explain why the FlowLayout did not work and the border layout did it?
Thanks.

Similar Messages

  • Can a JList display a JPanel with JButtons, JTextField, etc....  ?

    I've created a JPanel widget component that I hope could display on a line in a JList. The widget contains a JTextField, a JButton, a JCheckBox, etc...
    I'd like to insert these JPanel widgets into a JList, and have the JList box render them.
    The Widget does implement ListCellRenderer
    public class VOWidget2 extends javax.swing.JPanel implements ListCellRendereras the following
        public Component getListCellRendererComponent(JList list,
                                Object value, int index,
                                boolean isSelected, boolean cellHasFocus)
            return (JPanel)this;
        }I also set it in the JList as a DefaultListModel
    DefaultListModel model = new DefaultListModel();
    for(VideoOut curr: voList){
         VOWidget2 vow = new VOWidget2(curr,isHost);
         model.addElement(vow);
    jListVideoOutWidgets.setModel(model);I had hoped to see the JPanel rendered properly inside the JList, but instead it does a toString() on the Object and displays the text from that.
    Here is my question. Can you display a JPanel based widget inside a JList? Or should I just use a JTable instead.
    All the examples I find on the Internet only show example of JList rendering a JLable with an icon and text. Why? Why would the ListCellRenderer return a Component if the most complex thing it could display was a JLabel?

    Can you display a JPanel based widget inside a JList?Yes.
    but instead it does a toString() Implementing ListCellRenderer on your widget panel does not make it the renderer for the JList. You need to create a custom renderer that simply returns the "value" from the getListCellRendererComponent(...) method. Then you need to set this as the renderer for the JList.
    But as everyone else has mentioned you won't be able to edit any of the component or interact with them in any way. Attempting to do so would basically mean duplicating the code thats already available in JTable, which is why everybody is suggesting you just use a JTable.

  • How to resize a JPanel within another JPanel

    I have a JApplet that contains contains a JPanel which has several other components on the JPanel.
    The JApplet is an image query front-end which can be used to find images based on a single geographic point, a geographic rectangle or a geographic point and a radius (in meters). I have a JComboBox that the user uses to select which type of query they would like to perform. To enter the query information, I have a separate JPanel that contains the query parameters.
    For the single geographic point, it is just a simple row with JLabels and JTextFields for the latitude and longitude.
    For the rectangle, it is essentially a 3x3 grid to handle the JLabels and JTextFileds for the latitude and longitude of the upper left and lower right corners.
    For the geographic point and radius, I reuse the JPanel for the single geographic point and add a new row for the radius.
    In my ChangeListener for the JComboBox, I first call parentPanel.remove (queryPanel) then call a method to create the specific queryPanel and call parentPanel.add (queryPanel). The only thing that happens when I change the JComboBox to a different query type is the portion of the queryPanel that was covered by the selection of the JComboBox never gets repainted and doesn't change to the new queryPanel.
    I wish I could provide code examples, but the computer that I am developing on is not on the Internet and it is extremely difficult to get anything off of it to put out on the Internet.
    Hopefully, someone can help me figure out what is going on and why my parentPanel is not updating to reflect the new queryPanel.

    GoDonkeys wrote:
    Sorry, but what is the EDT?Please start here: [Concurrency in Swing|http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html]

  • Defining the origin within a JPanel

    Hi there, probably (hopefully) a simple problem, but here we go: I'm trying to create a JPanel that I can draw dots (or whatever) on at certain co-ordinates. In particular I'd like to be able to read positive and negative x and y co-ordinates and accurately represent them, so the origin of the axis should be in the middle of the JPanel. Any thoughts?
    At the moment I have made a JPanel that displays positive X and Y co-ordinates, with the Y co-ord inverted (i.e. how it comes out the box!).
    Cheers.
    Edited by: R.B. on May 4, 2008 11:49 AM

    take a look a Graphics2D
    in particular
    scale
    translate
    if you translate to the center of your panel, and then scale by (1,-1) (inverts the y axis) you should have it

  • Animating a textarea within a JPanel

    Hi,
    I have a JPanel with 5 textareas. I am using the text areas as cards. I.e they have a colour and a number in centre. I want to be able to do some animations as follows:
    When I click on one of the text areas. It would just move around and then disaapear. The other text areas would just move along.
    I am having a problem doing this because JPanels have default managers. Also, when I try to get the graphics context and draw on JPanel. The image I drew flashes then dissappears.
    Would appreciate your help.
    Thanks!

    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.Random;
    public class Test extends JFrame implements Runnable {
      JTextArea[] jtas = new JTextArea[5];
      boolean running = false;
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.setLayout(null);
        Random r = new Random();
        for (int i=0; i<jtas.length; i++) {
          jtas[i] = new JTextArea("Some Text - "+i);
          jtas.setBounds(r.nextInt(300), r.nextInt(250),100,100);
    content.add(jtas[i]);
    JButton jb = new JButton("Jiggle");
    jb.setBounds(100,350,100,20);
    content.add(jb);
    jb.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) { jiggle(); }
    setSize(400, 400);
    show();
    private void jiggle() { new Thread(this).start(); }
    public void run() {
    if (running) return;
    running = true;
    Point[] locs = new Point[jtas.length];
    for (int i=0; i<jtas.length; i++) locs[i]=jtas[i].getLocation();
    for (int i=0; i<20; i++) {
    for (int j=0; j<jtas.length; j++) jtas[j].setLocation(locs[j].x+5, locs[j].y+5);
    validate();
    try { Thread.sleep(50); } catch (Exception exc) {}
    for (int j=0; j<jtas.length; j++) jtas[j].setLocation(locs[j].x-5, locs[j].y-5);
    validate();
    try { Thread.sleep(50); } catch (Exception exc) {}
    for (int j=0; j<jtas.length; j++) jtas[j].setLocation(locs[j].x, locs[j].y);
    validate();
    try { Thread.sleep(50); } catch (Exception exc) {}
    running=false;
    public static void main(String args[]) {
    new Test();

  • Dragging JtextArea and images within Jpanel

    I have JPanel containing multiple JTextAreas and Images.
    What I want to do is that :
    user should be able to drag the textarea or image and reposition it anywhere within the JPanel.
    Thank you in advance.
    /Amol

    Here is a quick demo. program:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JFrame implements ActionListener {
    JTextArea ta = new JTextArea(20,20);
    JButton b = new JButton("Click");
    public Test() {
    super("Test");
    b.addActionListener(this);
    ta.addKeyListener(new MyKeyListener());
    getContentPane().add(ta, BorderLayout.CENTER);
    getContentPane().add(b, BorderLayout.SOUTH);
    pack();
    setVisible(true);
    public void actionPerformed(ActionEvent e) {
    System.out.println("Click on Button!");
    class MyKeyListener extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
    b.doClick();
    e.consume();
    public static void main(String[] args) {
    new Test();
    Note: if you want the 'enter' key also make the textarea
    has return line ==> comment out the e.consume().
    In that way, textarea return line And button click too.

  • JList selections automatically deselect on mouseout

    Hi,
    I'm having a problem with a JList that's contained within a JPanel that's contained within a JTable cell. The problem is that whenever I select a row in the JList and then leave the JList (to some other portion of the JPanel) the selection gets deselected. That way I can never click on a button that resides on the JPanel that should call an action using the selected item from the JList. Has anyone experienced this?

    If im getting your problem right theres a simple solution. Your list in the table cell is a TableCellEditor right? but when your done editing the value it switchs back to the TableCellRenderer. So if your renderer is another list its normal that this list has no item selected
    My advice, either take the same list as your renderer and editor or code your renderer to check the new selected value and to update his list.
    Hope it helps.

  • Using a JPanel as cell editor in JTable

    I have a composite component (JPanel that contains a JTextField and a
    JButton) that I would like to use as the a cell editor in a JTable.The JButton instantiates a UI editor component that I have designed. Example would be date editor for dates, tet editor for strings etc. This editor allows the user to select a date to populate the JTextField (the date may also be manually entered).
    I have no problem with the rendering of the component within the table.However, I would like for the JTextField embedded within the JPanel to receive focus and a visible caret, when using the tab key to navigate to the cell. After reading through some of the posts here , I was able to transfer the focus. But I dont see a visible caret. I am unable to edit. I have to click on the text box and then start typing. Its a great pain in the ass.
    I have a custom designed table and custom designed editor. Code is attached...
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))) {     
    if (selCol == 1) {
    isSelected= getCellEditor(selRow,selCol).stopCellEditing();
    targetRow = (selRow + 1) % rowCount;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    if (editCellAt(targetRow, 1, obj)) {
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    } else {
    getCellEditor(selRow, selCol).shouldSelectCell(obj);
    return super.processKeyBinding(ks,e,condition,pressed);
    </pre>
    Relevant code of my custom editor is below....
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    lastEditedRow = row;
    lastEditedCol = column;
    lastEditedTable = table;
    lastEditedValue = value;
    val = value;
    ((JTextField)editorComponent).
    setText(val == null ? "" : val.toString());
    setClickCountToStart(1);
    if (value instanceof CycCollectionChooserModel) {
    String collection = ((CycCollectionChooserModel)value).
    getCollection().cyclify();
    button.setVisible(EditorForCollectionMap.hasUIEditor(collection));
    button.setMargin (new Insets (1,1,1,1));
    button.setIconTextGap(0);
    buttonListener.model = (CycCollectionChooserModel)value;
    buttonListener.rowIndex = row;
    buttonListener.localTable = table;
    return panel;
    public boolean isCellEditable(EventObject evt) {
    if (evt instanceof MouseEvent) {
    int clickCount;
    clickCount = 1;
    return ((MouseEvent)evt).getClickCount() >= clickCount;
    return super.isCellEditable(evt);
    public boolean stopCellEditing() {   
    if (super.stopCellEditing()) {
    final int targetRow = (lastEditedRow+1)%lastEditedTable.getRowCount();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    lastEditedTable.changeSelection(targetRow, 1, false, false);
    lastEditedTable.getComponentAt(targetRow, 1).requestFocus();
    return true;
    return false;
    Does any one know why I am not able to see the caret? Any insights you have will be most welcome.
    Thanks in advance,
    Praveen.

    Almost solved the problem. Navigation through Tab key, up/ down arrow, Enter key works for text boxes. Navigation through Tab Key, Up/down arrow works for combo boxes. But for "Enter" key it doesnt. Changes in code ....
    (I have added a key listener to my editor class)
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0))) {     
    if (selCol == 1) {
    final int targetRow = (selRow + 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_UP,0))||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1))) {
    if (selCol == 1) {
    final int targetRow = (selRow - 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    return super.processKeyBinding(ks,e,condition,pressed);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    </pre>
    P.S : viravan, help me solve this problem and you will get the rest of the dukes LOL

  • JTable text alignment issues when using JPanel as custom TableCellRenderer

    Hi there,
    I'm having some difficulty with text alignment/border issues when using a custom TableCellRenderer. I'm using a JPanel with GroupLayout (although I've also tried others like FlowLayout), and I can't seem to get label text within the JPanel to align properly with the other cells in the table. The text inside my 'panel' cell is shifted downward. If I use the code from the DefaultTableCellRenderer to set the border when the cell receives focus, the problem gets worse as the text shifts when the new border is applied to the panel upon cell selection. Here's an SSCCE to demonstrate:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.EventQueue;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.border.Border;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import sun.swing.DefaultLookup;
    public class TableCellPanelTest extends JFrame {
      private class PanelRenderer extends JPanel implements TableCellRenderer {
        private JLabel label = new JLabel();
        public PanelRenderer() {
          GroupLayout layout = new GroupLayout(this);
          layout.setHorizontalGroup(layout.createParallelGroup().addComponent(label));
          layout.setVerticalGroup(layout.createParallelGroup().addComponent(label));
          setLayout(layout);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
          if (isSelected) {
            setBackground(table.getSelectionBackground());
          } else {
            setBackground(table.getBackground());
          // Border section taken from DefaultTableCellRenderer
          if (hasFocus) {
            Border border = null;
            if (isSelected) {
              border = DefaultLookup.getBorder(this, ui, "Table.focusSelectedCellHighlightBorder");
            if (border == null) {
              border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
            setBorder(border);
            if (!isSelected && table.isCellEditable(row, column)) {
              Color col;
              col = DefaultLookup.getColor(this, ui, "Table.focusCellForeground");
              if (col != null) {
                super.setForeground(col);
              col = DefaultLookup.getColor(this, ui, "Table.focusCellBackground");
              if (col != null) {
                super.setBackground(col);
          } else {
            setBorder(null /*getNoFocusBorder()*/);
          // Set up our label
          label.setText(value.toString());
          label.setFont(table.getFont());
          return this;
      public TableCellPanelTest() {
        JTable table = new JTable(new Integer[][]{{1, 2, 3}, {4, 5, 6}}, new String[]{"A", "B", "C"});
        // set up a custom renderer on the first column
        TableColumn firstColumn = table.getColumnModel().getColumn(0);
        firstColumn.setCellRenderer(new PanelRenderer());
        getContentPane().add(table);
        pack();
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TableCellPanelTest().setVisible(true);
    }There are basically two problems:
    1) When first run, the text in the custom renderer column is shifted downward slightly.
    2) Once a cell in the column is selected, it shifts down even farther.
    I'd really appreciate any help in figuring out what's up!
    Thanks!

    1) LayoutManagers need to take the border into account so the label is placed at (1,1) while labels just start at (0,0) of the cell rect. Also the layout manager tend not to shrink component below their minimum size. Setting the labels minimum size to (0,0) seems to get the same effect in your example. Doing the same for maximum size helps if you set the row height for the JTable larger. Easier might be to use BorderLayout which ignores min/max for center (and min/max height for west/east, etc).
    2) DefaultTableCellRenderer uses a 1px border if the UI no focus border is null, you don't.
    3) Include a setDefaultCloseOperation is a SSCCE please. I think I've got a hunderd test programs running now :P.

  • JTabbedPane lose JList contents

    Hi , this is my first question in the forum :D, i have a problem with a JTabbedPane with two tabs, each with a JList in a JPanel, the problem is that i populate the Jlists in a dynamic way using a vector. the Jlist in the first index (tab) is populated first and then I select the second tab and populate the second Jlist, but when I return to the first tab the Jlist is empty, i guess because it is repainted, which method or what i need to do to keep my JList populated !!

    In the future Swing related questions should be posted in the Swing forum.
    Without seeing your code we can only guess!
    Swing components can't be shared.
    You need to create two JLists, one for each tab.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Problem displaying image in jpanel

    Hi,I have posted this on the applet board, but I think its also a general programming problem, so apologies if it isn't relevant to this board, just say so and I'll remove it!
    I've got an applet that receives a variable from a PHP page as a parameter. The variable is "map1.png" the map this variable refers to sits in the same folder as the applet.
    I want to use this variable along with getDocumentBase() to create a URL which will then be used to display an image within a jPanel called mapPane.
    the code I currently have is:
    // get image url
    String mapURL = getParameter("mapURL");
    //set variable for image
    Image map_png;
    // set media tracker
    MediaTracker mt;
    //initialise media tracker     
    mt = new MediaTracker(this);
    map_png = getImage(getDocumentBase(),mapURL);
    // tell the MediaTracker to kep an eye on this image, and give it ID 1;
    mt.addImage(map_png,1);
    // now tell the mediaTracker to stop the applet execution
    // until the images are fully loaded.
    try
    mt.waitForAll();
    catch (InterruptedException e) {}
    // draw image onto mapPane
    mapPane.getGraphics().drawImage(map_png, 200, 200, null);
    Currently the Parameter is being passed into the applet (i've written it out within the applet) but the image is not being displayed. Does anyone have any suggestions about what I'm doing wrong?
    Cheers
    Steve

    hi,
    No, don't get any exceptions, the Java Console has a message:
    <terminated>JavaImageEditor[Java Applet]C:\Program Files\Java\jre1.6.0\bin\javaw.exe
    Cheers
    Steve

  • Adding files from JFileChooser to Jlists

    i have created a JList i am wondering how i can add files to this Jlist using a JFile chooser.
    i need to add the actual file with the path and everything i also need to add the contents of a directory into the jList if selected in the Filechooser.
    i have no problem creating a JFilechooser dialog.
    please help me out.

    Hi,
    I gave an example how to use the filechosser and filefilter [url http://forum.java.sun.com/thread.jsp?forum=57&thread=435432]here.
    I think its also where you got the source code above.
    Compactly and performable:import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileFilter;
    class Player2 extends JFrame
         public static final int DELAY = 10;
         JButton playButton;
         private JButton Shuffle;
         private JButton stopButton;
         Timer playTimer;
         private JLabel aMessage;
         private JButton openButton;
         JList playList = null;
         JPanel aPanel;
         JFileChooser theFileChooser = new JFileChooser();
         AudioFileFilter filter = new AudioFileFilter();
         JFrame win = new JFrame("AudioPlayer");
         class playTimerListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   //myPlayer.play();
         class OpenFileChooserAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   int retVal = theFileChooser.showOpenDialog(aPanel);
                   if (retVal == JFileChooser.APPROVE_OPTION)
                        File[] files = theFileChooser.getSelectedFiles();
                        DefaultListModel model = (DefaultListModel) playList.getModel();
                        model.clear();
                        for (int i = 0; i < files.length; i++)
                             if (files.isDirectory())
                                  String[] filesInDirectory = files[i].list();
                                  for (int ii = 0; ii < filesInDirectory.length; ii++)
                                       File f = new File(files[i].getPath() + "/" + filesInDirectory[ii]);
                                       //to prevent subdirectories to be added to the list
                                       if (f.isFile() && filter.accept(f))
                                            model.addElement(filesInDirectory[ii]);
                             else
                                  if (filter.accept(files[i]))
                                       model.addElement(files[i]);
         class playButtonActionListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   System.out.println("Playing...");
                   playTimer.start();
         class stopButtonActionListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   System.out.println("Stopped!");
                   playTimer.stop();
         public Player2(String s)
              super(s);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              playTimer = new Timer(DELAY, new playTimerListener());
              theFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              theFileChooser.setMultiSelectionEnabled(true);
              theFileChooser.setFileFilter(filter);
              theFileChooser.setFileHidingEnabled(false);
              makeMyGUI();
              pack();
              show();
         private void makeMyGUI()
              aMessage = new JLabel("Nothing selected yet", JLabel.CENTER);
              JScrollPane listScroll = new JScrollPane(playList = new JList(new DefaultListModel()));
              listScroll.setPreferredSize(new Dimension(200, 200));
              playList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              playButton = new JButton(new playButtonActionListener());
              playButton.setText("play...");
              stopButton = new JButton(new stopButtonActionListener());
              stopButton.setText("stop...");
              openButton = new JButton(new OpenFileChooserAction());
              openButton.setText("Open...");
              openButton.setBackground(Color.yellow);
              Shuffle = new JButton("Shuffle");
              aPanel = new JPanel();
              aPanel.setBackground(Color.blue);
              aPanel.add(openButton);
              aPanel.add(playButton);
              aPanel.add(stopButton);
              getContentPane().add(listScroll, "Center");
              getContentPane().add(aPanel, "North");
              getContentPane().add(aMessage, "South");
         class AudioFileFilter extends FileFilter
              public boolean accept(File f)
                   if (f.isDirectory())
                        return true;
                   String extension = Utils.getExtension(f);
                   if (extension != null)
                        if (extension.equals(Utils.wav)
                             || extension.equals(Utils.aif)
                             || extension.equals(Utils.rmf)
                             || extension.equals(Utils.au)
                             || extension.equals(Utils.mid))
                             return true;
                        else
                             return false;
                   return false;
              public String getDescription()
                   return "wav, aif, rmf, au and mid";
         public static void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e)
                   e.printStackTrace();
              new Player2("MP3 PLAYER");
    class Utils
         public final static String wav = "wav";
         public final static String aif = "aif";
         public final static String rmf = "rmf";
         public final static String au = "au";
         public final static String mid = "mid";
         * Get the extension of a file.
         public static String getExtension(File f)
              String ext = null;
              String s = f.getName();
              int i = s.lastIndexOf('.');
              if (i > 0 && i < s.length() - 1)
                   ext = s.substring(i + 1).toLowerCase();
              return ext;
    //without formatting
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileFilter;
    class Player2 extends JFrame
         public static final int DELAY = 10;
         JButton playButton;
         private JButton Shuffle;
         private JButton stopButton;
         Timer playTimer;
         private JLabel aMessage;
         private JButton openButton;
         JList playList = null;
         JPanel aPanel;
         JFileChooser theFileChooser = new JFileChooser();
         AudioFileFilter filter = new AudioFileFilter();
         JFrame win = new JFrame("AudioPlayer");
         class playTimerListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   //myPlayer.play();
         class OpenFileChooserAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   int retVal = theFileChooser.showOpenDialog(aPanel);
                   if (retVal == JFileChooser.APPROVE_OPTION)
                        File[] files = theFileChooser.getSelectedFiles();
                        DefaultListModel model = (DefaultListModel) playList.getModel();
                        model.clear();
                        for (int i = 0; i < files.length; i++)
                             if (files[i].isDirectory())
                                  String[] filesInDirectory = files[i].list();
                                  for (int ii = 0; ii < filesInDirectory.length; ii++)
                                       File f = new File(files[i].getPath() + "/" + filesInDirectory[ii]);
                                       //to prevent subdirectories to be added to the list
                                       if (f.isFile() && filter.accept(f))
                                            model.addElement(filesInDirectory[ii]);
                             else
                                  if (filter.accept(files[i]))
                                       model.addElement(files[i]);
         class playButtonActionListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   System.out.println("Playing...");
                   playTimer.start();
         class stopButtonActionListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   System.out.println("Stopped!");
                   playTimer.stop();
         public Player2(String s)
              super(s);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              playTimer = new Timer(DELAY, new playTimerListener());
              theFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              theFileChooser.setMultiSelectionEnabled(true);
              theFileChooser.setFileFilter(filter);
              theFileChooser.setFileHidingEnabled(false);
              makeMyGUI();
              pack();
              show();
         private void makeMyGUI()
              aMessage = new JLabel("Nothing selected yet", JLabel.CENTER);
              JScrollPane listScroll = new JScrollPane(playList = new JList(new DefaultListModel()));
              listScroll.setPreferredSize(new Dimension(200, 200));
              playList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              playButton = new JButton(new playButtonActionListener());
              playButton.setText("play...");
              stopButton = new JButton(new stopButtonActionListener());
              stopButton.setText("stop...");
              openButton = new JButton(new OpenFileChooserAction());
              openButton.setText("Open...");
              openButton.setBackground(Color.yellow);
              Shuffle = new JButton("Shuffle");
              aPanel = new JPanel();
              aPanel.setBackground(Color.blue);
              aPanel.add(openButton);
              aPanel.add(playButton);
              aPanel.add(stopButton);
              getContentPane().add(listScroll, "Center");
              getContentPane().add(aPanel, "North");
              getContentPane().add(aMessage, "South");
         class AudioFileFilter extends FileFilter
              public boolean accept(File f)
                   if (f.isDirectory())
                        return true;
                   String extension = Utils.getExtension(f);
                   if (extension != null)
                        if (extension.equals(Utils.wav)
                             || extension.equals(Utils.aif)
                             || extension.equals(Utils.rmf)
                             || extension.equals(Utils.au)
                             || extension.equals(Utils.mid))
                             return true;
                        else
                             return false;
                   return false;
              public String getDescription()
                   return "wav, aif, rmf, au and mid";
         public static void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e)
                   e.printStackTrace();
              new Player2("MP3 PLAYER");
    class Utils
         public final static String wav = "wav";
         public final static String aif = "aif";
         public final static String rmf = "rmf";
         public final static String au = "au";
         public final static String mid = "mid";
         * Get the extension of a file.
         public static String getExtension(File f)
              String ext = null;
              String s = f.getName();
              int i = s.lastIndexOf('.');
              if (i > 0 && i < s.length() - 1)
                   ext = s.substring(i + 1).toLowerCase();
              return ext;
    //Tim

  • Problems to show a Vertical JScrollPane with JList

    I have a JList within a JScrollPane, and update the JList with the output from a process.
    This means that the JList is updated very quickly with a lot of data.
    The scrollpane policy is set using this :
    myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    The problem happens as the list is being updated - sometimes the slider on the scrollbar disappears. It can reappear again, but this behaviour seems completely random.
    This means that if the process completes and the JList stops being updated, the lack of a slider prevents me from reviewing the JList contents.
    Does anyone know why this happens and what I can do to prevent it?

    JList displays the contents of a Vector. The Java version is JDK 1.2.2. And I'm using Windows 2000.

  • Selective Zoom of A JPanel

    I have an JPanel to which I am drawing an image. It is appearing rather small so I would like
    the user to have control over the image, so a mouse click in a specific location would zoom in on
    that region of the image, and a release would revert the image to it's actual size.
    //Within the JPanel's paintComponent
              if(isZoomed)
                   Graphics2D g2 = (Graphics2D) g;
    //possible translation? here
                   g2.scale(2.0, 2.0);
    //or here?
                   g2.drawImage(Image, 0, 0, getWidth(), getHeight(), this);
    //or here?
    My MouseListeners just relate (evt being the mouseEvent):
              x = evt.getX();
              y = evt.getY();
              isZoomed = !isZoomed;
    In it's current form it just scales the image - as result all I see is the top left corner of the image scaled. As stated
    I would like to make it a more selective and localized zoom, which seems reasonable and fairly easy to implement but confusing to me.
    Thanks!

    See those 0, 0 in the drawImage method call? Calculate negative values to set those two such that the zoomed portion is displayed instead.

  • Problems displaying image in JPanel

    Hi, I've got an applet that receives a variable from a PHP page as a parameter. The variable is "map1.png" the map this variable refers to sits in the same folder as the applet.
    I want to use this variable along with getDocumentBase() to create a URL which will then be used to display an image within a jPanel called mapPane.
    the code I currently have is:
    // get image url
            String mapURL = getParameter("mapURL");
            //set variable for image
            Image map_png;
            // set media tracker
            MediaTracker mt;
            //initialise media tracker             
            mt = new MediaTracker(this);
            map_png = getImage(getDocumentBase(),mapURL);
            // tell the MediaTracker to kep an eye on this image, and give it ID 1;
            mt.addImage(map_png,1);
            // now tell the mediaTracker to stop the applet execution
            //  until the images are fully loaded.
            try
                 mt.waitForAll();
            catch (InterruptedException  e) {}
            // draw image onto mapPane
            mapPane.getGraphics().drawImage(map_png, 200, 200, null);Currently the Parameter is being passed into the applet (i've written it out within the applet) but the image is not being displayed. Does anyone have any suggestions about what I'm doing wrong?
    Cheers
    Steve

    Hello,
    after an update of the graphics card driver to the newest just released version the problem has vanished.
    Regards

Maybe you are looking for