I have some troubles when I try to display an image in my JPanel
.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainWindow {
public static JFrame mainFrame;
public static JPanel loginRegisterPanel;
public MainWindow() {
MainFrame();
LoginRegisterPanel();
}
public void MainFrame() {
mainFrame = new JFrame();
mainFrame.setSize(640, 480);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setResizable(false);
}
public void LoginRegisterPanel() {
loginRegisterPanel = new JPanel();
loginRegisterPanel.setLayout(null);
mainFrame.add(loginRegisterPanel);
JButton loginButton = new JButton("Login");
JButton registerButton = new JButton("Register");
/*ImageIcon logoImage = new ImageIcon("Resource/logo.jpg");
JLabel logoImageLabel = new JLabel();
logoImageLabel.setBounds(0, 0, 640, 200);
logoImageLabel.setIcon(logoImage);
loginRegisterPanel.add(logoImageLabel);
*/
loginButton.setBounds(260, 180, 120, 50);
loginRegisterPanel.add(loginButton);
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
loginRegisterPanel.setVisible(false);
LoginPanel loginPanel = new LoginPanel();
mainFrame.getContentPane().add(loginPanel.loginP);
}
catch (Exception ce){
ce.printStackTrace();
}
}
});
registerButton.setBounds(260, 250, 120, 50);
loginRegisterPanel.add(registerButton);
}
public static void main (String[] args) {
MainWindow mainWindow = new MainWindow();
}
}
If I delete the section with ImageIcon
from my source code, my JPanel
displays the buttons, but if I use ImageIcon
, it doesn't display anything.
loginRegisterPanel.setLayout(null);
is causing the problem. I guess the absence of a Layout Manager confuses Java as to where to put it all. You should give a GridLayout perhaps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.