Trying to use GUI, having trouble adding buttons and labels - java

The assignment is simple, all we need to do is have the code create a window with a red panel with a single button and label. Here is the code thus far as well as the tester class.
I got the label to display on the window, but its in a weird place. I cant get the button to display at all as well getting the background to display as red.
This is where I'm having trouble with the most:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyCustomFrame extends JFrame
{
public MyCustomFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createComponents()
{
JPanel panel=new createPanel();
button=new JButton("Push Me");
label=new JLabel("This is a label");
add(button);
add(label);
}
private JButton button;
private JLabel label;
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 800;
public void createPanel()
{
JPanel panel=new JPanel();
panel.setBackground(Color.RED);
//button=new JButton("Push Me");
//label=new JLabel("This is a label");
}
public void createFrame()
{
JFrame frame=new JFrame();
add(frame);
frame.setVisible(true);
}
}
And this is the tester class:
import javax.swing.JFrame;
public class MyCustomFrameViewer
{
public static void main(String[] args)
{
MyCustomFrame frame = new MyCustomFrame();
frame.setTitle("My first frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

You create the JPanel, panel, but add nothing to it, and then never add the panel to your JFrame. You should add your components to the JPanel, panel, and then add the panel object to your JFrame.
Note that a JPanel uses FlowLayout by default, and so it will more easily accept multiple other components without special add methods. The JFrame's contentPane uses BorderLayout which is slightly more complicated to use.

Add the panel to the frame instead of the label and button, and add the label and button to the panel...
private void createComponents()
{
JPanel panel=new createPanel();
add(panel);
button=new JButton("Push Me");
label=new JLabel("This is a label");
panel.add(button);
panel.add(label);
}
You may also want to take a look at Initial Threads and make sure you are creating your UI from within the context of the Event Dispatching Thread
Some side notes...
This scares me...
public void createFrame()
{
JFrame frame=new JFrame();
add(frame);
frame.setVisible(true);
}
You're trying to add a frame to a frame, which is an illegal operation in Swing, but thankfully, you're not actually calling it from what I can see.
Instead of using setSize(FRAME_WIDTH, FRAME_HEIGHT);, you may wish to use pack instead.

See also the tips in comments in this example:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
// Don't extend frame, just use an instance
//public class MyCustomFrame extends JFrame {
public class MyCustomFrame {
private JFrame frame;
private JButton button;
private JLabel label;
private JPanel panel;
// better to override the preferred size of the component of interest
final int GAME_WIDTH = 300;
final int GAME_HEIGHT = 100;
public MyCustomFrame() {
createComponents();
// better to override the preferred size of the component of interest
//setSize(GAME_WIDTH, GAME_HEIGHT);
}
private void createComponents() {
// compilation error! createPanel() does not return anything..
//JPanel panel = new createPanel();
createPanel();
// create the frame!
createFrame();
}
private void createPanel() {
// creates a local instance
//JPanel panel = new JPanel();
panel = new JPanel() {
/* override the preferred size of the component of interest */
#Override
public Dimension getPreferredSize() {
return new Dimension(GAME_WIDTH, GAME_HEIGHT);
}
};
panel.setBackground(Color.RED);
button = new JButton("Push Me");
label = new JLabel("This is a label");
panel.add(button);
panel.add(label);
}
private void createFrame() {
// create a local instance of a JFrame that goes out of scope at end
// of method..
//JFrame frame = new JFrame();
frame = new JFrame("My first frame");
// add the panel to the frame!
frame.add(panel);
// better to use DISPOSE_ON_CLOSE
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// a good way to position a GUI
frame.setLocationByPlatform(true);
// this was trying to add a JFrame to another JFrame
//add(frame);
frame.pack();
}
public final JFrame getFrame() {
return frame;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
MyCustomFrame myFrame = new MyCustomFrame();
JFrame frame = myFrame.getFrame();
frame.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}

Related

Panel not showing object [duplicate]

I have a JPanel and JButton on the JFrame.
on runtime add JLabel to JPanel When click JButton.
I use of the following code:
panel.setLayout(null);
jLabel _lbl=new jLabel();
_lbl.setText("Label");
panel.add(_lbl);
panel.validate();
but no display any JLabel in JPanel.
I see you create a JLabel called _lbl:
JLabel _lbl=new JLabel();
but you never add it to your panel. Instead you add a new JLabel with no text to your panel:
panel.add(new JLabel());
This would ofcourse construct an empty label which wont be visible.
Also try calling revalidate() and repaint() on your JPanel instance after adding the JLabel like so:
JLabel _lbl=new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
With this you may also need to call pack() on your frames instance so as to resize the JFrame to fit the new components.
Also please never use a null/Absolute layout this is very bad practice (unless doing animation) and may prove to be problematic and very hard to use.
Rather use a LayoutManager:
A Visual Guide to Layout Managers
or if you only have a single component on the JPanel simply call add(label); as it will stretch to the JPanel size.
UPDATE:
Here is a small sample. Simply adds JLabels to the JPanel each time JButton is pressed:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaApplication116 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JavaApplication116().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private void initComponents(final JFrame frame) {
final JPanel panel = new JPanel(new FlowLayout());
JButton button = new JButton("Add label");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel _lbl = new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
frame.pack();//so our frame resizes to compensate for new components
}
});
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
}
}

Having trouble with creating a JFrame and adding text to it

I've been trying to setup a JFrame with text but I'm having trouble. I can create the JFrame, but I can't get a background color or text to work with it.
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class FundManager {
JFrame window;
JPanel panel;
JLabel text;
public void createWindow()
{
//Create the window
window = new JFrame();
window.setVisible(true);
window.setSize(960, 540);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
//Create the panel
panel = new JPanel();
panel.setBackground(Color.RED);
//Create the label
text = new JLabel("test");
}
public static void main(String args[]) {
FundManager.createWindow();
}
}
My createWindow() method is not running and I get the error:
cannot make a static reference to to the non-static method.
However, when I make it static the whole program breaks.
The issue here is that you need an instance of FundManager before you can call the method createWindow(). Try the code below instead.
new FundManager().createWindow();
First of all, you cannot make a call to FundManager.createWindow(), because createWindow() is not a static method. You need an instance of FundManager.
Furthermore, you are not adding the panel nor the text field to the frame. You are only declaring them. This is a quick example of how you could locate the elements inside the frame:
JFrame window;
JPanel panel;
JLabel text;
public void createWindow() {
// Create the window
window = new JFrame();
window.setVisible(true);
window.setSize(960, 540);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
// Create the panel
panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 500));
panel.setBackground(Color.RED);
// Create the label
text = new JLabel("test");
text.setPreferredSize(new Dimension(200, 30));
text.setLocation(100, 100);
panel.add(text);
window.getContentPane().add(panel);
window.pack();
}
And run this with:
new FundManager().createWindow();

Java JFrame components

I'm trying to create a simple 500x500 applet with a button, 2-label, and textfield. The applet opens up but it is just blank no components are displaying nor will the color change. Not sure what is happening or what I'm missing exactly.
import java.applet.*;
import java.awt.Color;
import javax.swing.*;
public class Greeting {
private JFrame frame;
private JPanel panel;
private JLabel label1;
private JTextField textbox1;
private JButton button1;
private JLabel label2;
public Greeting(){
gui();
}
public void gui(){
frame = new JFrame("Greeting");
frame.setVisible(true);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setBackground(Color.YELLOW);
label1 = new JLabel ("Please enter your name");
textbox1 = new JTextField(20);
button1 = new JButton ("Greet");
panel.add(label1);
panel.add(button1);
panel.add(textbox1);
frame.getContentPane().add(panel);
frame.add(panel);
}
public static void main(String[] args) {
new Greeting();
}
}
If you are planning on displaying frame with all the components, then move the frame.setVisible(true) line to the end of the method:
public void gui() {
...
frame.add(panel);
frame.setVisible(true);
}
This allows for all the components to be added to the JFrame before it is displayed on the screen.

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);

add component to jpanel on runtime

I have a JPanel and JButton on the JFrame.
on runtime add JLabel to JPanel When click JButton.
I use of the following code:
panel.setLayout(null);
jLabel _lbl=new jLabel();
_lbl.setText("Label");
panel.add(_lbl);
panel.validate();
but no display any JLabel in JPanel.
I see you create a JLabel called _lbl:
JLabel _lbl=new JLabel();
but you never add it to your panel. Instead you add a new JLabel with no text to your panel:
panel.add(new JLabel());
This would ofcourse construct an empty label which wont be visible.
Also try calling revalidate() and repaint() on your JPanel instance after adding the JLabel like so:
JLabel _lbl=new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
With this you may also need to call pack() on your frames instance so as to resize the JFrame to fit the new components.
Also please never use a null/Absolute layout this is very bad practice (unless doing animation) and may prove to be problematic and very hard to use.
Rather use a LayoutManager:
A Visual Guide to Layout Managers
or if you only have a single component on the JPanel simply call add(label); as it will stretch to the JPanel size.
UPDATE:
Here is a small sample. Simply adds JLabels to the JPanel each time JButton is pressed:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaApplication116 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JavaApplication116().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private void initComponents(final JFrame frame) {
final JPanel panel = new JPanel(new FlowLayout());
JButton button = new JButton("Add label");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel _lbl = new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
frame.pack();//so our frame resizes to compensate for new components
}
});
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
}
}

Categories