Add JTextField in A new JFrame - java

I have a JFrame with a JButton , this button open a new JFrame where there should be a text box ( JTextField ) that I will use for a search , the problem is that I don't know how to insert it . I came up with this :
N.B I'm a beginner, sorry in advance for the easy question :)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainWindow {
// Seconda Finestra
public static void NuovaFinestra (JPanel panel) {
panel.setLayout(null);
JButton Ricerca = new JButton("Ricerca");
Ricerca.setBounds(100, 100, 200, 50);
panel.add(Ricerca);
Ricerca.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFrame FinestradiRicerca = new JFrame("Finestra di Ricerca");
FinestradiRicerca.setBounds(300, 300, 500, 500);
FinestradiRicerca.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel riquadroRicerca = new JPanel();
FinestradiRicerca.add(riquadroRicerca);
FinestradiRicerca.setVisible(true);
JTextField ciao;
ciao = new JTextField ();
}
});
}
//Main
public static void main(String[] args) {
//Finestra Principale
JFrame finestra = new JFrame("Finestra principale");
finestra.setSize(500, 500);
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel della finestra principale
JPanel riquadro = new JPanel();
finestra.add(riquadro);
finestra.setVisible(true);
NuovaFinestra(riquadro);
}
}

You needed to add your new elements to riquadroRicerca BEFORE adding the Panel to FinestradiRicerca, I recommend you NOT to use null layout but a Layout Manager or combinations of them. If you insist on keeping null layout then see below example. But for this kind of app I'd suggest a CardLayout.
I also suggest not using multiple JFrames since they will open multiple windows on task bar which is user unfriendly. See: Use of multiple JFrames, Good / Bad Practice
As an aside note, follow Java naming conventions. For example you called a JFrame as FinestradiRicerca instead rename it to: finestradiRicerca (1st letter of a variable in lowercase).
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainWindow {
// Seconda Finestra
public static void NuovaFinestra (JPanel panel) {
panel.setLayout(null);
JButton Ricerca = new JButton("Ricerca");
Ricerca.setBounds(100, 100, 200, 50);
panel.add(Ricerca);
Ricerca.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFrame FinestradiRicerca = new JFrame("Finestra di Ricerca");
FinestradiRicerca.setBounds(300, 300, 500, 500);
//If you don't want to close whole app when closing this windo change it to: JFrame.DISPOSE_ON_CLOSE
FinestradiRicerca.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel riquadroRicerca = new JPanel();
JTextField ciao;
JLabel myLabel = new JLabel("Here goes your label text");
ciao = new JTextField ();
ciao.setColumns(20);
riquadroRicerca.add(myLabel);
riquadroRicerca.add(ciao);
FinestradiRicerca.add(riquadroRicerca);
FinestradiRicerca.setVisible(true);
}
});
}
//Main
public static void main(String[] args) {
//Finestra Principale
JFrame finestra = new JFrame("Finestra principale");
finestra.setSize(500, 500);
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel della finestra principale
JPanel riquadro = new JPanel();
finestra.add(riquadro);
finestra.setVisible(true);
NuovaFinestra(riquadro);
}
}
So, your code after a few modifications, to make JLabel and JTextField visible gives the following output:
However, please follow my above recomendations.

Add the JTextField to your new JFrame like this. You also have to initialize your textfield. It is basically the same as you have done with the initial JFrame.
JTextField ciao = new JTextField();
FinestradiRicerca.add(ciao);

Related

java not displaying jpanel in jframe after button press

I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...

Java.Swing BorderLayout issue

So I'm trying to get the button on the bottom right and the text field taking up the bottom left but it keeps switching around for some reason. I think its borderLayout being stupid. I'm a noob at Java btw. Here's my code:
package textchat;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class window extends JFrame{
public static void main(String[] args)
{
new window();
}
public window()
{
//Window Config
//JFrame frame = new JFrame();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dm = tk.getScreenSize();
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("CALI V1");
this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
//this.setLayout(null);
int Width = this.getWidth();
//Panel(s)
JPanel Panel = new JPanel();
Panel.setLayout(new BorderLayout());
JPanel PanelSouth = new JPanel();
JPanel PanelEast = new JPanel();
JPanel PanelWest = new JPanel();
//button
JButton btn = new JButton("SEND");
//Text Area
JTextArea txt = new JTextArea(100 , 100);
txt.setText("TEXT IS HERE");
//Text Field
JTextField fld = new JTextField("Type Here",15);
//Adding to the panel
Panel.add(txt);
PanelSouth.add(PanelEast, BorderLayout.EAST);
PanelSouth.add(PanelWest, BorderLayout.WEST);
PanelEast.add(btn);
PanelWest.add(fld);
//adding to frame
this.add(Panel);
this.add(PanelSouth , BorderLayout.SOUTH);
this.setVisible(true);
}
}
While using BorderLayout in such a way kind of works, you should
not use it in such a way. Besides, your example has several issues.
For instance, you did not start the application on the EDT (Event Dispatch Tread).
Here is a working example that creates your inteded layout. It uses the powerful GroupLayout manager.
package com.zetcode;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TextChatEx extends JFrame {
public TextChatEx() {
initUI();
}
private void initUI() {
JTextArea area = new JTextArea(15, 15);
JTextField field = new JTextField(15);
JButton sendButton = new JButton("Send");
createLayout(area, field, sendButton);
setTitle("Text chat");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setAutoCreateGaps(true);
gl.setHorizontalGroup(gl.createParallelGroup()
.addComponent(arg[0])
.addGroup(gl.createSequentialGroup()
.addComponent(arg[1])
.addComponent(arg[2]))
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addComponent(arg[0])
.addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(arg[1])
.addComponent(arg[2]))
);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
TextChatEx ex = new TextChatEx();
ex.setVisible(true);
});
}
}
GroupLayout is a powerful layout manager; with this manager, you don't have to create a bunch of panels to create some basic layout.
public TextChatEx() {
initUI();
}
The GUI creation is delegated to the initUI() method. Rather than placing all the code into the constructor, we use a specialized method.
EventQueue.invokeLater(() -> {
TextChatEx ex = new TextChatEx();
ex.setVisible(true);
});
Each Swing application should be placed on the EDT. Failing to do this can lead to hard to find bugs in the future.

How do I add a background image on a JFrame using a JLabel?

I am trying to display a background image on the JFrame using a JLabel. The code runs and the buttons appear, but the image does not. I have researched for solutions, yet I have not found one for my code specifically. Any help would be greatly appreciated.
/**
* Adds details to interface and programs buttons
*
* Imani Davis
* Final Project
*/
import java.awt.*;
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.border.EmptyBorder;
public class Use_PF_Interface extends JFrame implements Pet_Fish_Interface
{
// instance variables - replace the example below with your own
private JFrame window;
private JPanel panel1, panel2, panel3;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
/**
* Constructor for objects of class Use_PF_Interface
*/
public Use_PF_Interface()
{
setTitle("Virtual Pet Fish");
setSize(650, 650);
//initializes panels and panel layout
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel1.setLayout(new FlowLayout());
panel2.setLayout(new FlowLayout());
panel3.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("C:\\Users\\This PC\\Desktop\\OCEAN2.JPEG"));
panel1.add(lblBackgroundImage);
validate();
//adds button to panels
panel2.add(feedButton);
panel2.add(playGamesButton);
//add panels to frame
add(panel1);
add(panel2);
}
}
JFrame uses a BorderLayout by default, a BorderLayout can only manage a single component within any of the five available positions it provides, this means that panel2 is most likely the only component getting shown.
An alternative is to add you components to the JLabel, but remember, JLabel doesn't have a default layout manager. Also, remember, JLabel only uses the icon and text properties to calculate its preferred size, so if the contents require more space, they will be clipped.
Start by having a look at How to Use BorderLayout for more details
Also, remember, most Swing components are opaque generally, so you need to set them transparent when you want to do something like this
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Use_PF_Interface extends JFrame {
// instance variables - replace the example below with your own
private JPanel panel2;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
/**
* Constructor for objects of class Use_PF_Interface
*/
public Use_PF_Interface() {
setTitle("Virtual Pet Fish");
setSize(650, 650);
//initializes panels and panel layout
panel2 = new JPanel();
panel2.setOpaque(false);
panel2.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("..."));
lblBackgroundImage.setLayout(new BorderLayout());
//adds button to panels
panel2.add(feedButton);
panel2.add(playGamesButton);
lblBackgroundImage.add(panel2);
add(lblBackgroundImage);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Use_PF_Interface();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Try this,
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}

How can we put value on text field on output screen?

I want to put value in txtf1 at output screen and get it. How can we put value on text field on output screen?
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class demog extends JPanel implements ActionListener{
private TextField textf, txtf1;
public void jhand(){
textf = new TextField();
textf.setSize(40, 40);
textf.setText("20");
textf.setEditable(false);
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
//textf.setHorizontalAlignment(SwingConstants.CENTER);
textf.setLocation(15, 15);
//textf.addActionListener(this);
txtf1 = new TextField();
txtf1.setSize(40, 40);
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
//txtf1.setHorizontalAlignment(SwingConstants.CENTER);
txtf1.setLocation(50, 50);
JFrame frame = new JFrame("demo");
JPanel p = new JPanel();
p.setOpaque(true);
p.setBackground(Color.WHITE);
p.setLayout(null);
frame.setContentPane(p);
frame.setSize(500,500);
frame.setVisible(true);
p.add(textf);
p.add(txtf1);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
System.out.println(text);
}
public static void main(String... args){
demog g = new demog();
g.jhand();
}
}
You have to change some of your code in order to work. You had some problem in your code which I resolved them for you in the following code. See the comments to learn some in swing ;-)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
// Use upper Case in the start of you class names:
public class Demog extends JPanel implements ActionListener {
private JTextField textf, txtf1;
public Demog() {
jhand();
}
public void jhand() {
setLayout(new FlowLayout()); // Always set the layout before you add components
// you can use null layout, but you have to use setBounds() method
// for placing the components. For an advanced layout see the
// tutorials for GridBagLayout and mixing layouts with each other.
textf = new JTextField(); // Do not mix AWT component with
// Swing (J components. See the packages)
//textf.setSize(40, 40); // Use setPreferredSize instead
textf.setPreferredSize(new Dimension(40, 40));
textf.setText("20");
textf.setEditable(false); // Text fields are for getting data from user
// If you need to show something to user
// use JLabel instead.
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
add(textf);
txtf1 = new JTextField();
//txtf1.setSize(40, 40); Use setPreferredSize instead
txtf1.setPreferredSize(new Dimension(40, 40));
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
add(txtf1);
JButton b = new JButton("Click ME!");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
JOptionPane.showMessageDialog(Demog.this, "\"textf\" text is: "+text);
}
public static void main(String[] args) {
JFrame frame = new JFrame("demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Demog p = new Demog();
p.setBackground(Color.WHITE);
frame.setContentPane(p);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Good Luck.

Blank JPanel after adding a JTextField

Working on adding a GUI to my simple craps simulation program.
Made a new JPanel and added a few JTextFields to it with a default text value. I get no error, and the code runs, but all I get is a blank window with nothing in it.
Here is the code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CrapsGUI extends JFrame
{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField die1 = new JTextField("Die 1",30);
JTextField die2 = new JTextField("Die 2",30);
JTextField sum = new JTextField("Sum",30);
JTextField point = new JTextField("Point",30);
JTextField status = new JTextField("Status",30);
public CrapsGUI()
{
setTitle("Craps Simulator 2013");
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.add(die1);
jp.add(die2);
jp.add(sum);
jp.add(point);
jp.add(status);
}
public static void main(String[] args)
{
Craps craps = new Craps();
CrapsGUI crapsGUI = new CrapsGUI();
}
}
Thanks in advance!
You haven't added the JPanel that contains the visible components.
add(jp);
Three things come to mind
Make sure you are starting your UI's from within the context of the Event Dispatching Thread. See Initial Threads for more details
Call setVisible only after you have finished creating your UI
It would also be helpful if you added something to you frame. Try using add(jp)
try this one:
public static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Sample Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// first text box
JPanel textbox1Panel = new JPanel();
textbox1Panel.setLayout(new BoxLayout(textbox1Panel, 0));
textbox1Panel.setOpaque(true);
textbox1Panel.setBackground(new Color(100, 0, 131));
textbox1Panel.setPreferredSize(new Dimension(300, 300));
textbox1Panel.add(die1);
textbox1Panel.add(die2);
textbox1Panel.add(sum);
textbox1Panel.add(point);
// Set the menu bar and add the label to the content pane.
frame.getContentPane().add(textbox1Panel, BorderLayout.SOUTH);
// Display the window.
frame.pack();
frame.setVisible(true);
}

Categories