My problem is setting the size of the JButton. I want it to be a little button centered below the "Hello World" JLabel field (as it is now it spans the full width of the JFrame). I am unsure what is causing the setPreferredsize to be ignored. I am an ameture/novice Java Developer and appriciate any help and all help. My code is below error free:
/* Author: Ashley
* This program will display a basic JFrame, JLabel, and JButton.
* The JLabel will display "Hello World and the JButton will close the program
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author Ashley
*/
public class gui extends JFrame implements ActionListener {
public static void main(String[] args) { //main arguments string
gui gui = new gui(); // calls gui which holds all the GUI data
/**
* method declaration for the gui
*/
}
public gui() {
String text = "Hello World!"; // creates a string for hello world
JButton button; // names a JButton
JFrame frame = new JFrame("My GUI"); // creates a JFrame named fram
frame.setSize(250, 150); // sets frame size
frame.setVisible(true); // makes frame visable
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //creates default close functions
JPanel tpanel = new JPanel(); //creats a JPanel to hold the JLabel
JLabel label = new JLabel( text ); //creats a JLabel
label.setHorizontalAlignment(SwingConstants.CENTER); // sets JLabel middle and centered
tpanel.add(label); // adds JLabel to the panel
button = new JButton("OK"); // creates JButton
Dimension bd = new Dimension(50, 50);
button.setPreferredSize(bd);
button.addActionListener(new ActionListener() { // add an action listener with inner class to declare JButton event
@Override
public void actionPerformed(ActionEvent e) { //inner class assigns action to button
System.exit(0);
}
});
frame.add(label, BorderLayout.CENTER); // addes JLabel to the JFrame
frame.add(button, BorderLayout.SOUTH);// adds JButton to the JFrame
}
@Override // an override for inner class, ensures that the button action will run.
public void actionPerformed(ActionEvent ae) {
}
}