I am creating a GUI that will allow the user to input Lake information for the state of Florida and then has the ability to display that lake information. I want the display information to be in a JOptionPane.showMessageDialog that has the ability to scroll through the ArrayList of all the lake names. I am able to add the lakes into the ArrayList but they will not display in my JOptionPane and it is blank. I know it is reading something in the ArrayList since it is opening that window. Here is the code below in snippets as the whole thing would be cra.
public static ArrayList<Lakes> lake = new ArrayList<Lakes>();
private JTextArea textAreaDisplay;
private JScrollPane spDisplay;
// this is called in my initComponent method to create both
textAreaDisplay = new JTextArea();
for (Object obj : lake)
{
textAreaDisplay.append(obj.toString() + " ");
}
spDisplay = new JScrollPane(textAreaDisplay);
textAreaDisplay.setLineWrap(true);
textAreaDisplay.setWrapStyleWord(true);
spDisplay.setPreferredSize(new Dimension(500, 500));
// this is called in my createEvents method. After creating lakes in the database
// it will display the else statement but it is empty
btnDisplayLake.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
if (lake.size() == 0)
{
JOptionPane.showMessageDialog(null, "No Lakes in database!");
}
else
JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
}
catch (Exception e1)
{
}
}
});
Thank you for any help you can provide. I have been racking my brain for a few days on this. Been able to get other stuff accomplished but coming back to this issue.
Some obvious issues:
textAreaDisplay = new JTextArea();
A JTextArea should be created with code like:
textAreaDisplay = new JTextArea(5, 20);
By specifying the row/column the text area will be able to calculate its own preferred size. Scrollbars should appear when the preferred size of the text area is greater than the size of the scroll pane.
spDisplay.setPreferredSize(new Dimension(500, 500));
Don't use setPreferredSize(). The scroll area will calculate its preferred size based on the preferred size of the text area.
textAreaDisplay.append(obj.toString() + " ");
I would think you want each Lake to show on a different line, so I would append "\n" instead of the space.
I was setting textAreaDisplay before anything was entered into the ArrayList and it would not run again after anything was entered. I moved the for loop down and into the actionPerformed event and works well now.
btnDisplayLake.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
for (Object obj : lake)
{
textAreaDisplay.append(obj.toString() + "\n");
}
if (lake.size() == 0)
{
JOptionPane.showMessageDialog(null, "No Lakes in database!");
}
else
JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
}
catch (Exception e1)
{
Related
String [] texts= new String[26];
for(int a=0; a<26; a++){
String te=money[a].getText();
texts[a] = te;
box[a].setText(te);
}
In this code I want to set Text boxs and box is a JLabel. I created moneys which are also JLabel and has texts. I want that if I click on a box I wan to remove that box and money which has the same text with that box. For this I wrote this code:
for(clickLoop=0; clickLoop<26; clickLoop++){
box[clickLoop].addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
clickCount++;
if(clickCount == 0){
box[26].setVisible(false);
JLabel labelReference=(JLabel)e.getSource();
ortaPanel.remove(welcome);
ortaPanel.revalidate();
ortaPanel.repaint();
ortaPanel.add(labelReference).setBounds(390,480,im.getIconWidth(),im.getIconHeight());
System.out.println("a");
ortaPanel.add(six).setBounds(305, 465, s.getIconWidth(), s.getIconHeight());
labelReference.removeMouseListener(this);
}else if(clickCount == 6){
e.getComponent().setVisible(false);
JLabel labelReference=(JLabel)e.getSource();
ortaPanel.remove(six);
ortaPanel.revalidate();
ortaPanel.repaint();
//ortaPanel.add(labelReference).setBounds(390,480,im.getIconWidth(),im.getIconHeight());
ortaPanel.add(five).setBounds(305, 465, s.getIconWidth(), s.getIconHeight());
labelReference.removeMouseListener(this);
}else {
e.getComponent().setVisible(false);
String esles=((JLabel) e.getComponent()).getText();
for(int i=0; i<money.length; i++){
if(esles.equals(money[i].getText()) ){
sagPanel.remove(money[i]);
}
}
}
System.out.println(clickCount);
}
});
}
}
Some labels are working truely but most of them didnt work. I dont know why? There is one more question I want to ask: As you can see the code above I created text of box[i] same as text of money[i]. Instead of doing like that I want to make it randomly. I tried but did not achive. Do you know how can I do that? Thanx in advance.
I have a small Java swingui app where I display a JList and the user is able to cut, copy, paste and sort the list.
I use a custom TransferHandler to allow drag and drop on this Jlist. Here is the code in building the JList, it basically builds it from an ArrayList. "lstScripts" is the JList.
ListTransferHandler lh = new ListTransferHandler();
...
DefaultListModel listModelScripts = new DefaultListModel();
for(Script s : scripts) {
listModelScripts.addElement(s.getName());
}
this.lstScripts = new JList(listModelScripts);
this.lstScripts.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.lstScripts.addListSelectionListener(this);
JScrollPane sp = new JScrollPane(this.lstScripts);
sp.setPreferredSize(new Dimension(400,100));
this.lstScripts.setDragEnabled(true);
this.lstScripts.setTransferHandler(lh);
this.lstScripts.setDropMode(DropMode.ON_OR_INSERT);
setMappings(this.lstScripts);
...
On my custom TransferHandler class, I've got the importData routine working so that it handles the copy/paste/cut/sort.
public boolean importData(TransferHandler.TransferSupport info) {
String scriptname = null; // The script name on the list
//If we can't handle the import, bail now.
if (!canImport(info)) {
return false;
}
JList list = (JList)info.getComponent();
DefaultListModel model = (DefaultListModel)list.getModel();
//Fetch the scriptname -- bail if this fails
try {
scriptname = (String)info.getTransferable().getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException ufe) {
System.out.println("importData: unsupported data flavor");
return false;
} catch (IOException ioe) {
System.out.println("importData: I/O exception");
return false;
}
if (info.isDrop()) { //This is a drop
JList.DropLocation dl = (JList.DropLocation)info.getDropLocation();
int index = dl.getIndex();
model.add(index, scriptname);
return true;
} else { //This is a paste
int index = list.getSelectedIndex();
// if there is a valid selection,
// insert scriptname after the selection
if (index >= 0) {
model.add(list.getSelectedIndex()+1, scriptname);
// else append to the end of the list
} else {
model.addElement(scriptname);
}
return true;
}
}
So up to here, everything works fine as far as the GUI. But my problem is I need the original JList "lstScripts" to be automatically updated with the user GUI changes. For example, if the user cuts or reorders the list, I want it to show on in "lstScripts".
I'm not seeing how to make this connection between the TransferHandler and original GUI controller where "lstScripts" resides.
#kleopatra - you helped me! sorry I didnt understand how the model was working.
So in the controller, I create the "lstScripts" JList and add it to my panel (this is the first block of my code above).
pnlScripts.add(lstScripts, BorderLayout.WEST);
And as my code above showed, the listScripts JList had a custom transferhandler set as such:
this.lstScripts.setTransferHandler(lh);
So the transferhandler does all the user dnd (drag and drop) stuff. In the controller, I can get the updated list by doing:
DefaultListModel model = (DefaultListModel)lstScripts.getModel();
for (int i = 0; i < model.getSize(); i++){
scriptnames += model.getElementAt(i).toString() + ",";
}
The scriptnames String variable now contains the updated list.
Thanks!
I am attempting to build a twitter client using Twitter4. I am storing the users tweets and info etc in a DefaultListModel in a Jlist. I want to add the users profile picture and to do this I am setting the Icon using a ListCellRenderer. My issue here is that I am only able to set the ListCellRenderer text and icon to one users information. I use a loop to pull down multiple tweets and add them to the model, but the renderer is only setting one tweet many times.
This is the code to retrieve a tweet
for (int i = 0; i < list.size(); i++) {
Status each = (Status) list.get(i);
UI.model.addElement("<html><body style='width: 450px;'>"
+ "#"
+ each.getUser().getScreenName()
+ " - "
+ each.getText() + "<html><br>");
UI.whatIsDisplayedList.setCellRenderer(new newsFeedRenderer(each)); }
And this is how I am setting the ListCellRenderer
JLabel pic = new JLabel();
try {
ImageIcon img = new ImageIcon(TwitterFunctions.eachTweetProfilePic(each.getUser()));
pic.setIcon(img);
setIcon(img);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setText( "#" + each.getUser().getScreenName() + " - " + each.getText());
What modifications would I have to make to enable the correct formatting of the tweets?
Thanks for the help!
You shouldn't pass a newFeedReader() to setCellRenderer();
A ListCellRenderer is an object used to paint cells, not to be used as a database kind of object.
What you're going to want to do is,
Get all of the statuses at the beginning
Pass them as an array to a JList
Then create a custom ListCellRenderer class and in your getListCellRendererComponent method, return your JLabel which has your ListCellRenderer code
I have the following method which creates a JTable then prints it out by its appearing as a rectangle no the page with the header and footer.
public void printModules(){
MessageFormat header = new MessageFormat("Modules " + new Date());
MessageFormat footer = new MessageFormat("Created by Assignments Database");
try {
JTable jtModules = new JTable(new ModulesTableModel(Controller.getInstance().getModules()));
jtModules.setShowHorizontalLines(true);
jtModules.setShowVerticalLines(true);
jtModules.setShowGrid(true);
boolean complete = jtModules.print(JTable.PrintMode.NORMAL, header, footer, true, null, false, null);
if(complete){
System.out.println("Printed");
} else{
System.out.println("Printing Cancelled");
}
} catch (PrinterException e) {
e.printStackTrace();
}
}
What else is wrong? There is data in the table as one that is created from the same data is showing in one of the panels.
In my abstract table model I have implemented the following methods:
Constructor
getRowCount
getColumnCount
getValueAt
getColumnNames
Is there any other methods that need to be created?
JTable has very reduced support for printing, there are some descriptions about printing in the tutorials about JTable (inc. code example) and Printing
You need to display the table in order to print it, so add it to a JFrame, then frame.setVisible(true); then frame.setVisible(false);
This will make it print.
My Java GUI application needs to quickly show some text to the end-user, so the JOptionPane utility methods seem like a good fit. Moreover, the text must be selectable (for copy-and-paste) and it could be somewhat long (~100 words) so it must fit nicely into the window (no text off screen); ideally it should all be displayed at once so the user can read it without needing to interact, so scrollbars are undesirable.
I thought putting the text into a JTextArea and using that for the message in JOptionPane.showMessageDialog would be easy but it appears to truncate the text!
public static void main(String[] args) {
JTextArea textArea = new JTextArea();
textArea.setText(getText()); // A string of ~100 words "Lorem ipsum...\nFin."
textArea.setColumns(50);
textArea.setOpaque(false);
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JOptionPane.showMessageDialog(null, textArea, "Truncated!", JOptionPane.WARNING_MESSAGE);
}
How can I get the text to fit entirely into the option pane without scrollbars and selectable for copy/paste?
import java.awt.*;
import javax.swing.*;
public class TextAreaPreferredHeight2
{
public static void main(String[] args)
{
String text = "one two three four five six seven eight nine ten ";
JTextArea textArea = new JTextArea(text);
textArea.setColumns(30);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.append(text);
textArea.append(text);
textArea.append(text);
textArea.append(text);
textArea.append(text);
textArea.setSize(textArea.getPreferredSize().width, 1);
JOptionPane.showMessageDialog(
null, textArea, "Not Truncated!", JOptionPane.WARNING_MESSAGE);
}
}
If you need to display a string of an unknown length, you can set number of rows "on the fly":
public static void showMessageDialogFormatted(String msg, String title, int messageType, int columnWidth) {
JTextArea textArea = new JTextArea(msg);
textArea.setColumns(columnWidth);
textArea.setRows(msg.length() / columnWidth + 1);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
JOptionPane.showMessageDialog(null, textArea, title, messageType);
}
You've got the right idea. Just adjust the rows of your textarea.
textArea.setRows(10); // or value that seems acceptable to you...
This seemed to fix the issue for me, using 100 words of lorem ipsum.
Try this:
JTextArea textArea = new JTextArea();
textArea.setText(getText());
textArea.setSize(limit, Short.MAX_VALUE); // limit = width in pixels, e.g. 500
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);