How to print jTable onclick in NetBeans 14 - swing

I need to show a table which gets data from a query to my database when:
The app first starts.
Anytime the tab is clicked.
I've looked at multiple solutions including revalidate(), repaint(), jTableModel but none of them work.
I can display the table if I use jTextArea1.setText(result); but it doesn't look good enough.
This is what I have so far:
private void jTabbedPane1MouseClicked(java.awt.event.MouseEvent evt) {
String[][] content = voiControl.allVehicleModel();
String result = Arrays
.stream(content)
.map(Arrays::toString)
.collect(Collectors.joining(System.lineSeparator()));
jTextArea1.setText(result);
String[] headers = {"Model","Make"};
JTable table = new JTable(voiControl.allVehicleModel(), headers);
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
jPanel3.add(scrollPane);
revalidate();
repaint();
}

Related

JavaFX: How to setText of ComboBoxes and ToggleButtons in loop?

I have a JavaFX application with a lot of ToggleButtons, ComboBoxes and TextFields organised in lists by their types. I have also a JSON file with list of my Member's class objects.
Ofcourse I have a #FXML adnotations buttons for buttons, etc.
When my app launch I want to set for everyone ToggleButton a specific Text what I have prepared in JSON file for specific Member. I planned to do this by using initialize() method to call my method fillToggleButtons():
List<Member> membersFromJSON = new ArrayList<>();
List<ToggleButton> sendToTeamMembers = new ArrayList<>();
private void fillToggleButtons() {
Reader reader = null;
try {
reader = new FileReader(JSONFilePaths.membersJSONFilePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Gson gson = new Gson();
Type memberList = new TypeToken<ArrayList<Member>>() {}.getType();
List<Member> members = gson.fromJson(reader, memberList);
for (int i = 0; i < sendToTeamMembers.size(); i++) {
for (int k = 0; k < members.size(); k++) {
sendToTeamMembers.get(i).setText(members.get(k).getName());
}
}
}
But when I do this, my loops don't work. I have the same Text for everyone ToggleButton, but in JSON file I have them different. Do I need an ObservableList here instead of standard java List?
The same question for ComboBoxes (I know I should use index, also I have it in the same JSON file as Member's ID/index).
What should I do for set Text in loop for JavaFX objects?
Your loop logic is wrong - you're setting each ToggleButton's text multiple times (first to members.get(0).getName(), then to members.get(1).getName(), etc).
In the end, each ToggleButton will have its name set to the name of the last member from the list.
You only need one for loop:
for (int i = 0; i < sendToTeamMembers.size(); i++) {
sendToTeamMembers.get(i).setText(members.get(i).getName());
}
Be sure to check if members list contains at least sendToTeamMembers.size() elements before you call the code above - and if it doesn't, there's probably some error with loading/parsing your JSON file that you'll need to fix first.

Changing texture depending on action

So when a user makes a purchase they get a new texture available that will replace the original one. I´ve sort of pulled it of. But I also want the user to ba able to replace back to the original one if the wish to do so.
At the moment the user makes a purchase and the texture changes fine. But as I store that change in preferences it makes it permanent. So when I try to press the button to change to the original stone, which simply calls "setStone(...)" , nothing happends.
Anyone that can see where I´ve gone wrong?
P.S the code is not copied straight of, just cut in the important parts.
ObjectMap<Integer, Texture> screenMap = new ObjectMap<Integer, Texture>();
ObjectMap<String, Boolean> mTexturesStatus = new ObjectMap<String, Boolean>();
public void setStone1() {
stoneImage = new Image(screenMap.get(0));
}
public void setStone(int screenId) {
stoneImage = new Image(screenMap.get(screenId));
}
screenMap.put(0, sdStone);
screenMap.put(1, stone_3);
mTexturesStatus.put("stone1", stone1);
mTexturesStatus.put("stone2", stone2);
btnArrow.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
game.setScreen(0);
//Saves the entered text.
Preferences prefs = Gdx.app.getPreferences("preferences");
prefs.putString("textField", textField.getText());
prefs.putString("textArea", textArea.getText());
prefs.getBoolean("stoneOne");
prefs.getBoolean("stoneTwo");
prefs.flush();
}
});
//screenMap.put(prefs.getInteger("stoneOne", 0), sdStone);
//screenMap.put(prefs.getInteger("stoneTwo", 1), stone_3);
setStone1();
if(stone1 = true) {
setStone(0);
prefs.putBoolean("stoneOne", true);
}
if(stone2 = true) {
setStone(1);
prefs.putBoolean("stoneTwo", true);
}
}

Filling a JavaFX TableView with DataFX

I'm trying to fill a TableView with the data from a csv-file with the datafx extension.
Unfortunately the tableview is empty and I'm not able to find any example anywhere which indicates my mistake.
DataSourceReader dsr1 = new FileSource("Example3.csv");
CSVDataSource ds1 = new CSVDataSource(dsr1);
TableView table1 = new TableView();
table1.setItems(ds1.getData());
table1.getColumns().addAll(ds1.getColumns());
System.out.println("#ds1 " + ds1.getData().size()); //returns zero
The code does not throw an exception, which makes it even more mysterious.
even though the question is to fill the TableView with the DataFX extension here is a solution without DataFX:
Create a class that represents a list item of your tableView e.g.:
public class YourItem {
private String itemID;
private String itemTitle;
public String getItemID() {
return itemID;
}
public void setitemID(String itemID) {
this.itemID = itemID;
}
//getter and setter for the other vars, I am lazy. }
Parse your csv file and return a List<YourItem>
there are several tutorials and examples for that, you can find one here:
http://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/ Important is that you create a List of YourItem objects where each row is a YourItem object
Convert your List<YourItem> into an ObservableList<YourItem>
ObservableList<YourItem> obsList = FXCollections.observableArrayList(yourList);
finally set the items to your TableView:
I won't mention that you need to create Columns for your TableView
TableView<YourItem> test = new TableView<YourItem>();
test.setItems(obsList);

MONOTOUCH get row item selected

I have a navigation controller to show a list o item on table, then I need to touch an item a show the details of this item.
Here it's my code of how a fill the table:
public void SearchHotel (){
Hotel hotel = new Hotel();
var distribution = new HotelDistribution[]{new HotelDistribution(){ Adults = 1, Children = 0, ChildrenAges = new int[0]} };
var items = hotel.SearchHotels(Convert.ToDateTime("2013-08-08"),Convert.ToDateTime("2013-09-09 "),"(MIA)", distribution,"","","",0);
data = new List<DtoHotelinformation>();
foreach (var item in items)
{
DtoHotelinformation DtoHotelinformation = new DtoHotelinformation();
DtoHotelinformation.code = item.Code.ToString();
DtoHotelinformation.price = item.Price.ToString();
DtoHotelinformation.title = item.Name.ToString().ToTitleCase();
DtoHotelinformation.subtitle = item.Address.ToString();
DtoHotelinformation.rating = item.Rating.ToString();
DtoHotelinformation.imageUlr = item.ImageUrl;
data.Add(DtoHotelinformation);
}
hud.Hide(true);
hud.RemoveFromSuperview();
HotelSearchTable.Source = new HotelTableSource(data.ToArray());
HotelSearchTable.ReloadData();
}
Because I'm using storyboard to show the details view controller I have this code on my table source:
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
if (RowTouched != null) {
RowTouched (this, EventArgs.Empty);
}
tableView.DeselectRow (indexPath, true); // normal iOS behaviour is to remove the blue highlight
}
Back in to my viewcontroller I call the RowTouched to show the details controller like this:
public override void ViewDidAppear (bool animated) {
base.ViewDidAppear (animated);
SearchHotel ();
var source = new HotelTableSource(data.ToArray());
var detail = Storyboard.InstantiateViewController("HotelDetailScreen") as iPhoneHotelDetailViewController;
source.RowTouched += (sender, e) => {
this.NavigationController.PushViewController(detail, true);
};
HotelSearchTable.Source = source;
}
But I need to pass the information of the item touched on the table to show the details. I don't really don't know what do I have to do?
NOTE: I can't use PrepareForSegue because I don't have a segue between controllers.
Thanks in advance
If you want you can get a hold of your UINavigationController
from within your Row Selected event, inside of your Table Data Source.
From there you can push your new ViewController.
[indexPath.Row] in "Row_Selected" should tell you which element in your array or list, that the user has selected.
UINavigationController navcontroller =(UINavigationController)UIApplication.SharedApplication.Windows[0].RootViewController;
Passing data to an event handler is exatly what the EventArgs parameter is for.
Create a class that inherits from EventArgs and has properties for the data you need:
public class HotelSelectedEventARgs : EventArgs
{
public DTOHotelInformation HotelInfo { get; set; }
}
Then, when you call your handler in RowSelected, instead of passing an empty EventArgs, create an instance of your custom class and assign the selected data to the HotelInfo property.

Existing posts keep on re-added into jTable with newer post

Here are my codes :
public void submitReply(ActionEvent e) {
String replyBy = userName;
String reply = jTextArea_reply.getText();
if (reply.equals("")) {
JOptionPane.showMessageDialog(null, "Comment cannot leave blank");
} else {
eForumTopics comment = new eForumTopics(replyBy, reply);
if (comment.createComment() == true) {
JOptionPane
.showMessageDialog(null,
"Reply submitreted successfully. You will be redirect to main page.");
SetUpJTableComment();
public void SetUpJTableComment() {
// Get jTable model
DefaultTableModel tableModel1 = (DefaultTableModel) jTableComment
.getModel();
// Store column data into Array (3 columns)
String[] data = new String[3];
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select reply_content,reply_by from forumReplies WHERE reply_topic = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
data[0] = resultSet.getString("reply_content");
data[1] = resultSet.getString("reply_by");
// Add data to table model
tableModel1.addRow(data);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
// add tablemodel to jtable
}
The problem is whenever users post a new reply, the existing posts will be re-added together. I try to do like only the newer reply from the comment box will be added into the jTable instead of keep on re-add the existing posts with newer reply. What am I supposed to use? A for loop? Thanks in advance.
The correct way to delete the content of DefaultTableModel is
model.setRowCount(0);
vs. the evil way mentioned in the comment (won't repeat it here ;-) which violates two rules
never change the underlying datastructure of a model under its feet
never call any of the model's fireXX from code outside the model
If doing the latter seems to help, it's a waring signal: you either violated the former or your model implementation is incorrect