JPanel doesn't add button and text field - java

I don't understand why the panel.add(txtnum1) and panel.add(button2) doesn't show up when I compile the program. The panel.add(button) works just fine, my compiler doesn't throw any warning or errors, did I miss something?
package gui;
import javax.swing.*;
import java.awt.*;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(new Dimension(300, 500));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.GRAY);
frame.getContentPane().add(panel);
JButton button = new JButton("Submit");
panel.add(button);
JTextField txtnum1 = new JTextField();
txtnum1.setPreferredSize(new Dimension(30, 50));
panel.add(txtnum1);
JButton button2 = new JButton("Clear");
panel.add(button2);
}
}

When implementing GUI applications with Swing, I like to have this approach in the code that builds the JFrame (we assume a simple GUI that does not have JPanel containers inside JPanel containers and stuff like that):
Create JFrame and initialize it
Create JPanel
Create GUI components for that panel and add them
Add panel to the JFrame (repeat from 2) for every JPanel inside the JFrame)
Make the JFrame visible on the screen
So, your code would look something like this:
package gui;
import javax.swing.*;
import java.awt.*;
public class GUI {
public static void main(String[] args) {
/* step 1 */
JFrame frame = new JFrame();
frame.setSize(new Dimension(300, 500));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* step 2 */
JPanel panel = new JPanel();
panel.setBackground(Color.GRAY);
/* step 3 */
JButton button = new JButton("Submit");
panel.add(button);
JTextField txtnum1 = new JTextField();
txtnum1.setPreferredSize(new Dimension(30, 50));
panel.add(txtnum1);
JButton button2 = new JButton("Clear");
panel.add(button2);
/* step 4 */
frame.getContentPane().add(panel);
/* step 5 */
frame.setVisible(true);
}
}
Tested and it works in Eclipse.

You should call setVisible(true) at the end, after all components have been added.
Put frame.setVisible(true); at the end and it will work as expected.

Related

Need the following UI in Swing

I need the following UI on JFrame. Two Jlabel Vertically Left aligned. Two button horizontally below the Jlabel. I tried below code but it is coming in one row.
Label should be left and vertically aligned.
Button should cover all the width of Jframe.
import javax.swing.*;
import java.awt.*;
public class CustomPanel {
private JFrame frame = new JFrame();
private JPanel basePanel= new JPanel();
public static void main(String []args){
CustomPanel cp= new CustomPanel();
cp.showUI();
}
private void addui(){
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new GridBagLayout());
JLabel label11 = new JLabel("I am here to test");
JLabel label12 = new JLabel("I am here to test row");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
labelPanel.add(label11, gbc);
gbc.gridy++;
gbc.gridwidth = 2;
labelPanel.add(label12, gbc);
basePanel.add(labelPanel);
/////////////// button panel//////////
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 5, 5));
panel.add(new JButton("Click me"));
panel.add(new JButton("Click me22"));
basePanel.add(panel);
}
private void showUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
addui();
frame.setAlwaysOnTop(true);
frame.setType(Window.Type.UTILITY);
frame.setResizable(true);
frame.getContentPane().setLayout(new BorderLayout());
JScrollPane scrollPane = new JScrollPane(basePanel);
scrollPane.setPreferredSize(new Dimension(400, 250));
frame.getContentPane().add(scrollPane);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
When creating a Swing GUI, you can break up a complex JPanel layout into more than one simpler JPanels. I created three JPanels for this GUI; the main JPanel, the label JPanel, and the button JPanel.
A Swing application must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
I created the JFrame and the three JPanels in separate methods. This allows me to focus on one part of the GUI at a time and makes the code much easier to read and follow. This also allows me to experiment with different Swing layout managers to see which one is appropriate for the GUI.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CustomPanel implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CustomPanel());
}
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createLabelPanel(), BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.SOUTH);
return panel;
}
private JPanel createLabelPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JLabel label11 = new JLabel("I am here to test");
panel.add(label11, BorderLayout.NORTH);
JLabel label12 = new JLabel("I am here to test row");
panel.add(label12, BorderLayout.SOUTH);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridLayout(0, 2, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton button = new JButton("Click me");
panel.add(button);
button = new JButton("Click me22");
panel.add(button);
return panel;
}
}

Adding Panel to Panel

I anted to add a JPanel to my already existing JPanel so I could have a small window with a JTextField on top with a name and a scrollable JTextArea below it with some description. I made a class that extends JPanel with the following constructor:
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
public class LocationWindow extends JPanel {
public JTextField name;
public JTextArea desc;
public JScrollPane scroll;
public LocationWindow(){
super();
setBorder (new TitledBorder(new EtchedBorder(), "Display Area"));
setLayout(new BorderLayout());
setVisible(true);
setBounds(30, 40, 700, 290);
name = new JTextField(10);
name.setText("name");
desc = new JTextArea(5,10);
scroll = new JScrollPane(desc);
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
desc.setEditable (true);
desc.setLineWrap(true);
desc.setText("random text");
add(name);
add(desc);
add(scroll);
validate();
}
}
It almost works, as it gives me the window with the borders and a scroll, but both the JTextField and JTextArea are missing.
As you are using BorderLayout for the JPanel,
setLayout(new BorderLayout());
the components will always be added to the center if you dont specify the position. add(scroll); is same as add(scroll,BorderLayout.CENTER); as you're adding all via add the last added component only be visible.Refer this as well
The next is you are adding JTextArea seperately so it will be removed from ScrollPane.Just add scrollpane to Panel no need to add all components.[Add the parent component alone]
add(name,BorderLayout.NORTH);
//add(desc);Noo need to add desc as it is already added in JScrollPane
add(scroll,BorderLayout.CENTER);
There is no need for setVisible for JPanel.JPanel needs to be embedded in Container like JFrame to be visible
//setVisible(true);Wont do anything
So call like this
JFrame frame = new JFrame();
frame.add(new LocationWindow());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
You can use below code to adding panel to panel.
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LocationWindow loc = new LocationWindow();
frame.add(loc);
frame.setSize(300, 200);
frame.setVisible(true);
}

How to resize a JPanel

I am trying to resize the JPanels but there is a space under it . Here is a link to show :
And this is the code :
import java.awt.*;
import javax.swing.*;
public class Ex1 extends JFrame{
private JTextArea textarea = new JTextArea ();
private JTextField field = new JTextField ();``
private JButton buton = new JButton ("Trimite");
public Ex1(){
JPanel panel = new JPanel (new BorderLayout(2,2));
JPanel panel1 = new JPanel (new BorderLayout(2,2));
JPanel panel2 = new JPanel (new BorderLayout(2,2));
JLabel label1 = new JLabel ("Mesaje");
JLabel label2 = new JLabel ("Scrieti un mesaj");
panel1.setPreferredSize(new Dimension(350,100));
panel2.setPreferredSize(new Dimension(350,25));
panel1.add(label1, BorderLayout.NORTH);
panel1.add(textarea, BorderLayout.CENTER);
panel2.add(label2, BorderLayout.WEST);
panel2.add(field, BorderLayout.CENTER);
panel2.add(buton, BorderLayout.EAST);
setLayout(new GridLayout(2,1,1,1));
panel.add(panel1, BorderLayout.NORTH);
panel.add(panel2, BorderLayout.CENTER);
add(panel);
}
public static void main(String[] args) {
JFrame frame = new Ex1();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
You are setting a layout for a frame to GridLayout in which all components are given equal size. You have two rows, add(panel) adds the panel to the first row of the grid. The second row is left empty. See How to Use GridLayout.
Comment out setLayout(new GridLayout(2,1,1,1)); and the extra space should go away. When you comment this line the layout of frame's content pane will be BorderLayout. The default layout of the JFrame is BorderLayout. So add(panel); will add the panel to the center of the frame's content pane. As a result the panel should occupy all the available space.
As a side note, avoid setPreferredSize(), usually it is not necessary, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing for details.
You can specify the number of rows and columns for a text area and wrap it in the scroll pane, ie:
textArea = new JTextArea(5, 20);
JScrollPane scrollPane = new JScrollPane(textArea);
For more details see How to Use Text Areas
EDIT: example of getPreferredSize()
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
public class Ex1 extends JPanel{
private JTextArea textarea = new JTextArea ();
private JTextField field = new JTextField ();
private JButton buton = new JButton ("Trimite");
public Ex1() {
setLayout(new BorderLayout());
JPanel panel1 = new JPanel (new BorderLayout(2,2));
JPanel panel2 = new JPanel (new BorderLayout(2,2));
JLabel label1 = new JLabel ("Mesaje");
JLabel label2 = new JLabel ("Scrieti un mesaj");
panel1.add(label1, BorderLayout.NORTH);
panel1.add(new JScrollPane(textarea), BorderLayout.CENTER);
panel2.add(label2, BorderLayout.WEST);
panel2.add(field, BorderLayout.CENTER);
panel2.add(buton, BorderLayout.EAST);
add(panel1, BorderLayout.CENTER);
add(panel2, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
Ex1 panel = new Ex1();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
}
}
You need to resize the JFrame not the JPanel. Try:
this.setPreferredSize(new Dimension(350, 25);// in Ex1
Or in your main method:
frame.setPreferredSize(new Dimension(350, 25);

Java buttons not showing up on JFrame

I am fairly new to java, and I am starting a sort of glossary program.
At the start, I am trying to use a JFrame with buttons on.
But only 1 button shows up when I run it.
Also, I don't think I am positioning the buttons right.
package glossary;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Glossary {
public static void main(String[] args) {
JFrame frame = new JFrame("Glossary");
frame.setVisible(true);
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
frame.add(panel1);
JButton LookUpWord = new JButton("Look up word");
panel1.add(LookUpWord, BorderLayout.NORTH);
JPanel panel2 = new JPanel();
frame.add(panel2);
JButton SubmitNewWord = new JButton("Submit word");
panel2.add(SubmitNewWord, BorderLayout.SOUTH);
}
}
Please tell me what I am doing horribly wrong!
I think you are just getting mixed up about where to add your components. You probably aren't intending to add the buttons to NORTH and SOUTH, but rather adding the panels to the frame at NORTH and SOUTH. Also, wait until you've added all your components before calling frame.setVisible(true).
Try this:
public static void main(String[] args) {
JFrame frame = new JFrame("Glossary");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton LookUpWord = new JButton("Look up word"); // create the button
JPanel panel1 = new JPanel(); // create the panel
panel1.add(LookUpWord); // add the button to the panel
frame.add(panel1, BorderLayout.NORTH); // add the panel to the frame
JButton SubmitNewWord = new JButton("Submit word");
JPanel panel2 = new JPanel();
panel2.add(SubmitNewWord);
frame.add(panel2, BorderLayout.SOUTH);
frame.setVisible(true);
}
Add frame.setVisible(true);
Hoping this tutorial help you
How to Make Frames

JButton disappears when adding JTextrea

I'm having an issue with my Java program where I can add a JButton to the panel in JFrame, but when I create an JTextArea object, the JButton disappears?
package sandBox;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
JFrame frame = new JFrame("Hello world");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,500);
frame.setLayout(new BorderLayout());
JButton button2 = new JButton("STOP");
JButton button1 = new JButton("GO");
JTextArea text1 = new JTextArea();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(button1, BorderLayout.SOUTH);
panel.add(button2, BorderLayout.NORTH);
frame.add(panel);
}
}
Remember
BorderLayout will only allow a single component to occupy each of the available positions. Adding another component will cover the previous component
Where possible, always call setVisible after you've created the UI
To actually add all your components, your example doesn't actually add the JTextArea to the container
Someone like...
//...
// frame.setVisible(true);
//...
frame.add(text1);
frame.add(panel, BorderLayout.SOUTH);
frame.setVisible(true);
Might help

Categories

Resources