Java Using not extending from JFrame - java

I am having a hard time understanding how to write my program with out having it extend from JFrame.
I have tried removing the extends JFrame clause and and adding it into both my methods, replacing the CalculatorWhichUsesAInterface frame = new CalculatorWhichUsesAInterface(); section with JFrame frame = new JFrame(); and a few other things and nothing has worked.
How should I go about using JFrame frame = new JFrame() in my program instead of using extends JFrame?
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class CalculatorWhichUsesAInterface extends JFrame{
JFrame frame = new JFrame();
public CalculatorWhichUsesAInterface(){
JPanel jPanelOne = new JPanel();
jPanelOne.setLayout(new GridLayout(1, 1);
jPanelOne.add(new JButton("x"));
JPanel jPanelTwo = new JPanel(new BorderLayout());
JTextField field = new JTextField();
field.setText("2141987.01235");
jPanelTwo.add(field, BorderLayout.NORTH);
jPanelTwo.add(jPanelOne, BorderLayout.CENTER);
add(jPanelTwo, BorderLayout.CENTER);
}
public static void main(String[] args){
CalculatorWhichUsesAInterface frame = new CalculatorWhichUsesAInterface();
frame.setTitle("Calculator");
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

This is actually relativly easy (sorry, but it is).
Start by extending your class from JPanel, this provides you a basic container onto which to build your interface.
Remove the JFrame frame = new JFrame(); as you're not really using it and in your main method, create a new instance of JFrame and add you component to it
class CalculatorWhichUsesAInterface extends JPanel {
public CalculatorWhichUsesAInterface(){
JPanel jPanelOne = new JPanel();
jPanelOne.setLayout(new GridLayout(1, 1);
jPanelOne.add(new JButton("x"));
JPanel jPanelTwo = new JPanel(new BorderLayout());
JTextField field = new JTextField();
field.setText("2141987.01235");
jPanelTwo.add(field, BorderLayout.NORTH);
jPanelTwo.add(jPanelOne, BorderLayout.CENTER);
add(jPanelTwo, BorderLayout.CENTER);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
public void run() {
CalculatorWhichUsesAInterface calc = new CalculatorWhichUsesAInterface();
JFrame frame = new JFrame()
frame.setTitle("Calculator");
frame.add(calc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
This concept provides you with a flexible and re-usable component. This means that you can decide how and where the component is to be displayed. Displayed on it's own in it's own frame (as the above example does) or added to another container (such as another JPanel or even an applet)
You may also want to take a look at Initial Threads
Example two - not extending anything
class CalculatorWhichUsesAInterface {
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
public void run() {
JPanel jPanelOne = new JPanel();
jPanelOne.setLayout(new GridLayout(1, 1);
jPanelOne.add(new JButton("x"));
JPanel jPanelTwo = new JPanel(new BorderLayout());
JTextField field = new JTextField();
field.setText("2141987.01235");
jPanelTwo.add(field, BorderLayout.NORTH);
jPanelTwo.add(jPanelOne, BorderLayout.CENTER);
JFrame frame = new JFrame()
frame.setTitle("Calculator");
frame.add(jPanelTwo);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Updated with "builder" example
This is a (very basic) example of a builder pattern, basically, you have a separate class which simply builds the UI and returns a JPanel (in this example)
More complex builders would allow you to add additional properties to adjust the outcome.
class CalculatorWhichUsesAInterface {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setTitle("Calculator");
frame.add(CalculatorBuilder.build());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public static class CalculatorBuilder {
public static JPanel build() {
JPanel jPanelOne = new JPanel();
jPanelOne.setLayout(new GridLayout(1, 1));
jPanelOne.add(new JButton("x"));
JPanel jPanelTwo = new JPanel(new BorderLayout());
JTextField field = new JTextField();
field.setText("2141987.01235");
jPanelTwo.add(field, BorderLayout.NORTH);
jPanelTwo.add(jPanelOne, BorderLayout.CENTER);
return jPanelTwo;
}
}
}

to not extend JFrame you have the right idea, but on your code above you'd need to first remove the extends JFrame but the way you declare your frame is fine:
JFrame frame = new JFrame("Title");
Then from there you just have to reference the object of it from then on, so for example:
frame.add(jPanelTwo,BorderLayout.CENTER)

Looks like everything you do in main (setTitle, setSize etc) you do for JFrame object that "comes" from inheritance (extends JFrame). So actually you are doing nothing with:
JFrame frame = new JFrame();
If you want not to use inheritance, you should invoke methods of JFrame object, not the CalculatorWhichUsesAInterface(). So the constructor should look like this (in main leave only creating the object):
class CalculatorWhichUsesAInterface{
JFrame frame = new JFrame();
public CalculatorWhichUsesAInterface(){
JPanel jPanelOne = new JPanel();
jPanelOne.setLayout(new GridLayout(1, 1);
jPanelOne.add(new JButton("x"));
JPanel jPanelTwo = new JPanel(new BorderLayout());
JTextField field = new JTextField();
field.setText("2141987.01235");
jPanelTwo.add(field, BorderLayout.NORTH);
jPanelTwo.add(jPanelOne, BorderLayout.CENTER);
frame.add(jPanelTwo, BorderLayout.CENTER); //DIFFERENCE
frame.setTitle("Calculator");
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
As you can see, I copied almost everyting from main to constructor, but it is invoked on different object (JFrame actually, not the CalculatorWhichUsesAInterface). But doing JFrame through inheritance is common way.

Related

How do I add other swing components in a specific swing tabbed pane?

I have just started learning Java Swing and I am making a application form sort of project and I want to add more components like buttons,text areas and other in specific tab but I am not able to.
The code is given below:
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame("Hotel Appication Form");
JTextArea ta=new JTextArea(400,400);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(39,20,500,500);
tp.add("form",p1);
tp.add("preferences",p2);
tp.add("FaQ's",p3);
f.add(tp);
f.setSize(600,600);
f.setVisible(true);
//JButton
JButton b = new JButton("Submit");
b.setBounds(50,50,30,20);
f.add(b);
//JLabel
}
public static void main(String[] args) {
new TabbedPaneExample();
}
}
The screenshot of the output is attached here
In this code example simple frame with tabbed panel and simple components in each tab.
Your problem was incorrect adding components to JPanel.
Hope that helps you!
output1 output2
import java.awt.GridLayout;
import javax.swing.*;
public class test {
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Split Pane Example");
// Display the window.
frame.setSize(500, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set grid layout for the frame
frame.getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JButton button = new JButton("Button");
JLabel label = new JLabel("Label");
JTextField textField = new JTextField("TextField");
panel.add(button);
panel.add(label);
panel2.add(textField);
tabbedPane.addTab("Tab1", panel);
tabbedPane.addTab("Tab2", panel2);
frame.getContentPane().add(tabbedPane);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Displaying JDesktopPane in a JPanel

I am having some difficulty getting a JDesktopPane (that contains a JInternalFrame) to add to a JPanel. What is the proper way to do this? What am I doing wrong?
Here is my bare bones example:
import javax.swing.*;
import java.awt.*;
public class MainPanel extends JPanel {
JDesktopPane jDesktopPane = new JDesktopPane();
JInternalFrame jInternalFrame = new JInternalFrame();
public MainPanel() {
jDesktopPane.add(jInternalFrame);
add(jDesktopPane);
setSize(400,400);
setVisible(true);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("This isn't working...");
MainPanel mainPanel = new MainPanel();
frame.setLayout(new BorderLayout());
frame.add(mainPanel, BorderLayout.CENTER);
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(false);
frame.setSize(500, 500);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
JDesktop doesn't use a layout manager, so it's default/preferred size is 0x0
JPanel uses FlowLayout by default, which honours the preferredSize of it's child components when it lays them out
So, in your constructor, you could try changing the default layout manager to BorderLayout instead...
public MainPanel() {
setLayout(new BorderLayout());
jDesktopPane.add(jInternalFrame);
add(jDesktopPane);
// pointless
//setSize(400,400);
// pointless
//setVisible(true);
}
Now, you because nothing is actually defining a preferred size for anything, you should provide your own...
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
Then when you create the UI you can simply pack the frame...
private static void createAndShowGui() {
JFrame frame = new JFrame("This should be working now...");
MainPanel mainPanel = new MainPanel();
frame.setLayout(new BorderLayout());
// pointless considering the setContentPane call
//frame.add(mainPanel, BorderLayout.CENTER);
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(false);
//frame.setSize(500, 500);
frame.setVisible(true);
}
Now because JDesktopPane doesn't use any layout manager, you become responsible for ensuring that anything your add to it is positioned and size
jInternalFrame.setBounds(10, 10, 200, 200);
// Just like any frame, it's not visible when it's first created
jInternalFrame.setVisible(true);

How to give a preffered size to the JButton?

import javax.swing.*;
import java.awt.*;
class MainGui{
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon("C:\\Users\\BSK\\Desktop\\game5.jpg"));
public MainGui(){
frame.setSize(600,800);
frame.setVisible(true);
frame.setResizable(false);
setButtonSize();
frame.setLayout(new BorderLayout());
frame.setContentPane(backImage);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
insertBlankArea(frame);
frame.getContentPane().add(newBut);
insertBlankArea(frame);
frame.getContentPane().add(continueBut);
insertBlankArea(frame);
frame.getContentPane().add(exitBut);
frame.setSize(799,800);
}
public void insertBlankArea(JFrame frame){
frame.getContentPane().add(Box.createRigidArea(new Dimension(280,155)));
}
public void setButtonSize(){
Dimension dim = new Dimension(100,100);//here is the problem,i am not getting the desired dimension and the size of buttons remains the default.
newBut.setPreferredSize(dim);
continueBut.setPreferredSize(dim);
exitBut.setPreferredSize(dim);
}
public static void main(String[] args) {
MainGui mainGui = new MainGui();
}
}
So iam not getting the defined size for the buttons but when i set frame.setResizable(false); then when i stretch the screen the button's height increases but its width still remains the same.
So please tell me what is going wrong?
You should take a look at A Visual Guide to Layout Managers and choose the most appropriate one for your situation. You should also avoid explicitly setting sizes (ie: setSize, setMinimumSize, setMaximumSize, and setPreferredSize) because those methods are the responsibility of the layout manager. You may also be interested in reading this question on whether or not the use of the different set size methods should be avoided or not.
Finally, you should not be calling your MainGUI class outside of the Event Dispatch Thread (EDT). Most Swing GUI-related methods are not thread safe and therefore require being executed in the EDT. Below is a corrected version of your main method:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MainGui mainGui = new MainGui();
}
});
}
Just reading your short descrption, I have no idea what your problem is. But based solely on the question title
"How to give a preffered size to the JButton?"
Don't. Let the the layout manager handle this for you. If you want a bigger button, you can use JButton.setMargins(Insets) and/or JButton.setFont(Font) where you specify a bigger font.
If you want you button stretched or not to stretch, You need to select an appropriate layout manager, that will or won't respect the buttons preferred size. For instance, BorderLayout and GridLayout won't respect preferred sizes and will stretch the button the fit, and FlowLayout, BoxLayout, and GridBagLayout will respect the preferred size. As you can see here
See example with GridBagLayout
import javax.swing.*;
import java.awt.*;
class MainGui {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon(
getClass().getResource("images.jpg")));
public MainGui() {
backImage.setLayout(new BorderLayout());
frame.setContentPane(backImage);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
mainPanel.add(newBut, gbc);
gbc.gridy = 1;
mainPanel.add(continueBut, gbc);
gbc.gridy = 2;
mainPanel.add(exitBut, gbc);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.setSize(250, 275);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
MainGui mainGui = new MainGui();
}
});
}
}
And here's with nesting panels which will give the same result
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class MainGui {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon(
getClass().getResource("images.jpg")));
public MainGui() {
backImage.setLayout(new GridLayout(3,1));
frame.setContentPane(backImage);
JPanel p1= new JPanel(new GridBagLayout());
p1.setOpaque(false);
p1.add(newBut);
JPanel p2 = new JPanel(new GridBagLayout());
p2.setOpaque(false);
p2.add(continueBut);
JPanel p3 = new JPanel(new GridBagLayout());
p3.setOpaque(false);
p3.add(exitBut);
frame.add(p1);
frame.add(p2);
frame.add(p3);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 275);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
MainGui mainGui = new MainGui();
}
});
}
}

How to tidy up code into class files and methods

I am still learning Java and I am currently creating a program in Swing. I have been confused regarding when and when I should use methods and class files. I have created an application that has two cards, card 1: homeJPanel and card 2: guestFixturesJPanel and I want these to switch between each other on button click - which i have done to an extent. However, my code looks extremely messy and is hard to look at as all JPanels are in one method. I was wondering if there was any way I could put guestFixturesJPanel into a separate method or class file and still be able to call the card on button click. Is this possible? Also, does anyone know of any good tutorials that explain methods and class files well as I have been confused and this may be the solution to my problem.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
public class Main
{
protected static final Component c1 = null;
private JButton viewFixturesButton, loginButton, guestBackButton;
private JLabel testTextJLabel, testTextJLabel2;
JPanel container = new JPanel();
CardLayout cardLayout = new CardLayout();
public Main()
{
final JFrame window = new JFrame ("Main Game");
final CardLayout c1 = new CardLayout();
final JPanel container = new JPanel(c1);
JPanel homeJPanel = new JPanel(new BorderLayout());
container.add(homeJPanel);
JPanel centerJPanel = new JPanel(new BorderLayout());
testTextJLabel = new JLabel("TEST");
centerJPanel.add(testTextJLabel);
JPanel southPanel = new JPanel(new FlowLayout());
viewFixturesButton = new JButton("View Fixtures");
loginButton = new JButton("Login");
southPanel.add(viewFixturesButton);
southPanel.add(loginButton);
homeJPanel.add(centerJPanel, BorderLayout.CENTER);
homeJPanel.add(southPanel, BorderLayout.SOUTH);
centerJPanel.setBackground(Color.BLUE);
southPanel.setBackground(Color.GREEN);
JPanel guestFixturesJPanel = new JPanel(new BorderLayout());
container.add(guestFixturesJPanel);
JPanel guestCenterJPanel = new JPanel(new BorderLayout());
JPanel guestSouthPanel = new JPanel(new FlowLayout());
guestBackButton = new JButton("Back");
guestSouthPanel.add(guestBackButton);
guestFixturesJPanel.add(guestCenterJPanel, BorderLayout.CENTER);
guestFixturesJPanel.add(guestSouthPanel, BorderLayout.SOUTH);
guestCenterJPanel.setBackground(Color.BLUE);
guestSouthPanel.setBackground(Color.GREEN);
viewFixturesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
c1.show(container, "2");
}
});
container.add(homeJPanel, "1");
container.add(guestFixturesJPanel, "2");
c1.show(container, "1");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(container);
window.setSize(600, 500);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Main();
}
});
}
}
You could extract the guestFixturesPanel to a class of its own like this:
public class GuestFixturesPanel extends JPanel {
public GuestFixturesPanel() {
this.setLayout(new BorderLayout());
JPanel guestCenterJPanel = new JPanel(new BorderLayout());
JPanel guestSouthPanel = new JPanel(new FlowLayout());
JButton guestBackButton = new JButton("Back");
guestSouthPanel.add(guestBackButton);
add(guestCenterJPanel, BorderLayout.CENTER);
add(guestSouthPanel, BorderLayout.SOUTH);
guestCenterJPanel.setBackground(Color.BLUE);
guestSouthPanel.setBackground(Color.GREEN);
}
}
Then in your Main class you could instantiate a GuestFixturesPanel and add it to your container. This would preserve the functionality you have now, and extract the code out of your Main class.
GuestFixturesPanel guestFixturesPanel = new GuestFixturesPanel();
container.add(guestFixturesPanel, "2");
Not sure if that addresses the question you had, but I hope this helps.

JButtons not appearing on my JFrame

I am making a program that includes a GUI. For some reason, the JButton objects that I have created are not showing up onto my JFrame when I run the program. Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel buttonPanel;
private JTextArea textArea;
public ReverseAStringMain(){
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
enterButton.setPreferredSize(new Dimension(60,60));
exitButton.setPreferredSize(new Dimension(60,60));
ButtonListener listener = new ButtonListener();
enterButton.addActionListener(listener);
exitButton.addActionListener(listener);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(200,50));
buttonPanel.setBackground(Color.black);
buttonPanel.add(enterButton);
buttonPanel.add(exitButton);
textField = new JTextField();
textField.setSize(200, 100);
textArea = new JTextArea();
textArea.add(textField);
add(buttonPanel);
add(textField);
}
//Creating a ButtonListener class that implements the ActionListener interface
private class ButtonListener implements ActionListener{
#Override
//Overriding the ActionPerformed method of ActionListener
public void actionPerformed(ActionEvent action) {
if(action.getSource()== enterButton)
enterButton();
if(action.getSource()== exitButton)
System.exit(0);
}
}
private void enterButton() {
// TODO Auto-generated method stub
}
public static void main (String[] args){
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(600,600));
//frame.pack();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
}
}
If there are any problems or improvements I can make in my code, please let me know!
You're adding the components to your JFrame after it's visible. You should either add them to the JFrame before it's visible, or revalidate the JFrame after you add the components.
When I load your code (after making it a lot shorter in height), this is what I see:
I suspect this is more along the lines of what you expect to see.
Here is how I did it. Look carefully at:
The numbers provided to the BorderLayout constructor for white space between the panels.
The EmptyBorder for white space around the controls.
The use of pack() to shrink the GUI to the natural size.
The use of size hints in the construction of the text field and text area.
The use of a second layout - commonly known as a combined, or nested, layout.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel pageTopPanel;
private JTextArea textArea;
public ReverseAStringMain(){
super(new BorderLayout(10,10));
setBorder(new EmptyBorder(5,15,5,15));
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
pageTopPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
pageTopPanel.setBackground(Color.black);
pageTopPanel.add(enterButton);
pageTopPanel.add(exitButton);
textField = new JTextField(5);
pageTopPanel.add(textField);
textArea = new JTextArea(4,40);
add(pageTopPanel, BorderLayout.PAGE_START);
add(textArea); // defaults to CENTER
}
public static void main (String[] args){
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("XXX's Laid out Program");
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
General Tips
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Generally, you want to set the frame visible After adding components
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(600,600));
//frame.pack();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
frame.setVisible(true); <<------
Also, it is better practice to use .pack() insteack of .setSize(), so you had it right in the commented out //.pack()
If you wanted to set a size to the panel, you would override the getPreferredSize() like this
public Dimension getPreferredSize() {
return new Dimension(300, 300); // or whatever size you want
}
When you .pack(), this preferred size will be respected by the frame.
Also, not, setting the size of the JTextField won't work. What you want to do is pass it an integer value for the number of character spaces, like this
textField = new JTextField(20);
See an edited version of your program, with all the above mentioned points. One thing I also did was get rid of all your .setPreferredSizes. You will see the difference
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel buttonPanel;
private JTextArea textArea;
public ReverseAStringMain() {
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
//enterButton.setPreferredSize(new Dimension(60, 60));
//exitButton.setPreferredSize(new Dimension(60, 60));
ButtonListener listener = new ButtonListener();
enterButton.addActionListener(listener);
exitButton.addActionListener(listener);
buttonPanel = new JPanel();
//buttonPanel.setPreferredSize(new Dimension(200, 50));
buttonPanel.setBackground(Color.black);
buttonPanel.add(enterButton);
buttonPanel.add(exitButton);
textField = new JTextField(20);
//textField.setSize(200, 100); /// <<-----------
textArea = new JTextArea();
textArea.add(textField);
add(buttonPanel);
add(textField);
}
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
// Creating a ButtonListener class that implements the ActionListener
// interface
private class ButtonListener implements ActionListener {
#Override
// Overriding the ActionPerformed method of ActionListener
public void actionPerformed(ActionEvent action) {
if (action.getSource() == enterButton)
enterButton();
if (action.getSource() == exitButton)
System.exit(0);
}
}
private void enterButton() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.getContentPane().add(new ReverseAStringMain());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Have a look at the Swing tutorial trail for more information on creating GUIs with Swing.
Try to add the buttonPanel to a Container, like this. And extend JFrame instead
Container contentpane = getContentPane();
contentPane.add(buttonPanel);

Categories