Whenever i have created a GUI application, i have always extended JFrame. Encephalopathic showed me that i should be extending JFrame instead so that i dont subclass JFrame. This works really well now and it makes a lot of sense to do this. The only problem i am having with this layout now is where to put my JButtons. So far i have done the code like this:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.imageio.ImageIO;
public class Assignment2 extends JPanel
{
private static final String FILE_PATH = "C:\\Documents and Settings\\Maureen\\My Documents\\My Pictures\\olympic.png";
private JButton eventJButton;
private BufferedImage image = null;
public Assignment2()
{
try
{
image = ImageIO.read(new File(FILE_PATH));// load the image
}
catch (IOException e)
{
e.printStackTrace();
}
// set up the JPanel.
JLabel titleLabel = new JLabel("LONDON 2012");
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 48));
titleLabel.setForeground(Color.blue);
JPanel titlePanel = new JPanel();
titlePanel.setOpaque(false);
titlePanel.add(titleLabel);
eventJButton = new JButton();
eventJButton.setText( "EVENTS" );
eventJButton.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
eventJButtonActionPerformed( event );
}
}
);
setPreferredSize(new Dimension(800, 590));
setLayout(new BorderLayout());
add(titlePanel, BorderLayout.NORTH);
add(eventJButton, BorderLayout.SOUTH);
}
protected void paintComponent(Graphics g) //overriding paint method
{
super.paintComponent(g);
if (image != null)
{
g.drawImage(image, 100, -50, this); //applying my image
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Nerkesa");
frame.getContentPane().add(new Assignment2()); // adding the JPanel to the JFrame here
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void eventJButtonActionPerformed( ActionEvent event )
{
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
I added the JButton in the JPanel. I dont know if this is correct but it seems to work at the moment. The problem i am having is that when i try and set the size of this button, no changes are made. The only place it seems to let me make change to this button is when i add it to the JPanel
add(eventJButton, BorderLayout.SOUTH);
But then this adds the button at the bottom of my application and the size is the whole width of my application. How can i make changes to this button in relation to its size?