display image in Java - java

I am working on a desktop application for windows version using java. In my application there is a requirement to display IMAGES from Path with a next and previous button.
For that I wrote a class to return all the paths of the images : I use ArrayList
import java.io.File;
import java.util.ArrayList;
public class RE {
private ArrayList<String> c =new ArrayList<String>();
public RE (String rep)
{
File src=new File(rep);
if(src!=null && src.exists() && src.isDirectory())
{
String[] tab=src.list();
if(tab!=null)
{
for(String s:tab)
{
File srcc=new File(rep+File.separatorChar+s);
if(srcc.isFile())
{
if(srcc.getName().matches(".*"+"png$")|| srcc.getName().matches(".*"+"jpg$") || srcc.getName().matches(".*"+"gif$"))
c.add(srcc.getPath());
}
}
}
}
}
public ArrayList<String> getAll()
{
return c;
}
}
and a class to display images, but I have some problems in ActionPerformed
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ListIterator;
import javax.swing.*;
public class swing extends JFrame implements ActionListener{
private RE c=new RE("H:\\photos\\g");
JTextField chemin=new JTextField(30);
JLabel lab;ImageIcon imageIcon;
JButton next =new JButton("NEXT");
JButton prev=new JButton("prev");
JPanel pan1=new JPanel();
JPanel pan2=new JPanel();
JPanel pan3=new JPanel();
swing()
{
imageIcon = new ImageIcon(c.getAll().get(2));
lab = new JLabel(imageIcon);
this.setLayout(new BorderLayout());
this.setVisible(true);
pan1.setLayout(new FlowLayout());
pan1.add(new JLabel("ENTREZ LE CHEMIN DE REPERTOIRE :"));
pan1.add(chemin);
pan2.setLayout(new FlowLayout());
pan2.add(lab);
pan3.setLayout(new FlowLayout());
next.addActionListener(this);
prev.addActionListener(this);
pan3.add(prev); pan3.add(next);
this.add(pan1,BorderLayout.NORTH);
this.add(pan2,BorderLayout.CENTER);
this.add(pan3,BorderLayout.SOUTH);
this.pack();
}
public static void main(String[] args){
new swing();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==next)
{
String cur=imageIcon.toString();
ListIterator<String> l=c.getAll().listIterator(c.getAll().indexOf(cur));
lab.setIcon(new ImageIcon(l.previous().toString()));
}
else
{
}
}
}
but I can't complete that :
public void actionPerformed(ActionEvent e) {
if(e.getSource()==next)
{
String cur=imageIcon.toString();
ListIterator<String> l=c.getAll().listIterator(c.getAll().indexOf(cur));
lab.setIcon(new ImageIcon(l.previous().toString()));
}
else
{
}
}

Use an appropriate layout manager. In this case, use CardLayout. This will make image swapping easier. Unless the number of images is absurdly large, then I highly recommend this approach.

Use your List<String> to construct a corresponding List<ImageIcon> and replace the label's icon as required. In this example, a JComboBox holds the current selection, and the buttons change the selection accordingly. Note that the indexes wrap around, forming a circular queue.

Related

How do I create an array of JTextField and retrieve the text from an array of String?

I am quite new to Java and learning as a student. I hope you can understand me.
As you can see from the code below, I've only coded the frame and the label. The user should be able to write some song recommendations. There should be at least a few text fields created by an array. When the user makes changes, the new text should be displayed using JOptionPane.WARNING_MESSAGE.
I need some guidance on how I can create an array of JTextField and retrieve the text from an array of String. In addition, how can I use JOptionPane to display all of the text?
Thank you.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
class TextFrame extends JFrame
{
private final JLabel cLabel;
public TextFrame()
{
super("Hello there!");
setLayout(new FlowLayout());
cLabel = new JLabel("Please write some song recommendations.");
cLabel.setToolTipText("Write below.");
add(cLabel);
}
}
public class TestFrame
{
public static void main (String [] args)
{
TextFrame frame = new TextFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setVisible(true);
}
}
You should make an actionListener that checks to see if you have typed anything. You could have another listener or Mnemonic so when you hit enter it will update everything. When you hit enter, you could get the text from the JTextField or JTextArea and then save that into an array of Strings (ie String[] stringArray = new String[<num of items>] This way you could just have one textField and you will be able to store everything in a String[] instead of an array of Text Fields? I hope this helps!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class framearray2 extends JFrame implements ActionListener
{
JCheckBox c1[];
JTextField t1[];
int i;
framearray2(String p)
{
super(p);
c1=new JCheckBox[2];
t1=new JTextField[2];
for(i=0;i<2;i++)
{
t1[i]=new JTextField(40);
c1[0]=new JCheckBox("Singing");
c1[0].setBackground(Color.red);
c1[1]=new JCheckBox("Cricket",true);
}
for(i=0;i<2;i++)
{
add(t1[i]);
add(c1[i]);
t1[i].addActionListener(this);
}
setLayout(new FlowLayout());
setFont(new Font("Arial",Font.ITALIC,40));
}
public void actionPerformed(ActionEvent e)
{
for(i=0;i<2;i++)
{
if(e.getSource().equals(t1[0]))
{
t1[0].setBackground(Color.red);
}
if(e.getSource().equals(t1[1]))
{
t1[1].setBackground(Color.blue);
}
}
}
public static void main(String s[])
{
framearray2 f1=new framearray2("hello");
f1.setSize(600,500);
f1.setVisible(true);
}
}

How to change `JTextArea` contents using `JTextArea` instance field?

I have an object ReminderGUI which has a JTextArea field. ReminderGUI represents an app which lets save and display reminders. When getReminderButton is clicked I want the app to find the reminder which was previously saved for this date and display it in the JTextArea (I'm not showing this functionality in the code snippet).
I'm having trouble with changing JTextArea text and the code below demonstrates it. Once getReminderButton is clicked then getReminderButtonHandler() is supposed to initialize a new blank JTextArea and then append it to some new text here. Why doesn't this work?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReminderGUI extends JFrame implements ActionListener{
private JButton getReminderButton;
private JTextArea reminderTextArea;
public ReminderGUI() {
super();
super.setLayout(new BorderLayout());
this.reminderTextArea = new JTextArea("Enter text");
this.getReminderButton = new JButton("Get reminder");
JPanel southPanel = new JPanel();
southPanel.add(getReminderButton, BorderLayout.SOUTH);
super.add(southPanel, BorderLayout.SOUTH);
super.add(reminderTextArea, BorderLayout.CENTER);
this.getReminderButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.getReminderButton) {
this.getReminderButtonHandler();
}
}
private void getReminderButtonHandler() {
this.reminderTextArea = new JTextArea("");
this.reminderTextArea.append("some new text here");
}
public static void main(String[] args) {
ReminderGUI rmg = new ReminderGUI();
rmg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rmg.setSize(500, 300);
rmg.setVisible(true);
}
}
The problem is in this line: this.reminderTextArea = new JTextArea("Enter text"); you're creating a new TextArea
You can set it using the set method, like this: reminderTextArea.setText(text);

I'm attempting to create a small GUI application, but the contents of the JFrame are not showing on screen. How can I fix my code?

As of late I've been developing a (very) small GUI application in Java. I'm extremely new to Swing and Java in general, but up until now I have been able to get everything to work the way I want it to. However, after cleaning up my code, when I run the program nothing but the border of the window appears. What am I doing wrong and how can I fix my code? Thanks ahead of time!
For the sake of saving space I've made Pastebin links to all of my classes (besides Main).
Main Class
package me.n3rdfall.ezserver.main;
public class Main {
public static GUI g = new GUI();
public static void main(String[] args) {
g.showWindow(800, 500);
}
}
GUI Class
http://pastebin.com/gDMipdp1
ButtonListener Class
http://pastebin.com/4XXm70AD
EDIT: It appears that calling removeAll() directly on 'frame' actually removed essential things other than what I had added. By calling removeAll() on getContentPane(), the issue was resolved.
Quick hack: Remove the removeAll() functions.
public void homePage() {
// frame.removeAll();
// mainpanel.removeAll();
// topbar.removeAll();
I'm not sure what you're trying to achieve, but that will at least show some items. If I were you I would rebuild this GUI by extending JFrame. It will make your code a little easier to read.
I also think what you are trying to achieve with the buttons is to switch layouts, you can do this in an easier way by using CardLayout
Example (has nothing to do with your code, but to demonstrate):
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends JFrame implements ActionListener {
private JButton leftButton;
private JButton rightButton;
private CardLayout cardLayout = new CardLayout();
JPanel cards = new JPanel(cardLayout);
final static String LEFTPANEL = "LEFTPANEL";
final static String RIGHTPANEL = "RIGHTPANEL";
JPanel card1;
JPanel card2;
public Example() {
JPanel topPanel = new JPanel();
addButtons(topPanel);
add(topPanel, BorderLayout.NORTH);
add(cards, BorderLayout.CENTER);
//Initiates the card panels
initCards();
setTitle("My Window");
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
private void initCards() {
card1 = new JPanel();
card2 = new JPanel();
card1.setBackground(Color.black);
card2.setBackground(Color.red);
cards.add(card1, LEFTPANEL);
cards.add(card2, RIGHTPANEL);
}
private void addButtons(Container con) {
leftButton = new JButton("Left Button");
leftButton.addActionListener(this);
rightButton = new JButton("Right Button");
rightButton.addActionListener(this);
con.add(leftButton, BorderLayout.WEST);
con.add(rightButton, BorderLayout.EAST);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(leftButton)) {
//Change cardlayout
cardLayout.show(cards, LEFTPANEL);
} else if(e.getSource().equals(rightButton)) {
//Change cardlayout
cardLayout.show(cards, RIGHTPANEL);
}
}
public static void main(String[] args) {
new Example();
}
}

How to display different components in a JFrame?

I am very new to Java AWT. My question header must seem ridiculous to you, sorry about that. In my application I have three buttons which display different threads when clicked on. Now I want to add maybe a button or checkboxes or choicelist, etc when clicked on a particular button. For eg, if I click on yes button, it should display a choice list, something like that. How do I achieve something like that? Here is my code so far:
import java.awt.Button;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class AppWindow extends Frame implements ActionListener{
String keymsg = "Test message";
String mousemsg = "Nothing";
int mouseX=30, mouseY=30;
String msg;
public AppWindow(){
//addKeyListener(new MyKeyAdapter(this));
//addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g){
g.drawString(msg, 150, 100);
}
//Here the window is created:
public static void main(String args[]){
AppWindow appwin = new AppWindow();
appwin.setSize(new Dimension(300,200));
appwin.setTitle("My first AWT Application");
appwin.setLayout(new FlowLayout(FlowLayout.LEFT));
appwin.setVisible(true);
Button yes,no,maybe;
yes = new Button("yes");
no = new Button("no");
maybe = new Button("maybe");
appwin.add(yes);
appwin.add(no);
appwin.add(maybe);
yes.addActionListener(appwin);
no.addActionListener(appwin);
maybe.addActionListener(appwin);
}
#Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
String str = ae.getActionCommand();
if(str.equals("yes")){
msg = "You pressed Yes";
}
if(str.equals("no")){
msg = "You pressed No";
}
if(str.equals("maybe")){
msg = "You pressed Maybe";
}
repaint();
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we){
System.exit(0);
}
}
Points describing what you should be doing :
As already mentioned by others, better to use Swing over AWT, since Swing is more advanced.
As much as possible, always try to Paint on top of a JPanel or a
JComponent, instead of Painting right on top of your JFrame, by
overriding the paintComponent(Graphics g) method of the said
JComponent/JPanel
Never call setVisible(true) on the JFrame until and unless it's
size has been established. So in general terms, this has to be the
last call, once you are done adding components to the JFrame and
the size of the JFrame has been realized by the LayoutManager.
Inside your actionPerformed(...), instead of writing all if
statement blocks, you should adhere to the if-else if statement
blocks. The benefit of this, over the former is that, at any given
time, only one event will be fired, hence once the said condition is
satisfied, you don't want your code to keep checking other
conditions, which in general is really not a good programming
practice, IMHO.
MOST IMPORTANT THING : Never make calls like pack()/setVisible(...) from within the main method, such calls belong
to the Event Dispatch Thread, and must be done on the same. Please
read Concurrency in Swing for more detail.
Have a look at the example program, for better understanding.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ComponentExample
{
private CustomPanel drawingBoard;
private JPanel contentPane;
private JButton yesButton;
private JButton noButton;
private JButton maybeButton;
private JComboBox cbox;
private ActionListener buttonAction = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (cbox.isShowing())
contentPane.remove(cbox);
if (button == yesButton)
{
drawingBoard.setText("You Pressed YES.");
contentPane.add(cbox, BorderLayout.PAGE_END);
}
else if (button == noButton)
drawingBoard.setText("You Pressed NO.");
else if (button == maybeButton)
drawingBoard.setText("You Pressed MAYBE.");
/*
* revalidate()/repaint() is needed
* when the JComponent is added or
* removed from the already
* visible Container.
*/
contentPane.revalidate();
contentPane.repaint();
}
};
public ComponentExample()
{
cbox = new JComboBox(
new String[]{"I GOT IT"
, "I STILL HAD DOUBT"});
}
private void displayGUI()
{
JFrame frame = new JFrame("Component Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(5, 5));
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.WHITE);
yesButton = new JButton("YES");
yesButton.addActionListener(buttonAction);
noButton = new JButton("NO");
noButton.addActionListener(buttonAction);
maybeButton = new JButton("MAY BE");
maybeButton.addActionListener(buttonAction);
buttonPanel.add(yesButton);
buttonPanel.add(noButton);
buttonPanel.add(maybeButton);
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
drawingBoard = new CustomPanel();
contentPane.add(drawingBoard, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ComponentExample().displayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
private String msg;
public CustomPanel()
{
msg = "";
setOpaque(true);
setBackground(Color.WHITE);
}
public void setText(String msg)
{
this.msg = msg;
repaint();
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(msg, getWidth() / 3, getHeight() / 3);
}
}
I don't know if I have understood the question well but... couldn't you create those elements and call their setVisible(boolean) methods to make them not visible at first, and them make them visible when user pushes buttons?

How to set the orientation of JTextArea from right to left (inside JOptionPane)

I have JScrollPane with JTextArea inside it and I am trying to set the JTextArea's orientation from right to left so the text inside it will start from the right and the scrollbar will be on the left
I've tried the following but they didn't affect the direction of the orientation:
txt.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setAlignmentX(JTextArea.RIGHT_ALIGNMENT);
EDIT:
the two answers camickr & trashgod provided work fine but not in my program where I use my JTextArea as an object Message and pass it to OptionPane.
EDIT2:
I figured out that setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); doesn't work if I apply it on the JOptionPane contents .. is there an alternative solution to this issue?
Similar to my code:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class TextArea extends JPanel
{
private JTextArea txt = new JTextArea();
public TextArea()
{
setLayout(new GridLayout());
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JScrollPane scroll = new JScrollPane(txt);
scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setPreferredSize(new Dimension(200,200));
this.add(scroll);
}
private void display()
{
Object[] options = {this};
JOptionPane pane = new JOptionPane();
int option = pane.showOptionDialog(null, null, "Title", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
public static void main(String[] args)
{
new TextArea().display();
}
}
and the scrollbar will be on the left
scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
so the text inside it will start from the right
textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
The text starts on the right side, but still gets append to the end as you type instead of being inserted at the beginning of the line.
Update:
I don't know why it doesn't work in an option pane. Here is a simple solution:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class Test
{
public static void main(String args[]) throws Exception
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTextArea textArea = new JTextArea(4, 20);
JScrollPane scrollPane = new JScrollPane( textArea );
JPanel panel = new JPanel();
panel.add( scrollPane );
scrollPane.addAncestorListener( new AncestorListener()
{
public void ancestorAdded(AncestorEvent e)
{
JScrollPane scrollPane = (JScrollPane)e.getComponent();
scrollPane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
public void ancestorMoved(AncestorEvent e) {}
public void ancestorRemoved(AncestorEvent e) {}
});
JOptionPane.showMessageDialog(null, panel);
}
});
}
}
This seems to work.
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/** #see http://stackoverflow.com/questions/6475320 */
public class RTLTextArea extends JPanel {
private static final String s = "مرحبا العالم";
private JTextArea jta = new JTextArea(7, 5);
private Locale arabic = new Locale("ar", "KW");
private ComponentOrientation arabicOrientation =
ComponentOrientation.getOrientation(arabic);
public RTLTextArea() {
this.setLayout(new GridLayout());
this.add(new JScrollPane(jta));
this.applyComponentOrientation(arabicOrientation);
for (int i = 0; i < 8; i++) {
jta.append(s + "\n");
}
}
private void display() {
JFrame f = new JFrame("RTLTextAre");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new RTLTextArea().display();
}
});
}
}
this line
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT)
change the correct order of the words.
i have this result
KBytes 80.78
The following lines solved my problem:
jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
jTextArea1.setText(<text>);
They serve to:
setComponentOrientation() changes the orientation of the TextArea; and,
setText() refreshes TextArea immediately so it displays properly
Simply setting ComponentOrientation to RIGHT_TO_LEFT is not sufficient by itself. repaint() doesn't force the text to realign itself. A quick solution for me was to update the contents of the TextArea. That forced the text to realign itself.

Categories