Dynamically changing contents of ListCellRenderer - java

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

Related

JAVA - GridLayout and JScrollPane behave unexpected

My GridLayout in Java behaving diffrently like I expected.
I want to have multiple Boxes within an JScrollPane (like in the screenshot below).
But when i have to less entries (for example 2) the height of the boxes are 100% height.
Does someone can tell me what i made wrong in my code?
ResultSet result = MysqlDataReader.ReadFromDataBase("DUMMY",connectionStrato);
innerPanel.removeAll();
innerPanel.setLayout(new GridLayout(Integer.parseInt(Math.round(result.getRow() / 3) + ""), 6, 2, 2));
while(result.next()){
URL url;
Image image;
try{
url = new URL("DUMMY" + result.getString(1) + ".jpg");
image = ImageIO.read(url.openStream());
} catch (MalformatedURLException ex) {
url = new URL("DUMMY");
image = ImageIO.read(url.openStream());
Logger.getLogger(ItemforList.class.getName()).log(Level.SEVERE, null, ex);
} catch(IOException ex){
url = new URL("DUMMY);
image = ImageIO.read(url.openStream());
Logger.getLogger(ItemforList.class.getName()).log(Level.SEVERE, null, ex);
}
ItemforList item = new ItemforList("DUMMY"+result.getString(1)+".jpg", result.getString(1)+"");
innerPanel.add(item)
}
scrollPaneL.setViewportView(innerPanel);
Component[] components = innerPanel.getComponents();
for (Component component : components){
if(component.getClass().equals(ItemforList.class)){
ItemforList item = (ItemforList) component;
System.out.printLn("TEST");
item.SetResizedIcon();
}
}
You didn't post any code so I can't comment on or directly fix that.
But to answer your question, the way to fix your problem is to fill in the extra grid boxes with dummy components - something just to take up that space

Display Array in a JTextArea with ability to scroll

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)
{

Printer won't print the entire jTable [duplicate]

Question Now once the data is fetched from the database and shown in the JTable object "table" embedded in the scrollPane, how do we create a print job that makes it possible to print the displayed table as such in A3 sized paper ?
My code to fetch the data from the database is shown below:
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/newb","root","pass");
Statement stat=con.createStatement();
ResultSet res=stat.executeQuery("select * from table where name = '"+name+"'");
ResultSetMetaData rsmd = res.getMetaData();
int colcount = rsmd.getColumnCount();
Vector columns = new Vector(colcount);
for(int i=3; i<=colcount; i++)
{
columns.add(rsmd.getColumnName(i));
}
Vector data = new Vector();
Vector row;
// Store row data
while(res.next())
{
row = new Vector(colcount);
for(int i=3; i<=colcount; i++)
{
row.add(res.getString(i));
}
data.add(row);
}
table = new JTable(data, columns);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
scrollPane.setViewportView(table);
}
catch(Exception ex)
{
System.out.println(ex);
}
I am using vector class to fetch the data from the table. How do we print the data shown in the displayed table to a paper?
just use JTable.print() method. here is an article about sending JTable into printer and another one with more parameters
You obviously didn't read the links provided in your previous question.
From the Printing section of How to use Tables
Printing
JTable provides a simple API for printing tables. The easiest way to
print out a table is to invoke JTable.print with no arguments:
try {
if (! table.print()) {
System.err.println("User cancelled printing");
}
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n", e.getMessage());
}
Invoking print on a normal Swing application brings up a standard printing
dialog box. (On a headless application, the table is simply printed.)
The return value indicates whether the user went ahead with the print
job or cancelled it. JTable.print can throw
java.awt.print.PrinterException, which is a checked exception; that's
why the above example uses a try ... catch.
JTable provides several overloads of print with various options. The
following code from TablePrintDemo.java shows how to define a page
header:
MessageFormat header = new MessageFormat("Page {0,number,integer}");
try {
table.print(JTable.PrintMode.FIT_WIDTH, header, null);
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n", e.getMessage());
}
For more sophisticated printing applications, use JTable.getPrintable to obtain
a Printable object for the table. For more on Printable, refer to the
Printing lesson in the 2D Graphics trail.
i hope help you with this code try it its for How to print JTable in Java netbeans
private void btn_printActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MessageFormat header = new MessageFormat("Print Report");
MessageFormat footer = new MessageFormat("Page{0,number,integer}");
try {
table_employee.print(JTable.PrintMode.FIT_WIDTH, header, footer);
} catch (java.awt.print.PrinterAbortException e) {
} catch (PrinterException ex) {
Logger.getLogger(employee_info.class.getName()).log(Level.SEVERE, null, ex);
}
}

Java Swing - Dynamically change JList using TransferHandler

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!

JTable appearing as box when printing

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.

Categories