Using JComboBox with ActionListener in GUI - user-interface

I've just begun coding in Java and was wondering how to achieve this. What I want is for the user to be able to select what sub topic they would like to study, and then a new panel with text opens as the sub-topic is clicked. I've been trying everything i know but nothing seems to work. Any help would be appreciated. Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class FinalPanel extends JPanel {
private JLabel jcomp1;
private JComboBox jcomp2;
private JComboBox jcomp3;
private JComboBox jcomp4;
private JComboBox jcomp5;
private JLabel jcomp6;
public FinalPanel() {
//construct preComponents
String[] jcomp2Items = {"Introduction", "Summary ", "Terms"};
String[] jcomp3Items = {"Review Test"};
String[] jcomp4Items = {"Conversion Factors", "Calculations", "Problems a"};
String[] jcomp5Items = {"Limiting ", "Problems 1", "Percent Yield", "Problems 2",
"Energy Changes", "Problems 3", "Heat of Reaction", "Problems 4"};
//construct components
jcomp1 = new JLabel ("Welcome to the LifeSaving Chemistry Study guide!");
jcomp2 = new JComboBox (jcomp2Items);
jcomp3 = new JComboBox (jcomp3Items);
jcomp4 = new JComboBox (jcomp4Items);
jcomp5 = new JComboBox (jcomp5Items);
jcomp6 = new JLabel ("Stoichiometry");
//adjust size and set layout
setPreferredSize (new Dimension (644, 332));
setLayout (null);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
add (jcomp4);
add (jcomp5);
add (jcomp6);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (155, 20, 370, 20);
jcomp2.setBounds (90, 140, 175, 25);
jcomp3.setBounds (370, 205, 175, 30);
jcomp4.setBounds (90, 210, 175, 25);
jcomp5.setBounds (370, 140, 175, 25);
jcomp6.setBounds (265, 55, 100, 25);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new FinalPanel());
frame.pack();
frame.setVisible (true);
}
public void actionPerformed (ActionEvent e){
JFrame frame2 = new JFrame ("Clicked");
frame2.setVisible(true);
frame2.setSize(500,600);
JLabel label= new JLabel("Summary");
JLabel panel= new JLabel();
frame2.add(panel);
panel.add(label);
}
}

Related

Problem with ActionListener to give a buttona value

I'm trying to give a functions to an array of jbuttons with ActionListener
but when I pass 'i' as variable it gives erorr :
App.java:45: error: local variables referenced from an inner class must be final or effectively final
the error is on line 45, 58, and 71.
Here's the code :
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class App extends JFrame {
App(){
JFrame calcFrame = new JFrame();
calcFrame.setSize(320, 420);
calcFrame.setVisible(true);
calcFrame.setTitle("Calculator");
calcFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
calcFrame.setResizable(false);
calcFrame.getContentPane().setBackground(new Color(0x123456));
//add panel
JTextField textField = new JTextField();
textField.setBounds(35, 20, 200, 100);
textField.setBackground(new Color(0x000000));
calcFrame.add(textField);
JButton cbtn = new JButton(String.valueOf('c')); // clear button
cbtn.setBounds(240, 140, 50, 50);
calcFrame.add(cbtn);
JButton pbtn = new JButton(String.valueOf('^')); // power button
pbtn.setBounds(240, 200, 50, 50);
calcFrame.add(pbtn);
/*Add array of buttuns from 0 ... 9 */
JButton nums[] = new JButton[10];
calcFrame.getContentPane().setLayout(null);
// organzie using if statment
for(int i = 0; i < 4; i++)
{
nums[i] = new JButton(String.valueOf(i)); // organzie first line 0 ... 3
nums[i].setBounds(i * 60, 140, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
for(int i = 4, j = 0; i < 8; i++, j++)//organzie second line 4 ... 7
{
nums[i] = new JButton(String.valueOf(i));
nums[i].setBounds(j * 60, 200, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
for(int i = 8, j = 0; i < 10; i++, j++)//last numbers line 8 ... 9
{
nums[i] = new JButton(String.valueOf(i));
nums[i].setBounds(j * 60, 260, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
//End of numbers 0 ... 9
JButton dotbtn = new JButton();
JButton eqlbtn = new JButton();
dotbtn = new JButton(String.valueOf('.'));// dot button for a value less than 1
dotbtn.setBounds(120, 260, 50, 50);
calcFrame.add(dotbtn);
eqlbtn = new JButton(String.valueOf('=')); //equal button
eqlbtn.setBounds(180, 260, 50, 50);;
calcFrame.add(eqlbtn);
String[] arthmetictools = {"+", "-", "x", "/"};
JButton[] artbtns = new JButton[4]; // array of arthmetic buttons
for (int i = 0; i <= 4; i++) {
artbtns[i] = new JButton(String.valueOf(arthmetictools[i]));
artbtns[i].setBounds( 60 * i, 320, 50, 50);
calcFrame.add(artbtns[i]);
}
}
public static void main(String[] args) {
System.out.println("Hello, World!");
/* make the frame call it calc frame */
App calc = new App();
}
}
Thank you.
Tried to set text field to string of i from for loop.

Fill a text with JLabel entered by user

I am making a project that fill a text with information entered previously by a user.
For that, I am using the library JFrame.
So I have the form in the left of the panel and I want to put the filled text in the right when I click on the submit button.
My problem is that I don't undertand how to put the information in the right place of the text.
And for the moment the text doesn't appear at all in the frame on the click of the submit.
Can someone help me ?
Thanks a lot !
Here is my complete code :
public class LemurienAgileForm extends MainApplication {
public LemurienAgileForm(){
leLemurienAgileWindow();
}
public static void leLemurienAgileWindow() {
JFrame f = new JFrame("Le lémurien agile");
//set size of frame
f.setSize(1200, 1000);
f.setBackground(Color.black);
//make sure it quits when x is clicked
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel labelNameFP = new JLabel("Nom (f.pl) : ");
labelNameFP.setBounds(50, 50, 200, 30);
JTextField nameFP = new JTextField();
//set size of the text box
nameFP.setBounds(165, 50, 200, 30);
JLabel labelAdjectiveFP = new JLabel("Adj. (f.pl) : ");
labelAdjectiveFP.setBounds(50, 100, 200, 30);
JTextField adjectiveFP = new JTextField();
adjectiveFP.setBounds(165, 100, 200, 30);
JLabel labelNumber = new JLabel("Nombre : ");
labelNumber.setBounds(50, 150, 200, 30);
JTextField number = new JTextField();
number.setBounds(165, 150, 200, 30);
JButton submitButton = new JButton("Submit");
submitButton.setBounds(130, 720, 70, 50);
submitButton.setBackground(Color.black);
submitButton.setForeground(Color.white);
submitButton.setSize(150, 50);
submitButton.setFont(new Font("Times New Roman", Font.PLAIN, 25));
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JTextArea textArea = new JTextArea();
textArea.setText("Text " + labelAdjectiveMS.getText() + " Text");
JPanel panel = new JPanel();
panel.setBounds(300, 50, 400, 200);
panel.setBackground(Color.black);
panel.add(textArea);
}
});
//add elements to the frame
f.add(labelNameFP);
f.add(nameFP);
f.add(labelAdjectiveFP);
f.add(adjectiveFP);
f.add(labelNumber);
f.add(number);
f.add(submitButton);
f.setLayout(null);
f.setVisible(true);
}
}

How to create a custom dialog in installanywhere?

I want to know , how to create a custom dialog using installanywhere 2012. We are migrating our installer from installshiled to installanywhere. We have used alot of custom dialogs in installshiled. Now I need to change the same in IA 2013. I'm new to IA.
Please help me.
Thanks,
Thananjeyan
All the screens i n InstallAnywhere could be designed using Swings and AWT. You need to import and extend CustomCodePanel
Sample code is as below:
import com.zerog.ia.api.pub.CustomCodePanel;
import com.zerog.ia.api.pub.CustomCodePanelProxy;
import java.awt.*;
import java.util.Map;
import java.util.HashMap;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
public class JDBCParamsPanel extends CustomCodePanel{
private boolean inited = false;
private Font plainFont;
private Font boldFont;
private Map<String, TextField> varName2TextField = new HashMap<String, TextField>();
String databaseType = "";
#Override
public boolean setupUI(CustomCodePanelProxy customCodePanelProxy) {
if(!inited){
final String fontName = "Dialog";
LineBorder border = new LineBorder(Color.GRAY, 1, true);
final int fontSize = System.getProperty("os.name").contains("Windows") ? 12 : 8;
plainFont = new Font(fontName, Font.PLAIN, fontSize);
boldFont = new Font(fontName, Font.BOLD, fontSize);
setLayout(new BorderLayout(20, 1));
JTextArea topPrompt = new JTextArea(
"Please enter the following parameters that ABC will use\n"
+ "to connect to the database");
topPrompt.setRows(7);
topPrompt.setBorder(border);
databaseType = (String) customCodePanelProxy.getVariable("$DATABASE_TYPE$");
System.out.println("databaseType::: "+databaseType);
topPrompt.setEditable(false);
topPrompt.setFont(plainFont);
Panel topPanel = new Panel() {
public Insets getInsets() {
// return new Insets(10, 10, 10, 10);
return new Insets(7, 1, 4, 10);
}
};
topPanel.setSize(1, 50);
topPanel.setLayout(new BorderLayout());
topPanel.add(topPrompt, BorderLayout.CENTER);
add(topPanel, BorderLayout.NORTH);
Panel dataEntryPanel = new Panel();
add(dataEntryPanel, BorderLayout.CENTER);
dataEntryPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(5, 2, 8, 10);
gbc.fill = GridBagConstraints.BOTH;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.Host"), "$DB_HOST$", false, 100), gbc);
gbc.gridy = 1;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.Port"), "$DB_PORT$", false, 102), gbc);
gbc.gridy = 2;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.Database_Name"), "$DB_NAME$", false, 36), gbc);
gbc.gridy = 3;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.User"), "$DB_USER$", false, 99), gbc);
gbc.gridy = 4;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.Password"), "$DB_PASSWORD$", true, 68), gbc);
inited=true;
}
return true;
}
private Panel makeEntryPanel(String labelText, String varName, boolean useEchoChar, int hgap) {
Panel panel = new Panel(new BorderLayout(hgap, 1));
panel.add(makeStarLabel(labelText), BorderLayout.WEST);
TextField tf = new TextField();
tf.setFont(plainFont);
tf.setCaretPosition(Integer.MAX_VALUE);
if (useEchoChar) {
tf.setEchoChar('*');
}
panel.add(tf, BorderLayout.CENTER);
varName2TextField.put(varName, tf);
return panel;
}
private Label makeLabel(String text) {
Label label = new Label(text, Label.RIGHT);
label.setFont(boldFont);
return label;
}
private JLabel makeStarLabel(String text) {
JLabel label = new JLabel(text, Label.RIGHT);
label.setText("<html>" + text + "<font color=FF0000>*</font> </html>");
label.setFont(boldFont);
return label;
}
public String getTitle() {
return "JDBC Parameters";
}
#Override
public void panelIsDisplayed() {
populate("$DB_HOST$");
populate("$DB_PORT$");
populate("$DB_NAME$");
populate("$DB_USER$");
populate("$DB_PASSWORD$");
}
private void populate(String varName) {
TextField tf = varName2TextField.get(varName);
String value = (String) customCodePanelProxy.getVariable(varName);
tf.setText(value);
}
#Override
public boolean okToContinue() {
for (Map.Entry<String, TextField> entry : varName2TextField.entrySet()) {
String varName = entry.getKey();
TextField tf = entry.getValue();
String value = tf.getText().trim();
customCodePanelProxy.setVariable(varName, value);
}
return true;
}
}
The above code constructs a panel with 5 text input fields.
You can refer the above and write custom panels as per your requirement

Position of JLabel in Graphics when double buffering

I am using a thread to draw some animations, so I need to repaint the label for every frame. To do this without flickering I am updating the label with my backbuffer graphics object (using the lbl.update(bufferedGraphics); method), but when I do this, the label gets repainted in the top left of the Graphics object, and not where setLocation has specified.
How do I specify the location of the label within the graphics, instead of within the panel that owns the label?
Here is an SSCCE:
import javax.swing.*;
import java.awt.*;
public class LabelSSCCE extends JApplet implements Runnable {
JPanel pnl;
JLabel lbl;
Image buffer;
Graphics bufferedGraphics;
Thread t;
public void init (){
pnl = new JPanel (null);
lbl = new JLabel ();
lbl.setText ("Text");
lbl.setOpaque(true);
add(pnl);
pnl.add (lbl);
lbl.setLocation(100, 100);
lbl.setBounds (100, 100, 200, 20);
buffer = createImage (500, 500);
bufferedGraphics = buffer.getGraphics ();
t = new Thread (this, "Label");
t.start ();
}// init method
public void paint (Graphics g){
if (g != null)
g.drawImage (buffer, 0, 0, this);
}//paint
public void update (Graphics g){
paint (g);
}//update
public void render (){
bufferedGraphics.setColor (Color.WHITE);
bufferedGraphics.fillRect (0, 0, 500, 500);
lbl.update (bufferedGraphics);
update(getGraphics());
}//render
public void run (){
while (true){
try{
render ();
t.sleep (20);
} catch (InterruptedException e){
e.printStackTrace ();
}//catch
}//while
}//run
}//LabelSSCCE
First, convert the JLabel to a BufferedImage:
public BufferedImage componentToImage(Component component)
{
BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
Graphics g = img.getGraphics();
g.setColor(component.getForeground());
g.setFont(component.getFont());
component.paintAll(g);
Rectangle region = new Rectangle(0, 0, img.getWidth(), img.getHeight());
return img.getSubimage(region.x, region.y, region.width, region.height);
}
Then, change the render method to something like this:
public void render() {
bufferedGraphics.setColor(Color.WHITE);
bufferedGraphics.fillRect(0, 0, 500, 500);
BufferedImage bi = componentToImage(lbl);
bufferedGraphics.drawImage(bi, lbl.getX(), lbl.getY(), null);
update(getGraphics());
}

How to load background image into JPanel dynamically?

I have a swing gui application. I want to type into a image path and then click button to load the image into a jpanel. The problem is it won't be loaded, but if I add the extended jpanel which is able to load image when I instiate the jframe, image can be loaded normally. why is that?
code related:
package com.xdg.graphic;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImageLoader extends JPanel {
private String imgPath;
private BufferedImage image;
public ImageLoader(String imgPath) {
this.imgPath = imgPath;
try {
this.image=ImageIO.read(new File(imgPath));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
public Dimension getPreferredSize() {
if (image == null) {
return new Dimension(100,100);
} else {
return new Dimension(image.getWidth(null), image.getHeight(null));
}
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
}
invoker class:
package com.xdg.image;
import com.xdg.graphic.ImageLoader;
import sun.awt.windows.ThemeReader;
import java.awt.*;
public class FrmImgCropper extends javax.swing.JFrame {
private ImageLoader imageLoader;
/** Creates new form FrmImgCropper */
public FrmImgCropper() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
//GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
tfImagePath = new javax.swing.JTextField();
btnPreview = new javax.swing.JButton();
tfRatioW = new javax.swing.JTextField();
tfRatioH = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
btnLoad = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnPreview.setText("Preview");
jLabel1.setText(":");
btnLoad.setText("Load");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
jLabel2.setText("Image Path:");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
jPanel2Layout
.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(tfRatioW, javax.swing.GroupLayout.PREFERRED_SIZE, 55,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfRatioH, javax.swing.GroupLayout.PREFERRED_SIZE, 53,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 123,
Short.MAX_VALUE)
.addComponent(btnLoad, javax.swing.GroupLayout.PREFERRED_SIZE, 82,
javax.swing.GroupLayout.PREFERRED_SIZE).addGap(46, 46, 46)
.addComponent(btnPreview).addGap(276, 276, 276))
.addGroup(
jPanel2Layout.createSequentialGroup().addGap(66, 66, 66).addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfImagePath, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
.addGap(29, 29, 29)));
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
jPanel2Layout
.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addGroup(
jPanel2Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tfImagePath, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(
jPanel2Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tfRatioW, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tfRatioH, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnPreview).addComponent(btnLoad)).addGap(20, 20, 20)));
getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);
pack();
}// </editor-fold>
//GEN-END:initComponents
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {
if (imageLoader == null) {
imageLoader = new ImageLoader(tfImagePath.getText());
imageLoader.setBackground(Color.green);
getContentPane().add(imageLoader, BorderLayout.CENTER);
getContentPane().repaint();
this.repaint();//image does not show up this way dnamically
} else {
imageLoader.setImgPath(tfImagePath.getText());
imageLoader.repaint();
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FrmImgCropper cropper = new FrmImgCropper();
cropper.getContentPane().add(new ImageLoader("i:\\temp4\\car.jpg")); //if I add the image loader here directly,image shows up
cropper.setSize(800, 900);
cropper.setVisible(true);
}
});
}
//GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton btnLoad;
private javax.swing.JButton btnPreview;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField tfImagePath;
private javax.swing.JTextField tfRatioH;
private javax.swing.JTextField tfRatioW;
// End of variables declaration//GEN-END:variables
}
any ideas? I've been working on it two hours.
To update your panel you should call revalidate() method on panel's parent, not repaint() on the new panel since you change the content itself (the panel) but the image. In your case its content pane, which content should be validated.
But its still not the best way to update the image inside the panel if you ask me...
You can try this simple example (its much more simple and works perfectly):
private static BufferedImage image = null;
public static void main ( String[] args )
{
final JFrame imageFrame = new JFrame ();
imageFrame.setLayout ( new BorderLayout () );
final JPanel panel = new JPanel ()
{
protected void paintComponent ( Graphics g )
{
super.paintComponent ( g );
if ( image != null )
{
g.drawImage ( image, getWidth () / 2 - image.getWidth () / 2,
getHeight () / 2 - image.getHeight () / 2, this );
}
}
};
imageFrame.add ( panel, BorderLayout.CENTER );
imageFrame.add ( new JButton ( "Load image" )
{
{
addActionListener ( new ActionListener ()
{
public void actionPerformed ( ActionEvent e )
{
JFileChooser fc = new JFileChooser ();
fc.setDialogType ( JFileChooser.OPEN_DIALOG );
if ( fc.showOpenDialog ( imageFrame ) == JFileChooser.APPROVE_OPTION )
{
try
{
image = ImageIO.read ( fc.getSelectedFile () );
panel.repaint ();
}
catch ( IOException e1 )
{
//
}
}
}
} );
}
}, BorderLayout.SOUTH );
imageFrame.setSize ( 500, 500 );
imageFrame.setLocationRelativeTo ( null );
imageFrame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
imageFrame.setVisible ( true );
}
The only actual thing you need to do if you change the image inside panel - repaint the affected panel rect (or the whole panel if you don't like to get deep into the way graphics in Swing works).
As you can see i didn't even touch the panel itself - just changed the image source.

Resources