Adding Image to JPanel inside JFrame with multiple panels - java

I added my image straight onto the jframe but then if i add another panel the image disappears,
i have tried to add image to a label and added this to a panel but this doesn't work either here is my code used to get my image:
here is my updated program:
public class imgload extends JFrame implements ActionListener {
private JButton b1;
public imgload() {
makeframe();
}
public void makeframe() {
JFrame f = new JFrame();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JLabel lb = new JLabel();
b1 = new JButton("Confirm");
b1.addActionListener(this);
JTextArea q1 = new JTextArea();
ImageIcon icon = createImageIcon("sample.jpg");
lb.setIcon(icon);
q1.setLocation(10,10);
q1.setSize(50,50);
p2.add(q1);
b1.setLocation(100,105);
b1.setSize(80,30);
p2.add(b1);
f.add(p1.add(lb));
// f.add(p2);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,600);
f.setAlwaysOnTop(true);
f.setResizable(false);
}
public ImageIcon createImageIcon(String path) {
URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b1) {
System.exit(0);
}
}
public static void main(String[] args) {
new imgload();
}
}

You need to look into using layouts (BorderLayout, FlowLayout, GridLayout, GridBagLayout, etc) in Swing. By default, most things have a BorderLayout, and when you use add with no arguments, it places the item in the center. Subsequent calls just replace the item in the center.

Related

Button not displaying frame connected to it

I am trying to write code for an application I'm making, I have my main frame with 6 buttons on them. When I push one of my buttons, it is meant to bring up a frame that has a tabbed layout set up.
I have the tabbed frame coded correctly and when I set each frame as visible they will appear to screen but they don't appear when the button is pushed.
I have action listeners connected to the buttons and the frames I want to connect with them as well as constructors but for some reason I can't get my code to work correctly.
I have added my driver and my first two forms I'm trying to connect to each other.
public class SimpsonsDriver {
//#param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame simpsonFrame = new JFrame("The Simpson");
JFrame homerFrame = new JFrame ("Homer Simpson");
JFrame margeFrame = new JFrame ("Marge Simpson");
JFrame bartFrame = new JFrame ("Bart Simpson");
JFrame lisaFrame = new JFrame("Lisa Simpson");
JFrame maggieFrame = new JFrame("Maggie Simpson");
SimpsonForm simpsonForm = new SimpsonForm(simpsonFrame, homerFrame, margeFrame, bartFrame,
lisaFrame, maggieFrame);
HomerForm homerForm = new HomerForm(homerFrame, simpsonFrame);
MargeForm margeForm = new MargeForm(margeFrame, simpsonFrame);
BartForm bartForm = new BartForm(bartFrame, simpsonFrame);
LisaForm lisaForm = new LisaForm(lisaFrame, simpsonFrame);
MaggieForm maggieForm = new MaggieForm(maggieFrame, simpsonFrame);
}
}
public class SimpsonForm implements ActionListener{
JFrame simpsonFrame, homerFrame, margeFrame, bartFrame, lisaFrame, maggieFrame;//instance variables
JButton homerBtn, margeBtn, bartBtn, lisaBtn, maggieBtn, closeBtn; //instance variables
public SimpsonForm(JFrame simpsonFrame, JFrame homerFrame, JFrame margeFrame, JFrame bartFrame, JFrame lisaFrame, JFrame maggieFrame) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
this.margeFrame = margeFrame;
this.bartFrame = bartFrame;
this.lisaFrame = lisaFrame;
this.maggieFrame = maggieFrame;
simpsonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createPanel();
}//end constructor method SimpsonForm
private void createPanel(){
homerBtn = new JButton ("Homer");
margeBtn = new JButton ("Marge");
bartBtn = new JButton ("Bart");
lisaBtn = new JButton ("Lisa");
maggieBtn = new JButton ("Maggie");
closeBtn = new JButton ("Close");
FlowLayout flow = new FlowLayout();
JPanel p1 = new JPanel();
p1.setLayout(flow);
JPanel p2 = new JPanel();
p2.setLayout(flow);
ImageIcon img = new ImageIcon(this.getClass().getResource("simpsons.png"));
JLabel imgLabel = new JLabel();
imgLabel.setIcon(img);
imgLabel.setBounds(10, 10, img.getIconWidth(), img.getIconHeight());
p1.add(imgLabel);
p2.add(homerBtn);
homerBtn.addActionListener(this);
p2.add(margeBtn);
margeBtn.addActionListener(this);
p2.add(bartBtn);
bartBtn.addActionListener(this);
p2.add(lisaBtn);
lisaBtn.addActionListener(this);
p2.add(maggieBtn);
maggieBtn.addActionListener(this);
p2.add(closeBtn);
closeBtn.addActionListener(this);
simpsonFrame.setLayout(new BorderLayout());
simpsonFrame.setResizable(false);
simpsonFrame.add(p1, BorderLayout.BEFORE_FIRST_LINE);
simpsonFrame.add(p2, BorderLayout.CENTER);
simpsonFrame.setSize(425, 425);
simpsonFrame.setLocationRelativeTo(null);
simpsonFrame.setVisible(true);
}//end method createPanel
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == homerBtn) {
homerFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == margeBtn) {
margeFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == bartBtn) {
bartFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == lisaBtn) {
lisaFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == maggieBtn) {
maggieFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == closeBtn) {
System.exit(0);
}//end if
}//end event handler
}
public class HomerForm implements ActionListener{
JFrame simpsonFrame, homerFrame;
JButton closeBtn;
public HomerForm(JFrame simpsonFrame, JFrame homerFrame ) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
createPanel();
}
private void createPanel() {
homerFrame = new JFrame("Homer Simpson");
closeBtn = new JButton("Close");
closeBtn.setSize(200, 50);
ImageIcon ogImage = new ImageIcon(this.getClass().getResource("/homer1.png"));
JLabel ogLabel = new JLabel();
ogLabel.setIcon(ogImage);
JPanel p1 = new JPanel();
p1.add(ogLabel);
ImageIcon hwImage = new ImageIcon(this.getClass().getResource("/homer2.png"));
JLabel hwLabel = new JLabel();
hwLabel.setIcon(hwImage);
JPanel p2 = new JPanel();
p2.add(hwLabel);
ImageIcon cImage = new ImageIcon(this.getClass().getResource("/homer3.png"));
JLabel cLabel = new JLabel();
cLabel.setIcon(cImage);
JPanel p3 = new JPanel();
p3.add(cLabel);
JPanel p4 = new JPanel();
JTabbedPane tab = new JTabbedPane();
tab.setBounds(100, 100, 300, 300);
tab.add("Original", p1);
tab.add("HalfWay", p2);
tab.add("Current", p3);
tab.add("Close", p4);
p4.add(closeBtn);
closeBtn.setLayout(new BorderLayout());
closeBtn.addActionListener(this);
homerFrame.add(tab);
homerFrame.setResizable(false);
homerFrame.setSize(500, 500);
homerFrame.setLocationRelativeTo(null);
homerFrame.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == closeBtn) {
homerFrame.setVisible(false);
simpsonFrame.setVisible(true);
}//end if
else
{
System.exit(0);
}
}
}
When i run it, i get this image. simpsonsFrame
this is what happens when i click the homer button i then have to max it to see a blank screen.homerFrame.
when i set the homerFrame to visible, it displays what i what to appear if the button was pushed.it shows homerFrame then it shows the simpsonFrame.homersetVisible true

Making an applet

I have the problem that I am not getting my results, why?
public class cycle extends JApplet implements ActionListener {
Panel panel = new Panel();
JButton left = new JButton("left");
JButton right = new JButton("right");
Container c = getContentPane();
public void frame() {
Panel panel = new Panel();
JButton left = new JButton("left");
JButton right = new JButton("right");
c.add(left);
c.add(right);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setTitle("Move the ball");
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Change your code this way:
Add the Buttons to your JPanel
Add the Panel to the ContentPane
Add your cycle object to the JFrame
Here is the modified code
public class cycle extends JApplet implements ActionListener {
private JPanel panel;
private JButton left;
private JButton right;
private Container c = getContentPane();
public cycle() {
panel = new JPanel();
left = new JButton("left");
right = new JButton("right");
panel.add(left);
panel.add(right);
c.add(panel);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setTitle("Move the ball");
f.setSize(500, 500);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.add(new cycle());
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Also:
I would suggest you rename your class Cycle, it is a Java convention to start with an upper case.
Use WindowConstants.EXIT_ON_CLOSE instead of JFrame.EXIT_ON_CLOSE
As suggested below in the comments by Andrew Thompson: Don't mix Swing & AWT components. (The Panel should be a JPanel)

Bar Chart from different class in to GUI class

I have Gui class with a JPanel and JButton. When the button is clicked i would like to display the graph in my JPanel. The Graph is in different class. Can someone help me do this please?
GUI CLASS:
public class Gui extends JFrame implements ActionListener{
JButton showGraph;
public Gui() {
super("GUI");
setSize(1200,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
showGraph = new JButton("SHOW GRAPH");
JPanel mainPanel = new JPanel();
add(mainPanel);
mainPanel.setLayout(new GridLayout(2,0,10,10));
mainPanel.setBorder(new EmptyBorder(10,10,10,10));
mainPanel.add(showGraph);
JPanel graphPanel = new JPanel();
graphPanel.setBackground(Color.yellow);
mainPanel.add(graphPanel);
showGraph.addActionListener(this);
}
public static void main (String[] args){
new Gui().setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showGraph) {
SimpleBarChart b = new SimpleBarChart();
b.getGraph();
}
}
}
Change your getGraph() method to take a JFrame and pass in this.
public void getgraph(JFrame f) {
//JFrame f = new JFrame();
f.setSize(400, 300);
... as before ...
}
Then call in actionPerformed
if (e.getSource() == showGraph) {
SimpleBarChart b = new SimpleBarChart();
b.getGraph(this);
}
You can't have a frame inside a frame. Another option would be to make getGraph() return a JPanel and then you could put the panel in your existing frame instead of updating the whole frame.

Working with JFrames

hi I'm basically give up. Ok so this is what I am trying to do. So far I have written code to create a JFrame which contains a text field and combo box. The code is supposed to calculate the area of an input in the text field depending on what shape is selected from the combo box and output the result on the JFrame!
Here's is what the output should look like
And here is my code so far. it's a bit messed up but any help would be much appreciated. Thanks in advance
import javax.swing. *;
import java.awt.event. *;
import java.awt.FlowLayout;
import java.lang.Math;
public class AreaFrame3 extends JFrame
{
double Area;
double input;
public static void main(String[]args)
{
//Create array containing shapes
String[] shapes ={"(no shape selected)","Circle","Equilateral Triangle","Square"};
//Use combobox to create drop down menu
JComboBox comboBox=new JComboBox(shapes);
JLabel label1 = new JLabel("Select shape:");
JPanel panel1 = new JPanel(new FlowLayout()); //set frame layout
JLabel label2 = new JLabel("(select shape first)");
JTextField text = new JTextField(10); //create text field
text.setEnabled(false);
panel1.add(label1);
panel1.add(comboBox);
panel1.add(label2);
panel1.add(text);
JFrame frame=new JFrame("Area Calculator Window");//create a JFrame to put combobox
frame.setLayout(new FlowLayout()); //set layout
frame.add(panel1);
frame.add(text);
//JButton button = new JButton("GO"); //create GO button
//frame.add(button);
//set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
//set JFrame ssize
frame.setSize(400,250);
//make JFrame visible. So we can see it
frame.setVisible(true);
// public void actionPerformed(ActionEvent e)
//{
}
public void AreaCalc()
{
JButton button = new JButton("GO"); //create GO button
frame.add(button);
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
int input = double.parseDouble(text.getText());
if(e.getSource() == button)
{
String shape = (String).comboBox.getSelectedItem();
if(shape == "(no shape selected)")
{
text.setEnabled(false);
}
else{
text.setEnabled(true);
}
if(input > 1 && shape == "Circle")
{
// label2.getText() = "Enter the radius of the circle: ";
Area = (Math.PI * (input * input));
}
}
else{}
}
}
);
}
}
I try to understand what you did here:
panel1.add(label1);
panel1.add(comboBox);
panel1.add(label2);
panel1.add(text); // <---
JFrame frame=new JFrame("Area Calculator Window");//create a JFrame to put combobox
frame.setLayout(new FlowLayout()); //set layout
frame.add(panel1);
frame.add(text); // <---
Especially frame.add(text); and panel1.add(text);. Don't add text to JFrame. Use JPanel.
Further,
public class AreaFrame3 extends Frame
Use public class AreaFrame3 extends JFrame so you don't need create additional JFrame:
JFrame frame=new JFrame("Area Calculator Window");
Something like:
super.setLayout(new FlowLayout()); //set layout
super.add(panel1);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.pack();
//set JFrame ssize
super.setSize(400,250);
//make JFrame visible. So we can see it
super.setVisible(true);
At last Ill give you some tamplate to start with (that will help you):
public class FrameExmpl extends JFrame{
private static final long serialVersionUID = 1L;
private JTabbedPane tabbedPane;
private JPanel topPanel;
private JTextField txtf_loadDS_;
public static int valueInt = 0; // responsible for Task status updating
public static Boolean isFinish = false;
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
FrameExmpl UI_L = new FrameExmpl();
UI_L.buildGUI();
UI_L.setVisible(true);
}
public void buildGUI(){
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
setSize(435, 225);
setLocation(285, 105);
setResizable(false);
topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
txtf_loadDS_ = new JTextField();
txtf_loadDS_.setBounds(22, 22, 382, 25);
topPanel.add(txtf_loadDS_);
finishBuildGUI();
}
public void finishBuildGUI(){
tabbedPane = new JTabbedPane();
topPanel.add(tabbedPane, BorderLayout.CENTER);
}
}
There are multiple issues with this application such as extending from Frame rather than JFrame & attempting to assign an int from Double.parseDouble. I would recommend that you start again building a small but working application and incrementally add functionality, this way errors are easier to fix.

redraw jlabel in loop defined jpanels and decleration of jpanels in loop

So for fun I've been working on developing this simple stock-chart GUI, which grabs charts from YahooFinance and displays them into a tabbed-Jpanel. I've been able to get the tabs to populate with user-defined stocks and all. However, I've developed some buttons that allow one to query different chart aspects (boll bands, moving averages, etc.) and would like the be able to "redraw" the panel with this update chart.
Problem: I'm not sure how to access the individual panels that I create via the method below. I need to be able to select a panel (say panel1 created when i=1 below) and have it update in an ActionListener. I'm really just wondering how Java defines these panels in the loop so I can access them later and redraw the label! Cheers.
public static void urlstock(String options,final String[] s, final JFrame f,final
JTabbedPane tpane) throws IOException{
for(int i=0;i<s.length;i++){
String path = "http://chart.finance.yahoo.com/z?s="+s[i]+options;
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
JPanel panel=new JPanel();
tpane.addTab(s[i],null, panel);
panel.add(label);
}
So I've tried this which cues on a button press, but it doesn't work because it doesn't recognize panel as variable for a reason that is beyond my understanding:
public void actionPerformed(ActionEvent e)
{ //Execute when button is pressed
System.out.println("MAButton");
tpane.getComponentAt(1);
tpane.remove(panel);
//Container.remove();
String path = "http://chart.finance.yahoo.com/z?s=GOOG&t=7m&z=l&q=l&a=ss,sfs";
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
JPanel panel=new JPanel();
tpane.setComponentAt(1,panel);
panel.add(label);
}
Grab an index of the tab in question using it's name (s[i]) JTabbedPane#indexOfTab(String)
Get a reference to the component at the retrieved index (JTabbedPane#getComponentAt(int))
Remove the contents of the retrieved component Container#removeAll()
Add the new label....
UPDATED with Example
public class TestTabPane {
public static void main(String[] args) {
new TestTabPane();
}
public TestTabPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JTabbedPane tabPane = new JTabbedPane();
JPanel panel = new JPanel();
JButton updateButton = new JButton("Update me");
panel.add(updateButton);
updateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int indexOfTab = tabPane.indexOfTab("Testing");
JPanel panel = (JPanel) tabPane.getComponentAt(indexOfTab);
panel.removeAll();
panel.add(new JLabel("I've begin updated"));
panel.repaint();
}
});
tabPane.addTab("Testing", panel);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(tabPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Categories

Resources