I'm going to try to keep my post as short as possible;
Here's my custom Object
public class ListItem {
ListItem(String text){
this.text = text;
}
final String text;
final ObjectProperty<Font> font = new SimpleObjectProperty<>();
final ObjectProperty<Color> color = new SimpleObjectProperty(Color.BLACK);
}
It's a cell object for holding: String, Color, Font/int (I just need the Fontsize, might change it to int if needed)
Using it, I created a ListView<ListItem>.
Now I can fill that ListView<ListItem> with a cell which is a ListItem using a CellFactory. That looks like this.
Until here - everything works. (The above code & explanation is for better understanding what I'm trying to do)
but now, I don't know how to do the following:
Saving the ListView-Content to a file. Or a little more clearly; How can I take the whole content of my ListView, filled with custom Objects while saving all of their properties (String, Color, Int)?
A little example of how I'd imagine that to give you a better idea:
"entry_1":
text: "entry text goes here"
color: "web color code goes here (e.g. #ff4d4d)"
fontsize: "16"
"entry_2":
...
Update
I set up a loop, I guess it should work fine but this gives me errors;
My file/it's path:
private final String saveLoc = System.getenv("ProgramFiles")
+ File.separator
+ "simpleNotizen"
+ File.separator
+ "simpleNotizen.properties";
private final File save = new File(saveLoc);
How I call it:
if(!save.exists()){
save.getParentFile().mkdirs();
save.createNewFile();
}
The error (thrown on save.createNewFile();):
Caused by: java.io.IOException: The System can't find the given Path
(Or something similair, had to translate it)
I really don't get why the error is thrown, I tried FileWriter, OutputStream, File, but everytime the same error..
I also tried to give a sysout, which seems perfectly fine:
C:\Program Files\simpleNotizen\simpleNotizen.properties
Solved
If anyone wonders how I fixed it, here it is
For saving my ListView Content, I wrote a loop which repeats itself by the amount of entries there are in the ListView;
for (int i = 0; i < listSize; i++) {
prop.setProperty("entry_" + Integer.toString(i),
listView.getItems().get(i).text
+ "|"
+ listView.getItems().get(i).color.getValue()
+ "|"
+ listView.getItems().get(i).font.getValue().getSize()
);
}
My second problem appeared to be a Permission problem with the C:\Program Files\-Path, fixed it by replacing it w/ APPDATA
Related
Basically, i'm using 2 images for a board game type of thing, and i change it from time to time,
So i need to be able to check if two has the same imageIcon.
For example if both uses "pirosfigura.png" from the resources folder.
public String malomcheck() {
String pirosicon=lblNewLabel.getIcon().toString();
String pirosfilenev = pirosicon.substring(pirosicon.lastIndexOf("/" ) + 1);
String iconfilenev = labelhely_1.getIcon().toString();
String filenev = iconfilenev.substring(iconfilenev.lastIndexOf("/" ) + 1);
if(filenev==pirosfilenev) {
lblJtkos.setText("piros malom.");
JOptionPane.showMessageDialog(null, "working");
return "lefutott";
}
return "notworking. very sad.";
}
By the way the return value of the getIcon().toString() is javax.swing.ImageIcon#cd7e8021
which is refers to the memory place i guess(?) so it's random with every run and for every image therefore it's seems unusable.
One way you can achieve this, is to keep your own mapping of ImageIcons to files, so that whenever you load an ImageIcon you store it in a Map as a key and its file or some symbolic name/enum as value. This way when you want to compare imIc1 and imIc2 you would write something like:
if (map.get(imIc1).equals(map.get(imIc2)) { ... }
or (if you have descriptive string values )
if (map.get(imIc1).equals("NOT_WORKING_ICON") { ... }
or (if you are using enum values )
if (map.get(imIc1) == NOT_WORKING_ICON ) { ... }
it's so weird for me that there is no method to get to the filepath the Jlabel is using for an image.
Makes perfect sense. A JLabel displays an Icon.
Why should a JLabel know or care about the file path?
You could implement the Icon interface yourself and do the custom painting for the Icon. So not all Icons will have a file path. Only an ImageIcon is created from a file.
The property for the file name belongs to the ImageIcon.
By the way the return value of the getIcon().toString() is javax.swing.ImageIcon#cd7e8021
Image piros=new ImageIcon(this.getClass().getResource("pirosfigura.png")).getImage();
celpont.setIcon(new ImageIcon(piros));
Look at the above code that you are using.
You area creating an Icon from an Image, so the file information is lost.
Instead you should just create the ImageIcon directly:
ImageIcon icon = new ImageIcon( this.getClass().getResource("pirosfigura.png") );
celpont.setIcon( icon );
System.out.println( celpont.getIcon() );
I believe the ImageIcon will then save the filename as the "description" for the ImageIcon. It appears the toString() will return the description.
I'm trying to dynamically create some choice chip components based on an ArrayList of String from some computation and following are the code to create the chips and adding them to a ChipGroup created in layout XML file.
if (mChipGroup.getChildCount() == 0 ){
int i = 0;
for (Classifier.Recognition res: results){
Chip resultChip = new Chip(getDialog().getContext());
ChipDrawable chipDrawable =
ChipDrawable.createFromAttributes(
getActivity(),
null,
0,
R.style.Widget_MaterialComponents_Chip_Choice);
resultChip.setId(i++);
resultChip.setChipDrawable(chipDrawable);
resultChip.setText(res.getTitle());
mChipGroup.addView(resultChip);
}
}
The Chips displayed correctly with the text but when I tried to call getText() on the chips, it always return empty String but not the text contained by the chips. I tested this by setting the OnCheckedChangeListener on the ChipGroup and making a Toast with the text (though it didn;'t work). When I tried to display only the checkedId it works.
mChipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(ChipGroup group, int checkedId) {
Chip chip = group.findViewById(checkedId);
if(chip != null){
Toast.makeText(getContext(), chip.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
});
My current workaround is to have a variable holding the array results and use ArrayList.get(selectedChipId.getTitle()). but don't think it should be that way though
I also found that it is able to get text from Chips added in layout file but not run-time added Chips. Tried with both 1.1.0/alpha06 and 1.1.0/alpha07 release but am having no luck. Would like to have some advice if possible. Thank you very much.
So, it seems like a bug as per answered in here and here. Current workaround is to use ((ChipDrawable) chip.getChipDrawable()).getText() instead.
I'm having trouble batch adding images to a JButton grid. I'm trying to use a for loop who's variable is used in the string name.
The names of the images are like:
32px-Shuffle001.png
32px-Shuffle821.png
etc.
Here's the part of the code that I'm trying to add in images with. The third setIcon works, but the first two don't. I'm confused on why this is.
Additionally, the image files are not consecutive numbers. For example, I have 001,002,003,004,005, but not 007,008, then continuing at 009,010. I'm trying to figure out a good way to make it skip to the next available image.
Overall, this code is for a match 3 puzzle solver, and this is a selection grid for icons to put on the puzzle grid, so I need to be able to call the correct image associated to a button ID.
for (int i = 0; i < 1000; i++) {
JButton selectionClicky = new JButton();
if (i < 10) {
selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle" + "00"
+ i + ".png"));
}
if (i < 100){
selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle"+ "0"
+ i + ".png"));
}
if (i < 1000){
selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle"
+ i + ".png"));
}
selectionClicky.setFocusable(false);
selectionMainPanel.add(selectionClicky);
selectionButtonList.add(selectionClicky);
}
Don't ever use src in any path reference, this is a good indication that things will go wrong, instead use Class#getResource or Class#getResourceAsStream depending on your requirements.
Basically, the general idea would be to test if the resource actually existed before trying to load it, for example...
String path = String.format("/img/32px-Shuffle%03d", i);
URL resource = getClass().getResource(path);
if (resource != null) {
BufferedImage img = ImageIO.read(resource);
selectionClicky.setIcon(new ImageIcon(img));
}
Generally, ImageIO is preferred over using ImageIcon, mostly because ImageIO throws an IOException when the image can't be loaded for some reason (instead of failing silently) and won't return until the image is fully loaded
See Reading/Loading an Image for more details about ImageIO
I want to change the text of selected text in JTextArea.
For example when i press button i want the selected text to be change (Original Text Selected - I want to replace like this when i press the button : Replace:Original Text Selected) this is what i am trying to do in my code,
String replacement = "Replace:" + messageBodyText.getSelectedText() ";
but i have no idea how to change only selected text i am trying to do something but i am changing entire text of JTextArea Hope you understood my question ?
Thanks to Hovercraft Full Of Eels he solved my problem this is my code for other people who are facing the same problem :
int start = messageBodyText.getSelectionStart();
int end = messageBodyText.getSelectionEnd();
StringBuilder strBuilder = new StringBuilder(messageBodyText.getText());
strBuilder.replace(start, end, "Replace:" + messageBodyText.getSelectedText() + ".");
messageBodyText.setText(strBuilder.toString());
textComponent.replaceSelection(newText);
JTextComponent (and thus JTextArea) has getSelectionStart() and getSelectionEnd() methods that will help you. Get your text from the JTextArea or its Document, and using these int values you can change your text and replace it into the text component.
For example,
int start = myTextField.getSelectionStart();
int end = myTextField.getSelectionEnd();
StringBuilder strBuilder = new StringBuilder(myTextField.getText());
strBuilder.replace(start, end, newText);
myTextField.setText(strBuilder.toString());
I have written an applet in Java as a part of my programming class that takes a person's birthday and finds the day of the week on which they were born. As per the assignment specifications, we are to put this applet on our Amazon EC2 virtual servers as well.
Now, when the person is selected from a JTable, the program takes their information as well as the path to an image file also located in the JTable beside their info. So, for example, you could have the selection consisting of:
| John Doe | 17 | 02 | 2013 | /images/John.jpg |
When I run this on my local machine, everything works as expected - the date is calculated and the image is displayed. However, when I put it on my server, one of two things happens:
If I put the "display date" code before the "display image" code, then when I press the "Calculate" button, only the text displays and the image does not.
If I put the "display image" code before the "display date" code, nothing happens when I press the "Calculate" button.
What might be happening here? My images are still in the "images/Name.jpg" path, and I even tried using the entire path ("https://myUsername.course.ca/assignment/images/Name.jpg"). Neither works! Would there be any obvious reason for this odd behaviour?
/**
* Method that handles the user pressing the "Calculate" button
*/
private class btnCalculateHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int result;
name = (String)table.getValueAt(table.getSelectedRow(), 0);
day = Integer.parseInt((String)table.getValueAt(table.getSelectedRow(), 1));
month = Integer.parseInt((String)table.getValueAt(table.getSelectedRow(), 2));
year = Integer.parseInt((String)table.getValueAt(table.getSelectedRow(), 3));
result = calculateDayOfWeek(day, month, year);
writeToFile();
ImageIcon imgPerson = new javax.swing.ImageIcon((String)table.getValueAt(table.getSelectedRow(), 4));
Image person = imgPerson.getImage();
Image personResized = person.getScaledInstance(75, 100, java.awt.Image.SCALE_SMOOTH);
ImageIcon imgPersonResized = new ImageIcon(personResized);
image.setIcon(imgPersonResized);
outputValue.setText(name + " was born on a " + days[result] + ".");
}
}
The first problem I see is this....
ImageIcon imgPerson = new javax.swing.ImageIcon((String)table.getValueAt(table.getSelectedRow(), 4))
ImageIcon(String) is used to specify a file name of the image. This should be used for loading images of a local disk, not a network path.
If the images are loaded relative to the to the applet, you would use Applet#getImage(URL, String) passing it a reference of Applet#getDocumentBase()
Something like getImage(getDocumentBase(), (String)table.getValueAt(table.getSelectedRow(), 4))
A better choice would be to use ImageIO. The main reason for this is that it won't use a background thread to load the image and will throw a IOException if something goes wrong, making it easier to diagnose any problems...
Something like...
BufferedImage image = ImageIO.read(new URL(getDocumentBase(), (String)table.getValueAt(table.getSelectedRow(), 4)));