JTextField - Java swing - no cursor? - java

Hey guys, see this snipped of code:
JFrame loginFrame = new JFrame("Login");
loginFrame.setSize(500,400);
JPanel loginPanel = new JPanel();
loginPanel.setLayout(new GridLayout(0,2));
JLabel header = new JLabel("Login");
JLabel header2 = new JLabel("blahvlah");
JLabel loginLabel = new JLabel("Login");
JTextField loginField = new JTextField(24);
JLabel passLabel = new JLabel("Password");
JTextField passField = new JTextField(24);
loginPanel.add(header);
loginPanel.add(header2);
loginPanel.add(loginLabel);
loginPanel.add(loginField);
loginPanel.add(passLabel);
loginPanel.add(passField);
loginFrame.add(loginPanel);
loginFrame.setVisible(true);
loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
the JTextFields are present on the app, but i cannot enter anything into them? There is no cursor either, what is the problem? Also my exit on close does not seem to work?
thanks

The code you posted does not compile (on the last line you typed loginframe instead of loginFrame). Having fixed that, the following program:
public class JFrameTest {
public static void main(String[] args) {
JFrame loginFrame = new JFrame("Login");
loginFrame.setSize(500,400);
JPanel loginPanel = new JPanel();
loginPanel.setLayout(new GridLayout(0,2));
JLabel header = new JLabel("Login");
JLabel header2 = new JLabel("blahvlah");
JLabel loginLabel = new JLabel("Login");
JTextField loginField = new JTextField(24);
JLabel passLabel = new JLabel("Password");
JTextField passField = new JTextField(24);
loginPanel.add(header);
loginPanel.add(header2);
loginPanel.add(loginLabel);
loginPanel.add(loginField);
loginPanel.add(passLabel);
loginPanel.add(passField);
loginFrame.add(loginPanel);
loginFrame.setVisible(true);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
runs just fine. I can enter text in both JTextFields and can also close the JFrame:

Related

access input that get from user in UI in java and show them in console

i want save input that i get from user and save them in element .
i want to access elements that user write in my UI.
and if i want save the elements in array list which kind of array list i should build.
in my UI i have text field name and text field middle name and combo box city has got 3 city name and and a radio box that it depend sex.
in final show them in console what should i do ?
this all of my code:
package ui;
import java.awt.*;
import javax.swing.*;
public class UI extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(500, 600);
BorderLayout blayout = new BorderLayout();
JButton center = new JButton();
JButton north = new JButton();
JButton south = new JButton();
JComboBox combo = new JComboBox();
combo.addItem("-");
combo.addItem("Tehran");
combo.addItem("Tabriz");
combo.addItem("Shiraz");
JRadioButton rb1 = new JRadioButton("man");
JRadioButton rb2 = new JRadioButton("weman");
frame.setLayout(blayout);
FlowLayout fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
JLabel jb1 = new JLabel("Name :");
JTextField name = new JTextField(20);
center.add(jb1);
center.add(name);
JLabel jb2 = new JLabel("Family :");
JTextField family = new JTextField(20);
center.add(jb2);
center.add(family);
JLabel jb4 = new JLabel("City :");
center.add(jb4);
center.add(combo);
JLabel jb5 = new JLabel("Sex :");
center.add(jb5);
center.add(rb1);
center.add(rb2);
JLabel jb6 = new JLabel("Comment :");
JTextField comment = new JTextField(50);
JLabel jb7 = new JLabel("Save");
south.add(jb7);
JPanel cpanel = new JPanel();
cpanel.add(center);
JPanel spanel = new JPanel();
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
cpanel.add(jb6);
cpanel.add(comment);
frame.add(cpanel,BorderLayout.CENTER);
frame.add(spanel,BorderLayout.SOUTH);
}
}
You need to use listeners to create code that runs when ui component is pressed. I added listener to every component. try it:
public class UI extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout blayout = new BorderLayout();
JButton center = new JButton();
JButton north = new JButton();
JButton south = new JButton();
south.addActionListener(e->{System.out.println("Save button is pressed");});
JComboBox combo = new JComboBox();
combo.addItem("-");
combo.addItem("Tehran");
combo.addItem("Tabriz");
combo.addItem("Shiraz");
combo.addActionListener(e -> {
System.out.println(((JComboBox<String>) e.getSource()).getSelectedItem());
});
JRadioButton rb1 = new JRadioButton("man");
rb1.addActionListener(e -> {
System.out.println("man: " + ((JRadioButton) e.getSource()).isSelected());
});
JRadioButton rb2 = new JRadioButton("weman");
rb2.addActionListener(e -> {
System.out.println("weman: " + ((JRadioButton) e.getSource()).isSelected());
});
frame.setLayout(blayout);
FlowLayout fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
JLabel jb1 = new JLabel("Name :");
JTextField name = new JTextField(20);
center.add(jb1);
center.add(name);
name.addActionListener(e -> {
System.out.println("name: " + ((JTextField) e.getSource()).getText());
});
JLabel jb2 = new JLabel("Family :");
JTextField family = new JTextField(20);
center.add(jb2);
center.add(family);
family.addActionListener(e -> {
System.out.println("family: " + ((JTextField) e.getSource()).getText());
});
JLabel jb4 = new JLabel("City :");
center.add(jb4);
center.add(combo);
JLabel jb5 = new JLabel("Sex :");
center.add(jb5);
center.add(rb1);
center.add(rb2);
JLabel jb6 = new JLabel("Comment :");
JTextField comment = new JTextField(50);
comment.addActionListener(e -> {
System.out.println("comment: " + ((JTextField) e.getSource()).getText());
});
JLabel jb7 = new JLabel("Save");
south.add(jb7);
JPanel cpanel = new JPanel();
cpanel.add(center);
JPanel spanel = new JPanel();
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
cpanel.add(jb6);
cpanel.add(comment);
frame.add(cpanel, BorderLayout.CENTER);
frame.add(spanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
You will have to put JRadioButton into RadioGroup to select one of them.
At first, you need to check your GUI, because from skimming it works not good. Later you can get data from the different component using an appropriate listener for each component or you can use any General button to reading data from all components and print it in a console or anywhere else.
To get data from combo, for example, will be here:
String data = combo.getSelectedIndex();
More information you can get here:
How can I get the user input in Java?

new line in JLabel and JTextField in Flow Layout

I am using FlowLayout and trying to make JLabels and JTextField in order but I am stuck and do not know how to do it.
public class SoftwareProducts extends JPanel implements ActionListener {
JTextField ramtf;
JTextField processortf;
JTextField productIDtf;
JTextField productNametf;
JTextField productYeartf;
JTextField productPublishHousetf;
JButton CompleteOrder;
JLabel Ramlb = new JLabel("RAM:");
JLabel processorlb = new JLabel("Processor:");
JLabel productIDlb = new JLabel("Product ID");
JLabel productNamelb = new JLabel("Product Name:");
JLabel productYearlb = new JLabel("Product Year:");
JLabel PublishHouselb = new JLabel("Publish House:");
JPanel softwarePanel;
CardLayout c2 = new CardLayout();
CompleteOrder completeOrder;
public static void main(String[] args) {
new SoftwareProducts();
}
public SoftwareProducts() {
setSize(500, 300);
setLayout(new FlowLayout());
add(Ramlb);
Ramlb.setFont(new Font("Arial", 5, 28));
ramtf = new JTextField(15);
add(ramtf);
ramtf.addActionListener(this);
add(processorlb);
processortf = new JTextField(15);
processortf.addActionListener(this);
add(processortf);
add(productIDlb);
productIDtf = new JTextField(10);
productIDtf.addActionListener(this);
add(productIDtf);
add(productNamelb);
add(productNamelb);
productNametf = new JTextField(10);
productNametf.addActionListener(this);
add(productNametf);
add(productYearlb);
productYeartf = new JTextField(10);
productYeartf.addActionListener(this);
add(productYeartf);
add(PublishHouselb);
productPublishHousetf = new JTextField(10);
productPublishHousetf.addActionListener(this);
add(productPublishHousetf);
CompleteOrder = new JButton("CompleteOrder");
CompleteOrder.setSize(25, 40);
CompleteOrder.addActionListener(this);
add(CompleteOrder);
softwarePanel = new JPanel(new FlowLayout());
softwarePanel.add(Ramlb);
softwarePanel.setLayout(c2);
completeOrder = new CompleteOrder();
softwarePanel.add(new JPanel(), "empty");
softwarePanel.add(completeOrder, "completeOrder");
this.add(softwarePanel);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == CompleteOrder) {
c2.show(softwarePanel, "completeOrder");
float ram = Float.parseFloat(ramtf.getText());
float processor = Float.parseFloat(processortf.getText());
int productID = Integer.parseInt(productIDtf.getText());
String productName = productNametf.getText();
int productYear = Integer.parseInt(productYeartf.getText());
String productPublishHouse = productPublishHousetf.getText();
main.softwareList.add(new Software(productID, productName, productYear, productPublishHouse));
ramtf.setText("");
System.out.println("Saved");
}
}
}
What code would result in it new lines breaks in each line? Shat should to be done to make the line breaks down in JLabel and LTextField?
These are two completely different problems and neither of them has anything to do with the LayoutManager.
For the JTextField:
Taken from the docs:
JTextField is a lightweight component that allows the editing of a single line of text
There's no way at all to add a newline to a JTextField (atleast no legit way). Use a JTextArea instead; newlines are just like in the console \n.
JLable like most other JComponents aswell can process and display HTML-code. So a newline in a JLabel would look like this:
JLabel twoLined = new JLabel("This is one line</br>And this is another one");

Java scrollbar not visible

I am new to java. I am trying to implement scroll feature to my Jpanel but the schoolpane is not visible. I tried to many methods but nothing works.
public class test extends ContentPanel {
JPanel secondary;
JPanel customerType;
JPanel primary;
JPanel labelPanel;
JLabel lCustNo;
JLabel lCustName;
JLabel lTelNo;
JLabel lAddress;
JLabel lNationality;
JLabel lResident;
JLabel lVisitor;
JLabel lCustomerType;
JLabel lIdCard;
JLabel lBankName;
JLabel lPassportNo;
JLabel lVisitStart;
JLabel lVisitEnd;
JTextField tCustNo;
JTextField tCustName;
JTextField tTelNo;
JTextField tAddress;
JTextField tNationality;
JTextField tIdCard;
JTextField tBankName;
JTextField tPassportNo;
JTextField tVisitStart;
JTextField tVisitEnd;
JPanel radioButton;
JRadioButton rResident;
JRadioButton rVisitor;
ButtonGroup custType;
JScrollPane scrollBar;
JSeparator s1;
public test (String title, JPanel parent) {
super(title, parent);
secondary = new JPanel(new GridLayout(2,0));
secondary.setBounds(10, 10, 500, 800);
labelPanel = new JPanel(new GridLayout(5,2,300,20));
radioButton = new JPanel(new GridLayout(1, 4));
customerType = new JPanel(new GridLayout(3,4, 30, 20));
primary = new JPanel(new BorderLayout());
lCustNo = new JLabel("Customer No: ");
lCustName = new JLabel("Name: ");
lTelNo = new JLabel("Telephone Number: ");
lAddress = new JLabel("Address: ");
lNationality = new JLabel("Nationality: ");
lResident = new JLabel("Resident");
lVisitor = new JLabel("Visitor");
lCustomerType = new JLabel("Customer Type");
lIdCard = new JLabel("Id Card");
lBankName = new JLabel("Bank Name");
lPassportNo = new JLabel("Passport Number");
lVisitStart = new JLabel("Visit Start");
lVisitEnd = new JLabel("Visit End");
tCustNo = new JTextField(10);
tCustName = new JTextField(10);
tTelNo = new JTextField(10);
tAddress = new JTextField(10);
tNationality = new JTextField(10);
tIdCard = new JTextField(10);
tBankName = new JTextField(10);
tPassportNo = new JTextField(10);
tVisitStart = new JTextField(10);
tVisitEnd = new JTextField(10);
rResident = new JRadioButton();
rVisitor = new JRadioButton();
custType = new ButtonGroup();
customerType.add(lPassportNo);
customerType.add(tPassportNo);
customerType.add(lVisitStart);
customerType.add(tVisitStart);
customerType.add(lIdCard);
customerType.add(tIdCard);
customerType.add(lBankName);
customerType.add(tBankName);
customerType.add(lVisitEnd);
customerType.add(tVisitEnd);
custType.add(rResident);
custType.add(rVisitor);
radioButton.add(lVisitor);
radioButton.add(rVisitor);
radioButton.add(lResident);
radioButton.add(rResident);
labelPanel.add(lCustNo);
labelPanel.add(tCustNo);
labelPanel.add(lCustName);
labelPanel.add(tCustName);
labelPanel.add(lTelNo);
labelPanel.add(tTelNo);
labelPanel.add(lAddress);
labelPanel.add(tAddress);
labelPanel.add(lNationality);
labelPanel.add(tNationality);
secondary.add(customerType);
secondary.add(labelPanel);;
primary.add(secondary,BorderLayout.CENTER);
scrollBar= new JScrollPane(primary);
scrollBar.setBounds(10, 10, 400, 555);
this.add(scrollBar);
}
}
My code is above. This class extends contentPanel and contentPanel extends JPanel. Someone please help me.
Thanks.
Your scrollBar is not visible because it is not necessary. If you change JScrollPane settings, for example:
scrollBar.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollBar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
you will see you have it, but not use it. It is because your scrollBar doesn't have a content which expands dynamically (like JTextArea for example). Your scrollBar has JPanel inside, which has size to fit all its components, so it will not be enough to add some text inside text components.
To make scroll bars visible, you can change a size of JSrollPane. However setBound() will not work if you JPanel use default FlowLayout. To use absolute positioning in JPanel you need to use null layout, what is generally not recommended and is seen as bad programming practice.
Try to delete setBound() lines and use for example scrollBar.setPreferredSize(new Dimension(400,555)); instead. You should see a difference.

Trying to layout JPanels. Java program layout changes every time I run

First time posting so go easy on me.
I am new to Java and am trying to get 3 JPanels to line up on top of each other. The first image is how I want it to look and it does sometimes when I run the program but as you can see by the other images it doesn't line up every time I run it. Sometimes not even showing some of the images/components.
So how can I get three JPanels to line up one after the other vertically?
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class FrameMain {
static final int MY_MINIMUM = 0;
static final int MY_MAXIMUM = 100;
public static void main(String[] args) {
JFrame frame1 = new JFrame("Harvest Frame Test");
frame1.setVisible(true);
frame1.setSize(800,700);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Container Panel
JPanel container = new JPanel();
container.setSize(800,700);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
frame1.add(container);
//First Panel
JPanel panel1 = new JPanel();
panel1.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel1);
JButton button1 = new JButton("Add Water");
panel1.add(button1);
JButton button2 = new JButton("Add Food");
panel1.add(button2);
JButton button3 = new JButton("Add Medicine");
panel1.add(button3);
ImageIcon image = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel = new JLabel(image);
panel1.add(imagelabel);
JProgressBar pbar = new JProgressBar();
pbar.setMinimum(MY_MINIMUM);
pbar.setMaximum(MY_MAXIMUM);
// add to JPanel
panel1.add(pbar);
// Second Panel
JPanel panel2 = new JPanel();
panel2.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel2);
JButton button4 = new JButton("Add Water");
panel2.add(button4);
JButton button5 = new JButton("Add Food");
panel2.add(button5);
JButton button6 = new JButton("Add Medicine");
panel2.add(button6);
ImageIcon image1 = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel1 = new JLabel(image1);
panel2.add(imagelabel1);
JProgressBar pbar1 = new JProgressBar();
pbar1.setMinimum(MY_MINIMUM);
pbar1.setMaximum(MY_MAXIMUM);
// add to JPanel
panel2.add(pbar1);
// Third Panel
JPanel panel3 = new JPanel();
panel3.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
container.add(panel3);
JButton button7 = new JButton("Add Water");
panel3.add(button7);
JButton button8 = new JButton("Add Food");
panel3.add(button8);
JButton button9 = new JButton("Add Medicine");
panel3.add(button9);
ImageIcon image2 = new ImageIcon("C:/Users/Nick/Documents/EclipseArt/plant.gif");
JLabel imagelabel2 = new JLabel(image2);
panel3.add(imagelabel2);
JProgressBar pbar2 = new JProgressBar();
pbar2.setMinimum(MY_MINIMUM);
pbar2.setMaximum(MY_MAXIMUM);
// add to JPanel
panel3.add(pbar2);
}
//static class Action implements ActionListener {
//public void actionPerformed (ActionEvent e){
//}
//}
}
Move the frame1.setVisible(true); all the way to the bottom. Changing Components on a frame that is already visible can cause issues.

Content in JPanel won't appear

There is no errors but when I Run it the content that I added into the JPanel won't appear, only the one not inside the JPanel appear.
import javax.swing.*;
import java.awt.*;
public class SimpleGUI extends JFrame
{
public static void main(String arg[])
{
SimpleGUI f = new SimpleGUI("GUI components");
f.setSize(600,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
SimpleGUI(String s)
{
setTitle(s);
setLayout(new GridLayout(3,2));
JLabel msg = new JLabel("FINAL EXAM IS JUST AROUND THE CORNER!");
JButton bt = new JButton("OK");
JLabel lb = new JLabel ("Enter your name:");
JTextField tf = new JTextField("<type name here>");
JLabel lb2 = new JLabel ("Enter age:");
JTextField tf2= new JTextField(10);
tf2.setHorizontalAlignment(JTextField.RIGHT);
JCheckBox cb = new JCheckBox("Bold",true);
JRadioButton rb1 = new JRadioButton("Red");
JTextArea ta = new JTextArea(5,20);
JList list = new JList(new Object[] {"Block A", "Block B"});
JComboBox jcb = new JComboBox(new Object[] {"Hello", "Bye"});
ImageIcon ic = new ImageIcon("music.gif");
JButton newbt = new JButton("Play",ic);
newbt.setVerticalTextPosition(JButton.TOP);
newbt.setHorizontalTextPosition(JButton.CENTER);
JPanel p1 = new JPanel();
p1.setLayout(new BorderLayout());
p1.add(lb, BorderLayout.WEST);
p1.add(tf, BorderLayout.CENTER);
p1.add(cb, BorderLayout.EAST);
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(lb2, BorderLayout.WEST);
p2.add(tf2, BorderLayout.CENTER);
p2.add(rb1, BorderLayout.EAST);
JPanel p3 = new JPanel();
p3.setLayout(new BorderLayout());
p3.add(jcb);
add(ta);
add(list);
p3.add(newbt, BorderLayout.NORTH);
add(msg);
p3.add(bt, BorderLayout.SOUTH);
}
}
I've updated your code. Have a look at this version:
import javax.swing.*;
import java.awt.*;
public class SimpleGUI extends JFrame {
public static void main(String arg[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SimpleGUI f = new SimpleGUI("GUI components");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
public SimpleGUI(String s) {
setTitle(s);
setLayout(new GridLayout(3, 2));
JLabel msg = new JLabel("FINAL EXAM IS JUST AROUND THE CORNER!");
JButton bt = new JButton("OK");
JLabel lb = new JLabel("Enter your name:");
JTextField tf = new JTextField("<type name here>");
JLabel lb2 = new JLabel("Enter age:");
JTextField tf2 = new JTextField(10);
tf2.setHorizontalAlignment(JTextField.RIGHT);
JCheckBox cb = new JCheckBox("Bold", true);
JRadioButton rb1 = new JRadioButton("Red");
JTextArea ta = new JTextArea(5, 20);
JList list = new JList(new Object[]{"Block A", "Block B"});
JComboBox jcb = new JComboBox(new Object[]{"Hello", "Bye"});
ImageIcon ic = new ImageIcon("music.gif");
JButton newbt = new JButton("Play", ic);
newbt.setVerticalTextPosition(JButton.TOP);
newbt.setHorizontalTextPosition(JButton.CENTER);
JPanel p1 = new JPanel();
p1.setLayout(new BorderLayout());
p1.add(lb, BorderLayout.WEST);
p1.add(tf, BorderLayout.CENTER);
p1.add(cb, BorderLayout.EAST);
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(lb2, BorderLayout.WEST);
p2.add(tf2, BorderLayout.CENTER);
p2.add(rb1, BorderLayout.EAST);
JPanel p3 = new JPanel();
p3.setLayout(new BorderLayout());
p3.add(jcb);
add(ta);
add(list);
p3.add(newbt, BorderLayout.NORTH);
add(msg);
p3.add(bt, BorderLayout.SOUTH);
/**
* Need to add the following lines
*/
this.add(p1);
this.add(p2);
this.add(p3);
this.pack();
this.setVisible(true);
}
}
A couple of pointers:
You need to add your components to your JFrame for them to actually show up.
Any updates to the user interface must happen on the event dispatch thread. Consequently you would notice that I've added a SwingUtilites.invokeLater() to the main. Have a look at this article to understand "Threading with Swing"
Where you you add your panels to the frame? Also, forgotten my java "rules and regulations": do you need to call "super()"?

Categories