Adding multiple images through Arrays - java

Can we add multiple images in Java through arrays?
Like if we want to store each picture in an array
and then display it through a loop?
And
This displays all the picture at a time. I want to display one picture then another one after some time
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\MR\\Downloads\\Body Parts";
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
DefaultListModel listModel = new DefaultListModel();
int count = 0;
for (int i = 0; i < listOfFiles.length; i++)
{
System.out.println("check path"+listOfFiles[i]);
String name = listOfFiles[i].toString();
// load only JPEGs
if ( name.endsWith("jpg") ) {
ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
listModel.add(count++, ii);
}
}
JList lsm=new JList(listModel);
lsm.setVisibleRowCount(1);
frame.add(new JScrollPane(lsm));
frame.pack();
frame.setVisible(true);
}

Yes. Internally an array is a sequential chunk of heap memory and you can store anything /of reasonable size/.

Related

Store image to Array

Before adding image to JLabel, I used below code to resize them.
BufferedImage myPicture1 = ImageIO.read(new
File("C:\\Users\\yumi\\Desktop\\Salad.png"));
Image scaled1 = myPicture1.getScaledInstance(80,95,Image.SCALE_SMOOTH);
JLabel picLabel1 = new JLabel("Japanese Noodles",new
ImageIcon(scaled1),JLabel.CENTER);
panel.add(picLabel1);
Now I have array, want to store image to array
static private JLabel[] foodLabel;
static private JTextField[] qtyField;
static private ImageIcon[] imageIcon;
static private Image[] imageScaled;
static private BufferedImage[] image;
static private File[] file;
private static final int ELEMENTS = 9;
Trying to read file and scale it
file[0] = new File("C:\\Users\\yumi\\Desktop\\Salad.png");
.....
for (int i = 0; i < ELEMENTS; i++) {
image[i] = ImageIO.read(file[i]);
imageScaled[i] = image[i].getScaledInstance(80,95,Image.SCALE_SMOOTH);
foodLabel[i] = new JLabel(imageIcon([imageScaled[i]])); // error
}
Error
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
Syntax error on token "(", Expression expected after this token
The following should work. You have to create an ImageIcon for your scaled image first.
for (int i = 0; i < ELEMENTS; i++) {
image[i] = ImageIO.read(file[i]);
imageScaled[i] = image[i].getScaledInstance(80,95,Image.SCALE_SMOOTH);
imageIcon[i] = new ImageIcon(imageScaled[i]);
foodLabel[i] = new JLabel(imageIcon[i]);
}
Note that there seems to be no reason to keep all those values in an array. Unless you have more code that references those arrays the following is a bit cleaner:
for (int i = 0; i < ELEMENTS; i++) {
Image image = ImageIO.read(file[i]);
Image imageScaled = image.getScaledInstance(80,95,Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(imageScaled);
foodLabel[i] = new JLabel(imageIcon);
}

How can I access variables outside of loop in Java?

So I have my if statements to search a .txt file for the currency codes that correspond to the country the user types in. I store those country codes in Strings called 'from' and 'to'. I need to access the results of the if statements which are stored in the 'from' and 'to' variables to plug into something later. When I try to use these in the line way down at the end it says Cannot find symbol 'from' and Cannot find symbol 'to'. How can I fix this?
//all my imports here
public class ExchangeApp {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("Exchange App");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 2, 5, 3));
//GUI Elements
JLabel toLabel = new JLabel("To");
JTextField CurrencyTo = new JTextField(20);
JLabel fromLabel = new JLabel("From");
JTextField CurrencyFrom = new JTextField(20);
JLabel amountLabel = new JLabel("Amount");
JTextField AmountText = new JTextField(20);
JLabel displayLabel = new JLabel();
JLabel updateLabel = new JLabel();
JButton Calculate = new JButton("Calculate");
JButton Clear = new JButton("Clear");
//Add elements to panel
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(fromLabel);
panel.add(CurrencyFrom);
panel.add(toLabel);
panel.add(CurrencyTo);
panel.add(amountLabel);
panel.add(AmountText);
panel.add(Calculate);
panel.add(Clear);
panel.add(displayLabel);
panel.add(updateLabel);
//make visible
frame.add(panel);
frame.setVisible(true);
class calculateListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==Calculate){
String line, from, to;
String fromString = CurrencyFrom.getText();
String toString = CurrencyTo.getText();
double amount = Double.parseDouble(AmountText.getText());
try{
//import text file
File inputFile = new File("currency.txt");
//create file scanner
Scanner input = new Scanner(inputFile);
try{
//skip first line
input.nextLine();
//while has next line
while(input.hasNextLine()){
//set line equal to entire line
line = input.nextLine();
String[] countryArray = line.split("\t");
//search for from
if(fromString.equals(countryArray[0])){
//set 'from' equal to that country code
from = countryArray[2];
//testing
System.out.println(from);
}
//search for to
if(toString.equals(countryArray[0])){
//set 'to' equal to that country code
to = countryArray[2];
System.out.println(to);
}
else{
displayLabel.setText("To country not found");
}
}//while loop
}//2nd try
finally{input.close();}
}//1st try
catch(IOException exception){
System.out.println(exception);
}//catch bracket
}//if bracket ****these 2 variables****
String address = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to;
}//action bracket
}//class implements action listener bracket
ActionListener listener = new calculateListener();
Calculate.addActionListener(listener);
}//main bracket
}//class bracket

Stack Cards horizontally with some offset

How do I stack images (of cards) like this:
This is what I have so far and obviously I am trying to set the location of the JLabel cardIcon which gets replaced each time I guess.
JPanel tableMat = new JPanel();
for (CardSet card : playersHand) {
String path = dirPath + card.suit().toString()+"-"+card.rank().toString()+".gif";
File file = new File(path);
if (!file.exists()) {
System.out.println(path);
throw new IllegalArgumentException("file " + file + " does not exist");
} else {
BufferedImage icon = ImageIO.read(new File(file.getAbsolutePath()));
JLabel cardIcon = new JLabel(new ImageIcon(icon));
cardIcon.setLocation(300,300);
tableMat.add(cardIcon);
}
}
tableMat = new JPanel() initialises it with the default FlowLayout, so cardIcon.setLocation(300, 300) will be ignored - the layout manager will decide the position when tableMat.add(cardIcon) is called.
You need to remove the layout manager from tableMat, e.g. tableMat = new JPanel(null).
Of course, you also need to update the x co-ordinate to stagger them left-to-right.
See https://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
I ended up doing like this and it works well for me.
JLayeredPane tableMat = new JLayeredPane();
int i =0;
int x_offset = 15;
for (CardSet card : playersHand) {
String path = dirPath + card.suit().toString()+"-"+card.rank().toString()+".gif";
File file = new File(path);
if (!file.exists()) {
System.out.println(path);
throw new IllegalArgumentException("file " + file + " does not exist");
} else {
BufferedImage icon = ImageIO.read(new File(file.getAbsolutePath()));
JLabel cardIcon = new JLabel(new ImageIcon(icon));
cardIcon.setBounds(x_offset,20,300,300);
tableMat.add(cardIcon, new Integer(i));
i++;
x_offset += 15;
}
}
And hence the output is :

Display DICOM file on screen

I am having some trouble displaying a dicom file. I have tried many things to display the picture onto the frame but all it does is make an error which is "image is empty". Any suggestions would be appreciated. (I know that the image is not empty and that it is able to access the image from the laptop).
Thank you.
Here is my code (which is coded in java):
class Open{
public static void main(String s) throws IOException{
String [] array = s.split("/");
String k = array[0];
k+= "/";
k += array[1];
k+= "/";
k += array[2];
k+= "/";
k+= array[3];
k+= "/";
k+= array[4];
k+= "/";
System.out.println(k);
System.out.println(s.length());
if(s.length() == 0){
System.out.println("The path and filename are empty!");
System.exit(0);
}
File source = new File(k, array[5]);
final Image image = ImageIO.read(source);
//final BufferedImage image = ImageIO.read(new File(k, array[5]));
if(image == null){
System.out.println("The image is empty or can't be read!");
System.exit(0);
}
JFrame frame = new JFrame();
final Rectangle bounds = new Rectangle(0,0,240, 240);
JPanel panel = new JPanel();
//{
// public void paintComponent(Graphics g){
//// Rectangle box = g.getClipBounds();
//// ((Graphics2D)g).fill(box);
////
//// if(bounds.intersects(box)){
// g.drawImage(image,0,0,null);
//// }
// }
// };
JLabel b = new JLabel(new ImageIcon(image));
panel.add(b);
frame.getContentPane().add(panel);
panel.setPreferredSize(new Dimension(300, 300));
frame.pack();
frame.setVisible(true);
}
}
You can do it with PixelMed. The documentation is pretty much non-existent, but there are javadocs.
If you primarily intend to display the image, you should be able to use SourceImage and SingleImagePanel from the com.pixelmed.display package to load and display the image. If you want to parse DICOM attributes, you could start with one of the read methods in com.pixelmed.dicom.AttributeList.

How To Keep Size Of JTextArea constant?

I'm using an object of JTextArea in my application which deals with sending sms.
I've used a DocumentFilter so as to allow only 160 characters to be typed in the textarea but now, I want the size of the textarea to be constant. it goes on increasing if I keep writing on the same line without pressing 'enter' key or even when I keep on pressing only Enter key. I tried once using 'scrollbar' too but the problem remains same. Suggest me something over this. Below is my code. Please check it.
class Send_sms extends JPanel implements ActionListener,DocumentListener
{
JButton send;
JTextArea smst;
JLabel title,limit;
JPanel mainp,titlep,sendp,wrap,titlewrap,blankp1,blankp2,sendwrap;
JScrollPane scroll;
Border br,blackbr;
Boolean flag = false;
PlainDocument plane;
public static final int LINES = 4;
public static final int CHAR_PER_LINE = 40;
//character limit 160 for a sms
public Send_sms()
{
br = BorderFactory.createLineBorder(Color.RED);
blackbr = BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.DARK_GRAY,Color.GRAY);
setBorder(blackbr);
title = new JLabel("Enter the text you want to send!");
title.setFont(new Font("",Font.BOLD,17));
limit = new JLabel(""+charCount+" Characters");
smst = new JTextArea(LINES,CHAR_PER_LINE);
smst.setSize(100,100);
plane = (PlainDocument)smst.getDocument();
//adding DocumentSizeFilter 2 keep track of characters entered
plane.setDocumentFilter(new DocumentSizeFilter(charCount));
plane.addDocumentListener(this);
send = new JButton("Send");
send.setToolTipText("Click Here To Send SMS");
send.addActionListener(this);
//scroll = new JScrollPane(smst);
//scroll.setPreferredSize(new Dimension(200,200));
//scroll.setVerticalScrollBarPolicy(null);
//scroll.setHorizontalScrollBarPolicy(null);
smst.setBorder(br);
blankp1 = new JPanel();
blankp2 = new JPanel();
titlep = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlewrap = new JPanel(new GridLayout(2,1));
mainp = new JPanel(new BorderLayout());
sendwrap = new JPanel(new GridLayout(3,1));
sendp = new JPanel(new FlowLayout(FlowLayout.CENTER));
wrap = new JPanel(new BorderLayout());
titlep.add(title);
titlewrap.add(titlep);
titlewrap.add(blankp1);
sendp.add(send);
sendwrap.add(limit);
sendwrap.add(blankp2);
sendwrap.add(sendp);
wrap.add(smst,BorderLayout.CENTER);
mainp.add(titlewrap,BorderLayout.NORTH);
mainp.add(wrap,BorderLayout.CENTER);
mainp.add(sendwrap,BorderLayout.SOUTH);
add(mainp);
}
public void actionPerformed(ActionEvent e)
{
Vector<Vector<String>> info = new Vector<Vector<String>> ();
Vector<String> numbers = new Vector<String>();
if(e.getSource() == send)
{
//Call a function to send he message to all the clients using text
//charCount = 165;
String msg = smst.getText();
if(msg.length() == 0)
JOptionPane.showMessageDialog(null,"Please Enter Message","Error",JOptionPane.ERROR_MESSAGE);
else
{
// System.out.println("Message:"+msg);
Viewdata frame = new Viewdata(msg);
limit.setText(""+charCount+" Characters");
charCount = 160;
}
}
}
public void insertUpdate(DocumentEvent e)
{
System.out.println("The legth:(insert) "+e.getLength());
for(int i = 0;i<e.getLength(); i++)
{
if(charCount >0)
charCount--;
else
break;
}
limit.setText(""+charCount+" Characters");
}
public void removeUpdate(DocumentEvent e)
{
//System.out.println("The legth(remove): "+e.getLength());
for(int i = 0;i<e.getLength(); i++)
{
charCount++;
}
limit.setText(""+charCount+" Characters");
}
public void changedUpdate(DocumentEvent e)
{
//System.out.println("The legth(change): "+e.getLength());
}
}//end Send_sms
Sound like you are creating the text area using
JTextArea textArea = new JTextArea();
When using this format the text area doesn't have a preferred size so it keeps on growing. If you use:
JTextArea textArea = new JTextArea(2, 30);
JScrollPane scrollPane = new JScrollPane( textArea );
Then the text area will have a preferred size of 2 rows and (roughly) 30 columns. As you type when you exceed the preferred width the horizontal scrollbar will appear. Or if you turn on wrapping, then the text will wrap and a vertical scrollbar will appear.
you need to specify:
textArea.setColumns (160);
textArea.setLineWrap (true);
textArea.setWrapStyleWord (false); //default
But the real problem is that you allow to input more than 160 characters. You need to create some kind of validator which will skip all inputed characters when there are already 160 characters written.
Initialise the textArea with a document that extends PlainDocument and in the insertString method limit the characters to 160

Categories

Resources