I am trying to create a function which can preview the image that the user selected from a customized JFileChooser. The following are the code snippets from the test frame and the customized JFileChooser.
Test.java
public class Test extends JFrame {
private JPanel contentPane;
private FileChooser file;
private static JLabel lblPicPreview;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Test() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("main menu");
setBounds(100, 100, 960, 540);
setLocationRelativeTo(null);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new FlowLayout(FlowLayout.LEADING));
lblPicPreview = new JLabel();
lblPicPreview.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
file.setPic();
}
});
lblPicPreview.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Preview", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
lblPicPreview.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblPicPreview.setToolTipText("Click to change profile picture");
file= new FileChooser();
contentPane.add(file);
contentPane.add(lblPicPreview);
}
// Method to update image
public static void updatePicture(ImageIcon icon){
lblPicPreview.setIcon(icon);
}
public void refresh(){
repaint();
revalidate();
}
}
FileChooser.java
public class FileChooser extends JPanel implements ActionListener {
/**
* Constructor FileChooser to place the UI for customized JFileChooser
*/
// actionPerformed for the "select" button in the custom UI
public void actionPerformed(ActionEvent e){
returnVal= fileChooser.showOpenDialog(button);
if(returnVal==JFileChooser.APPROVE_OPTION){
file= fileChooser.getSelectedFile();
fileLabel.setText(file.getAbsolutePath());
img= new ImageIcon(file.getAbsolutePath());
/** caller object to chg icon when user chooses new image
* i want to make this to update the image from its caller
* something like this
* {sourceLabel}.setIcon(img);
*/
Test.updatePicture(img);
}
}
}
The code works fine for the application. The problem is that i wish to make the customized JFileChooser to be reusable for all other frames/ classes. I want to make my custom JFileChooser smart enough to get any caller's class's JLabel (eg. lblPicPreview) to be updated with the chosen image instead of calling Test.java's lblPicPreview.setIcon() from the FileChooser class itself. This is done so that I can use FileChooser for other instances of frames/class.
One problem is that Test.java's lblPicPreview is an instance variable, so i cannot directly use it from FileChooser class.
All helps are appreciated. Thank you in advance.
Just add a method to specify the label to set:
public class FileChooser extends JPanel implements ActionListener {
protectedJLabel activeLabel;
public void setActivelabel( JLabel label ) {
activeLabel = label;
}
}
Related
I'm writing an application where I need to get two String objects from the GUI to the nullObject class.
I'm relatively new to programming, and am trying my best to learn. If you have any tips on how to make this better, I'd be really thankful!
My GUI class:
package com.giuly.jsoncreate;
public class GUI {
private JFrame startFrame;
private JFrame chkFrame;
private JFrame osFrame;
private JFrame appVFrame;
private JPanel controlPanel;
private JButton nextPage;
private JButton cancel;
private JButton save;
public GUI() {
generateGUI();
}
public static void main(String[]args) {
GUI gui = new GUI();
}
public void generateGUI() {
//Creation of the First Frame
startFrame = new JFrame("JSCON Creator");
startFrame.setSize(1000, 700);
startFrame.setLayout(new FlowLayout());
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Panel Creation
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//Button Creation
cancel = new JButton("Cancel");
cancel.setSize(100, 100);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
nextPage = new JButton("Next");
nextPage.setSize(100, 100);
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFrame.setVisible(false);
showText();
}
});
startFrame.add(controlPanel);
startFrame.add(cancel);
startFrame.add(nextPage);
startFrame.setVisible(true);
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void showText() {
JFrame textFrame = new JFrame();
textFrame.setSize(1000, 700);
textFrame.setTitle("Text");
textFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel textPanel = new JPanel();
JLabel titleLabel = new JLabel("Title");
textPanel.add(titleLabel);
JLabel descrLabel = new JLabel("Description");
JTextField tfTitle = new JTextField("",15);
tfTitle.setForeground(Color.BLACK);
tfTitle.setBackground(Color.WHITE);
JTextField tfDescr = new JTextField("",30);
tfDescr.setForeground(Color.BLACK);
tfDescr.setBackground(Color.WHITE);
textPanel.add(tfTitle);
textPanel.add(descrLabel);
textPanel.add(tfDescr);
JButton buttonOK = new JButton("OK");
textPanel.add(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jsonTitle = tfTitle.getText();
String jsonDescr = tfDescr.getText();
System.exit(0);
}
});
textFrame.add(textPanel);
textFrame.setVisible(true);
}
I want to get the Strings jsonTitle and jsonDescr into another class, so I can store them. In the end I will have some Strings and I need to save them in a JSON file. I need a way to get those two Strings, what advice do you guys have?
Erick is correct with his answer. Just thought I should add additional info. If you declare jstonTitle and jsonDescr like your other fields using private you still will not be able to access these fields from another class. Coding up a getter for the fields along with declaring them at the top of GUI should solve your problem. Then just create an instance of GUI in your other class and call the method.
public String getJsonTitle(){
return this.jsonTitle;
}
You're declaring jstonTitle and jsonDescr inside the actionPerformed() method. That means that as soon as actionPerformed() exits you'll lose those variables. You need to declare them in an enclosing context. For example, you could make them fields on the GUI class. Still assign them in actionPerformed(), but declare them up at the top of GUI where you're declaring startFrame, chkFrame, etc.
That will give you the ability to access those values from anywhere within GUI.
Oh, BTW, get rid of System.exit(0);. (Have you actually tried to run your program?)
I want to change the JPanel of a JFrame, using the CardLayout class.
I have already run this example and it works.
Now I want to use as action listener, the JMenuItem; so If I press that JMenuItem, I want to change it, with a specific panel. So this is the JFrame:
public class FantaFrame extends JFrame implements Observer {
private static final long serialVersionUID = 1L;
private JPanel cardPanel = new JPanel();
private CardLayout cardLayout = new CardLayout();
public FantaFrame(HashMap<String, JPanel> fantaPanels) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("FantaCalcio App");
setSize(500, 500);
cardPanel.setLayout(cardLayout);
setPanels(fantaPanels);
}
public void update(Observable o, Object arg) {
cardLayout.show(cardPanel, arg.toString());
}
private void setPanels(HashMap<String, JPanel> fantaPanels) {
for (String name : fantaPanels.keySet()) {
cardPanel.add(fantaPanels.get(name), name);
}
}
}
Those are the Menu, the Controller and the Main:
private void pressed(){
home.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
controller.changePanel(home.getText());
}
});
}
public class Controller extends Observable {
public void changePanel(String panel){
setChanged();
notifyObservers(panel);
}
}
public static void main(String[] args) {
fantaPanels.put("Login", new LoginPanel());
Controller controller = new Controller();
MenuBarApp menuApp = new MenuBarApp(controller);
FantaFrame frame = new FantaFrame(fantaPanels);
frame.setJMenuBar(menuApp);
controller.addObserver(frame);
frame.setVisible(true);
}
The problem is that the JPanel doesn't change. What do you think is the problem ?
I've already debugged it, and in the update() method, the correct String value arrives.
You never add the cardPanel JPanel, the one using the CardLayout and displaying the "cards" to anything. You need to add it to your JFrame's contentPane for it to display anything. i.e.,
public FantaFrame(HashMap<String, JPanel> fantaPanels) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("FantaCalcio App");
setSize(500, 500);
cardPanel.setLayout(cardLayout);
add(cardPanel, BorderLayout.CENTER); // ****** add this line ******
setPanels(fantaPanels);
}
Code in Question
There isn't an actionListener for the image thumbnails, yet when clicked they update the image.
From this webpage.
Edit: I am currently importing images using JFileChooser and then creating a thumbnail and displaying the full image in a similar way to this, although not using ImageIcons. But would like to use this method so when I add an image it adds to the list and allows me to click the thumbnail to show that image.
However mine using actionListeners to change when something is pressed but this doesn't and can't understand the code where it does.
Thanks
Edit2:
Regarding the repaint option:
I have a class which extends component which then calls a repaint function.
public class Image extends Component {
private BufferedImage img;
//Print Image
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
I then have a class with all my Swing components which call methods from other classes.
Image importedImage = new Image(loadimageone.openFile());
Image scaledImage = new Image();
// Save image in Buffered Image array
images.add(importedImage.getImg());
// Display image
imagePanel.removeAll();
imagePanel.add(importedImage);
imagePanel.revalidate();
imagePanel.repaint();
previewPanel.add(scaledImage);
previewPanel.revalidate();
previewPanel.repaint();
If I remove the revalidate or repaint it wont' update the image on the screen.
Edit 3:
This is the code on how I implemented the dynamic buttons:
//Create thumbnail
private void createThumbnail(ImpImage image){
Algorithms a = new Algorithms();
ImpImage thumb = new ImpImage();
//Create Thumbnail
thumb.setImg(a.shrinkImage(image.getImg(), 75, 75));
//Create ImageIcon
ImageIcon icon = new ImageIcon(thumb.getImg());
//Create JButton
JButton iconButton = new JButton(icon);
//Create ActionListener
iconButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bottomBarLabel.setText("Clicked");
imagePanel.removeAll();
imagePanel.add(images.get(position)); //Needs Fixing
imagePanel.revalidate();
}
});
//Add to previewPanel
previewPanel.add(iconButton);
previewPanel.revalidate();
previewPanel.repaint();
}
It looks like it uses ThumbnailAction instead which extends AbstractAction (at the very bottom of the code). Swing components can use Actions instead of ActionListeners. The advantage of Actions is that buttons can share an Action and they will automatically use the same key-bindings etc.
http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
EDIT: I have added some code demonstrating that you do not need to explicitly repaint(). Give it a try.
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(2, 1));
final JLabel iconLabel = new JLabel();
JButton button = new JButton("Put Image");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
iconLabel.setIcon(new ImageIcon(ImageIO.read(fc.getSelectedFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
panel.add(iconLabel);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
EDIT 2 (There is no Edit 2)
EDIT 3: Try this
public class MyActionListener implements ActionListener {
private JPanel imagePanel;
private Image image;
public MyActionListener(JPanel imagePanel, Image image) {
this.imagePanel = imagePanel;
this.image = image;
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Clicked");
imagePanel.removeAll();
imagePanel.add(image); //Needs Fixing
imagePanel.revalidate();
}
}
I tried codes from different site's and one from here about a color. How do I get color chooser to work with the press of a jmenu item?
I looked at ColorChooser Example and also Oracle Color Chooser Example and then implementing into the original class using the following code:
JMenuItem clr = new JMenuItem("Font Color");
clr.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
ColorChooserDemo ccd = new ColorChooserDemo();
ccd.setVisible(true);
}
});
But this seems do do nothing when I press the menu item.
The class code is from the oracle webpage. These are the following class I use (shortened of course to the problem at hand). I'm making a notepad program as i'm getting back into programming and refreshing my memory of how to do things in java. Problem at hand is, I am unable to get the color chooser to come up when I click on the jmenuitem clr (which is font color) the following code show's what I have so far:
Color Chooser Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
/* ColorChooserDemo.java requires no other files. */
#SuppressWarnings("serial")
public class ColorChooserDemo extends JPanel
implements ChangeListener {
protected JColorChooser tcc;
protected JLabel banner;
public ColorChooserDemo() {
super(new BorderLayout());
//Set up color chooser for setting text color
tcc = new JColorChooser();
tcc.getSelectionModel().addChangeListener(this);
tcc.setBorder(BorderFactory.createTitledBorder(
"Choose Text Color"));
add(tcc, BorderLayout.PAGE_END);
}
public void stateChanged(ChangeEvent e) {
Color newColor = tcc.getColor();
FirstWindow.ta1.setForeground(newColor);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ColorChooserDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ColorChooserDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Main Class:
import java.awt.EventQueue;
public class Main{
protected static Object fw;
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try
{
FirstWindow fw = new FirstWindow();
fw.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}
FirstWindow class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class FirstWindow extends JFrame {
private static final long serialVersionUID = 1L;
protected JColorChooser tcc;
protected static JTextArea ta1;
public FirstWindow() {
super("Note Pad");
Font font = new Font("Verdana", Font.BOLD, 12);
//Setting the size of the note pad
setSize(650, 745);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Create the MenuBar
JMenuBar mb = new JMenuBar();
setJMenuBar(mb);
//Create the panel to hold everything in
JPanel p = new JPanel();
//Create the Text Area
final JTextArea ta1 = new JTextArea();
ta1.setFont(font);
ta1.setMargin(new Insets(5,5,5,5));
ta1.setLineWrap(true);
ta1.setWrapStyleWord(true);
//Create the Scroll Pane to hold the Text Area
final JScrollPane sp = new JScrollPane(ta1);
sp.setPreferredSize(new Dimension(625,675));
sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
//Create the menu's
JMenu format = new JMenu("Format");
//Create menu item for picking font color
JMenuItem clr = new JMenuItem("Font Color");
clr.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
ColorChooserDemo ccd = new ColorChooserDemo();
ccd.setVisible(true);
}
});
//adding the menu items to the file menu tab
//adding menu items to the edit tab
//adding menu items to the format tab
format.add(clr);
//adding the menus to the menu bar
mb.add(format);
//adding the scroll pane to the panel
p.add(sp);
add(p, BorderLayout.CENTER);
}
}
Probably the easiest way to show the ColorChooser is the following:
In the ColorChooserDemo class, you have the method private static void createAndShowGUI(), which you should declare public.
Then, replace the ActionListener for the menu item to the following:
clr.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
ColorChooserDemo.createAndShowGUI();
}
});
Your ColorChooserDemo class extends JPanel, not JFrame. You first need a JFrame, then add the panel, then show the JFrame. This is what happens in the createAndShowGUI() method.
Edit:
I understood that you only wanted to know how to show the ColorChooserDemo when selecting a menu item.
However, to actually set the color, you might want to skip using your own ColorChooserDemo class, and replace the ActionListener code with the following:
clr.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Color c = JColorChooser.showDialog(ta1, "ColorChooserDemo", null);
ta1.setForeground(c);
}
});
An SSCE is easier not only for us to provide a solution, as Andrew suggested, but it may also help you figure out and understand what to do. Anyway, here's a quick example of opening a colour chooser after pressing a JMenuItem:
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JColorChooser jColorChooser = new JColorChooser();
JDialog jDialog = new JDialog();
jDialog.setContentPane(jColorChooser);
jDialog.pack();
jDialog.setVisible(true);
}
});
LE: (sorry, new to colour choosers myself) or just use JColorChooser.showDialog()
I have a class that reads an excelfile and creates frame with a graph inside a jpanel. I invoke this class through an actionlistener in a jmenuitem. Then I have another jmenuitem that invokes the same class that opens the same file, but reads a different excel sheet, and gives a different graph (thats the only string that changes in the class). The jmenubar that has these jmenitems belong to a jframe from which the program starts. I would like to know if it is possible every time I click the jmenuitems that create the graphs to be added in a new jframe cardlayout, so that I can roll on them. Thanks in advance
This is the code I am currently using to open a graph in a jframe when the jmenuitem is clicked:
public class startup extends JFrame { // creates a jframe with some stuff and the jmenubar
public void menu() {
...
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event2) {
new Thread(new Runnable() {
#Override
public void run() {
new ReadExcel();
ReadExcel.excel(".xls", 0); // this jmenuitem invokes the class to read the excelfile sheet 0
graphgen.main(null);
}
}).start();
}
});
subsubmenu1.add(menuItem);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event2) {
new Thread(new Runnable() {
#Override
public void run() {
new ReadExcel();
ReadExcel.excel(".xls", 1); // this jmenuitem invokes the class to read the excelfile sheet 1
graphgen.main(null);
}
}).start();
}
});
subsubmenu1.add(menuItem);
....
}
public static void main(String[] args)
{
GUIquery frame = new GUIquery();
p.add(graphComponent, BorderLayout.CENTER);
frame.setLayout(new BorderLayout());
frame.add(p, BorderLayout.CENTER);
frame.setJMenuBar(GUIquery.createMenuBar());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setSize(1600, 1200);
frame.setVisible(true);
}
}
The readexcel class just reads an excelsheet of an excelfile and returns some arraylist which are processed in the graphgen class.
public class graphgen extends JFrame {
public graphgen() {
super("Results");
gen();
}
public void gen(){
//creates the graphcomponent
getContentPane().add(graphComponent);
add(graphComponent);
}
public static void main(String[] args)
{
graphgen frame = new graphgen();
p2.add(graphComponent, BorderLayout.CENTER);
frame.add(p2, BorderLayout.CENTER);
frame.pack();
frame.setResizable(true);
frame.setSize(1600, 1200);
frame.setVisible(true);
}
Use Action to encapsulate the target component, file and sheet, as shown here and here. Add a method to update state of the class based on the chosen sheet. Examples of navigating among cards are seen here and here. See also Card Layout Actions, cited here.