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);
}
}
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();
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.
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);
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);
}
}