43764

How do I resize a JScrollPane within a JFrame? And how do I read from a file in Java?

Question:

I have a song library, and I would like this selection list to only be on the left hand side of the window because I want to put other information about the song on the righthand side. I'm not sure how to change the size of JScrollPane, which is inside the JFrame.

In this library, I want to be able to import the songs stored in a file to my song library. Right now, I have an array within my code, but I want to be able to read from a text file instead of using this approach. In the file, I want to be able to store artist and album information about the song, but I don't want it to display in the song list.

String songs[] = {"Song1", "Song2", "Song3", "Song4", "Song5"}; JList list = new JList(songs); public SongLib(){ JFrame songLibrary = new JFrame("Song Library"); songLibrary.setLocationRelativeTo(null); songLibrary.setResizable(true); songLibrary.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); list.addListSelectionListener(new ListSelectionListener(){ public void valueChanged(ListSelectionEvent evt){ int i = list.getSelectedIndex(); if (i != -1) System.out.println("Selected: " + songs[i]); else System.out.println("Choose a song"); } }); JScrollPane JSPane = new JScrollPane(list); JSPane.setPreferredSize(new Dimension(100,100)); songLibrary.add(JSPane); songLibrary.setSize(400,400); songLibrary.setVisible(true); } public static void main(String[] args){ new SongLib(); }

Answer1:

<ol><li>Stop calling (for the rest of your entire life) setPreferredSize(). Meaning that this call: JSPane.setPreferredSize(new Dimension(100,100)); should definitely be removed. </li> <li>If you want to have 2 panels side-by-side with a draggable separator: use JSplitPane. If you don't want the draggable divider, use a JPanel with an appropriate LayoutManager (GridBagLayout may be a good choice)</li> <li>Reading from a file is pretty easy, just make a search on SO and you will find hundreds of response. If you want to parse csv-files, there are some libraries around that can help you do that. Eventually, if you consider making this an application for a while, there are some small pure-java, embeddable, databases which will do a much better job at reading/storing/searching information than a simple text-file.</li> <li>Learn the Java naming conventions and stick to them: variables always start with a lower-case letter.</li> </ol>

Answer2:

In addition to @Guillaume Polet's good <a href="https://stackoverflow.com/a/14801818/230513" rel="nofollow">advice</a>, <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getVisibleRowCount%28%29" rel="nofollow">setVisibleRowCount()</a> may be useful to you going forward.

<img alt="image" class="b-lazy" data-src="https://i.stack.imgur.com/o0U6K.png" data-original="https://i.stack.imgur.com/o0U6K.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** @see https://stackoverflow.com/a/14801908/230513 */ public class SongLib { String songs[] = {"Song1", "Song2", "Song3", "Song4", "Song5"}; JList list = new JList(songs); public SongLib() { JFrame songLibrary = new JFrame("Song Library"); songLibrary.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); list.setVisibleRowCount(4); list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent evt) { int i = list.getSelectedIndex(); if (i != -1) { System.out.println("Selected: " + songs[i]); } else { System.out.println("Choose a song"); } } }); JScrollPane JSPane = new JScrollPane(list); songLibrary.add(JSPane); songLibrary.pack(); songLibrary.setLocationRelativeTo(null); songLibrary.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new SongLib(); } }); } }

Answer3:

For 1., take a look at layouting in Java, especially the GridBagLayout. <a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html" rel="nofollow">http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html</a>

For 2: Reading and writing from / into files is made by using File-Objects and Inout/Output-Streams. But this is a very low level way to do this. I think you should consider using an XML file. Take a look at JAXB

Recommend

  • how to call combobox selected item from another class in java?
  • Converting string array to list: double brackets
  • hotmail login error in java (IDE: Netbeans)
  • Swift: Segmented control behaves in a weird way in UITableView Cell
  • UmbrellaException when button is clicked
  • An object reference is required for the nonstatic field, method, or property 'member'
  • Why is PyQt connect() syntax so verbose?
  • UIRefreshControl with low height UICollectionView
  • .NET Text To Speech Volume
  • Add click event on window, but ignore all links that start with https
  • Open a file from the same package
  • Java refreshing second form
  • SVG Error: Permission denied to access property 'someFunction'
  • Who propagate bugfixes across branches (corporate development)?
  • How do I display a dialog that asks the user multi-choice questıon using tkInter?
  • MySQL Order by column = x, column asc?
  • MVC3 Razor - ListBox pre-select not working
  • How to install a .deb file on a jailbroken iphone programmatically?
  • How to delay loading a property with linq to sql external mapping?
  • Scrapy recursive link crawler
  • How to rebase a series of branches?
  • Recording logins for password protected directories
  • SignalR .NET Client Invoke throws an exception
  • Lost migrations and Azure database is now out of sync
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • How do I fake an specific browser client when using Java's Net library?
  • Sony Xperia Z Tablet not found by adb
  • How to get a value (ex: baseURL) in every Karate feature?
  • Validaiting emails with Net.Mail MailAddress
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Rearranging Cells in UITableView Bug & Saving Changes
  • File upload with ng-file-upload throwing error
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • How does Linux kernel interrupt the application?
  • Sorting a 2D array using the second column C++
  • java string with new operator and a literal
  • How to push additional view controllers onto NavigationController but keep the TabBar?