Sajad
Sajad

Reputation: 2363

set picture to jpanel

I use this code to set a picture to jframe . But , now my Jtable don't show, why?

public class samplepage extends JFrame{
private AllUser userModel;
private JTable uTable;
JButton addUser;
JButton deleteUser;
JButton mainButton;
JTextField tf1;
JButton searchButton;
JLabel resultLbl;

public samplepage(){
    userModel=new AllUser();
    uTable=new JTable(userModel);
    add(new JScrollPane(uTable), BorderLayout.CENTER);
    add(buttonPanels() , BorderLayout.PAGE_START);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(800,600);
    this.setLocation(300, 60);
    this.setResizable(false);
}

public final JPanel buttonPanels(){
    JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    setPic(this);
    addUser=new JButton("Add New User");
    deleteUser=new JButton("delete User");
    mainButton= new JButton("Main Page");
    tf1 = new JTextField("              ");
    searchButton=new JButton("Search");
    resultLbl=new JLabel();

    buttonsPanel.add(addUser);
    buttonsPanel.add(deleteUser);
    buttonsPanel.add(mainButton);
    buttonsPanel.add(tf1);
    buttonsPanel.add(searchButton);
    buttonsPanel.add(resultLbl);

    return buttonsPanel;
}

public void setPic(JFrame jframe){
 try{
  File f=new File("pics\\user_group.png");
  BufferedImage img=ImageIO.read(f);
  jframe.setContentPane(new SetMyImage(img));
 }
 catch(IOException ioe){

 }
}

public static void main(String[] args){
    new samplepage().setVisible(true);
}

}

second Class:

public class SetMyImage extends JPanel{

private Image img;

public SetMyImage(Image img){
    this.img=img;
}

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(img, 00, 00, null);

}
}

Where is my mistake?

Upvotes: 0

Views: 112

Answers (1)

camickr
camickr

Reputation: 324098

uTable=new JTable(userModel);
add(new JScrollPane(uTable), BorderLayout.CENTER);
add(buttonPanels() , BorderLayout.PAGE_START);

First you add the table to the content pane. Then you create your buttonPanels() which invokes the setPic(...) method which creates your image panel and makes it the content pane of your frame so you lose the table.

Remove the setPic() code from your buttonPanels code. Instead your code should be something like:

setPic(...);
uTable=new JTable(userModel);
add(new JScrollPane(uTable), BorderLayout.CENTER);
add(buttonPanels() , BorderLayout.PAGE_START);

Also, you need to set the layout of your image panel to be a BorderLayout.

Since you are painting your image at its actual size there is no need to create a custom panel to do the painting. Instead you can just use a JLabel as your content pane. For more information on this approach see Background Panel.

Upvotes: 3

Related Questions