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

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.

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

JButton does not open JDialog

I am building a simple program. I have a class that extends from JDialog and class that extends from JFrame and is GUI of the application. I implemented ActionListener which should open the dialog after clicking on the JButton. Nothing happens though and I can't figure out why.
GUI
package nemocnice_sam;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class App extends JFrame {
JTable tbl = new JTable();
JButton pridejPacienta = new JButton("Přidej pacienta");
JButton smazPacienta = new JButton("Smaž pacienta");
JButton export = new JButton("Export");
JButton konec = new JButton("Konec");
JPanel panel = new JPanel();
PacientDialog novyPacient;
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == pridejPacienta){
novyPacient = new PacientDialog();
novyPacient.setModal(true);
novyPacient.setVisible(true);
}
}
};
SeznamPacientu pacienti = new SeznamPacientu();
ModelPacientu model = new ModelPacientu(pacienti);
public static void main(String[] args) {
new App();
}
public App() {
setLayout(new BorderLayout());
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(pridejPacienta);
panel.add(smazPacienta);
panel.add(export);
panel.add(konec);
add(panel,BorderLayout.NORTH);
tbl.setModel(model);
add(new JScrollPane(tbl), BorderLayout.CENTER);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
}
DIALOG CLASS
package nemocnice_sam;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class PacientDialog extends JDialog {
JTextField jmeno = new JTextField();
JTextField prijmeni = new JTextField();
JTextField rc = new JTextField();
JTextField cp = new JTextField();
JButton ok = new JButton("OK");
public PacientDialog(){
setLayout(new GridLayout(5,2));
add(new JLabel("Jméno:"));
add(jmeno);
add(new JLabel("Příjmení:"));
add(prijmeni);
add(new JLabel("RČ:"));
add(rc);
add(new JLabel("ČP:"));
add(cp);
pack();
}
}
You need to define the actionListener in button.
konec.addActionListener(al);
Defining an ActionListener alone is not sufficient.
In order to do its job, that listener must be registered with some component that actually sends Events to that Listener.
So you have it to add to the corresponding button for example, like:
pridejPacienta.addActionListener(al);
Besides: when you do that, you do not need that if (source == check within your action listener. You see, when each button has a distinct listener, then there will not be different sources.
You only need such kinds of checks when you want to attach the same ActionListener to multiple buttons!

JList position resets to default whenever update occurs

list is to accept input from Action1 this works, however, whenever a new element is added to the list, the list's position moves back to the default top-middle position.
This also occurs when the frame is resized, so as a temporary fix I the line frame.setResizable(false) but I do not want that to be permanent.
How would I fix both of these issues?
import static java.lang.String.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class lists
{
static String newUrl;
static DefaultListModel<String> model = new DefaultListModel<String>();
static int listXCoord = 650;
static int listYCoord = 10;
public static void createGUI()
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel panel = new JPanel();
frame.add(panel);
JButton addurl = new JButton("Add URL");
panel.add(addurl);
addurl.addActionListener(new Action1());
JButton remurl = new JButton("Remove URL");
panel.add(remurl);
//model.addElement("one");
//model.addElement("two");
//model.addElement("three");
JList list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
list.setLocation(listXCoord, listYCoord);
list.setBackground(new Color(186, 203, 250));
//list.setLocation(650, 10);
panel.add(list);
list.setSize(130, 540);
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
newUrl = JOptionPane.showInputDialog("Enter the URL to be Launched");
model.addElement(newUrl);
}
}
public static void main(String[] args)
{
createGUI();
}
}
Basically, you're fighting the layout manager (Flowlayout) and losing. When you add a new element to the JList, the container hierarchy is been revalidated which is causing the layout managers to re-layout the contents of their containers
The basic solution would be to use a different layout, but, JFrame uses a BorderLayout, so instead of adding the JList to the JPanel, you could simply add it to the EAST position of the frame instead
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Lists {
static String newUrl;
static DefaultListModel<String> model = new DefaultListModel<String>();
static int listXCoord = 650;
static int listYCoord = 10;
public static void createGUI() {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton addurl = new JButton("Add URL");
panel.add(addurl);
addurl.addActionListener(new Action1());
JButton remurl = new JButton("Remove URL");
panel.add(remurl);
//model.addElement("one");
//model.addElement("two");
//model.addElement("three");
JList list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
list.setLocation(listXCoord, listYCoord);
list.setBackground(new Color(186, 203, 250));
//list.setLocation(650, 10);
frame.add(new JScrollPane(list), BorderLayout.EAST);
frame.setVisible(true);
}
static class Action1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
newUrl = JOptionPane.showInputDialog("Enter the URL to be Launched");
model.addElement(newUrl);
}
}
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();
}
createGUI();
}
});
}
}
See Laying Out Components Within a Container, How to Use BorderLayout and How to use FlowLayout for more details.
You should also be calling setVisible last, after all the components have been added to the frame, this reduces the possibilities that some of your components won't be displayed when you think they should be.
JList will also benefit from been contained within a JScrollPane. See How to Use Lists and How to Use Scroll Panes for more details

Java cannot instantiate type ActionListener

im trying to add an ActionListener to my buttons for my calculator Im making. The problem is that Im being presented an error when I try to make an ActionListener. I tried in one class then I created a listener class just to see if that would help. Here is my code:
package main;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public abstract class Main extends JFrame implements Listener{
public static void main(String[] args) throws IOException{
//Main variables
String dis = "0";
double ans = Double.parseDouble(dis);
//Making frames
JFrame frame = new JFrame("Calculator");
JPanel panel = new JPanel();
//Buttons
JButton enter = new JButton("Enter");
JButton sub = new JButton("-");
JButton add = new JButton("+");
JButton div = new JButton("÷");
JButton mult = new JButton("*");
JTextField text = new JTextField(dis);
//Font
Font bigFont = text.getFont().deriveFont(Font.PLAIN, 30f);
Font butf = text.getFont().deriveFont(Font.PLAIN, 20f);
//Methods
panel.setLayout(new FlowLayout());
panel.add(text);
panel.setSize(590, 100);
text.setColumns(22);
text.setFont(bigFont);
text.setHorizontalAlignment(JTextField.RIGHT);
text.setEditable(false);
enter.setForeground(Color.RED);
sub.setForeground(Color.RED);
div.setForeground(Color.RED);
mult.setForeground(Color.RED);
add.setForeground(Color.RED);
//Buttons Methods
enter.setBounds(470, 450, 100, 150);
sub.setBounds(470, 350, 100, 90);
div.setBounds(470, 250, 100, 90);
mult.setBounds(470, 150, 100, 90);
add.setBounds(470, 50, 100, 90);
enter.setFont(butf);
sub.setFont(butf);
div.setFont(butf);
mult.setFont(butf);
add.setFont(butf);
//Frame
frame.add(div);
frame.add(mult);
frame.add(sub);
frame.add(enter);
frame.add(add);
frame.add(panel);
frame.setSize(600, 650);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//extra
text.setSize(1000, 100);
//Actions
}
}
package main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public interface Listener extends ActionListener {
//Throwing error here 'Cant instantiate the type ActionListener'
ActionListener al = new ActionListener();
public default void actionPerformed(ActionEvent e){
}
}
Anyone know how to fix this error?
To declare an ActionListener use
public class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//dostuff
}
}
ActionListener is a interface, it can't be instantiated, without provide a concrete implementation of it's contract
interfaces can't contain instance fields
Simply speaking, it should look more like...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public interface Listener extends ActionListener {
public default void actionPerformed(ActionEvent e) {
}
}
You may also like to have a closer look at
How to Write an Action Listeners
What Is an Interface?
The Interfaces trail
In Swing, you should make sure that your UI is only created and manipulated from within the context of the Event Dispatching Thread. Have a look at Initial Threads for more details
You're also going to be very disappointed with the results of your layout, have a look at Laying Out Components Within a Container for better solutions

Switching between JPanels in different classes

I've stumbled upon this complications and have spent more than 4 hours debugging and googling but to no avail..
Basically what I have here is 1 JFrame, 2 JPanels.
I had my JFrame setContentPane to 1 of the JPanel, and when I run the Application, the JFrame will appear with the JPanel inside.
Now this JPanel have 1 JButton inside it, when I click it I want it to switch to another JPanel. As you can see from the code, when I click the JButton(Add Product), I want the OnlineShopAdPane to switch to AddProduct. I tried using CardLayout but it only has NSEW formatting.
package OnlineShop.ui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class OnlineShopMainFrame extends JFrame {
/**
* Launch the application.
*/
AddProduct Add;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OnlineShopMainFrame MainFrame = new OnlineShopMainFrame();
MainFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public OnlineShopMainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
OnlineShopAdPane AdPanel = new OnlineShopAdPane();
setContentPane(AdPanel);
}
}
package OnlineShop.ui;
import javax.swing.JPanel;
import java.awt.CardLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
public class OnlineShopAdPane extends JPanel {
/**
* Create the panel.
*/
public OnlineShopAdPane() {
JLabel lblWhatDoYou = new JLabel("What do you want to do?");
lblWhatDoYou.setBounds(28, 26, 160, 26);
add(lblWhatDoYou);
JButton btnAddProduct = new JButton("Add Product");
btnAddProduct.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OnlineShopMainFrame MainFrame = new OnlineShopMainFrame();
MainFrame.removeAll();
MainFrame.add(new AddProduct());
MainFrame.revalidate();
MainFrame.repaint();
}
});
btnAddProduct.setBounds(46, 75, 115, 23);
add(btnAddProduct);
}
}
package OnlineShop.ui;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddProduct extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public AddProduct() {
JLabel lblProductName = new JLabel("Product Name:");
lblProductName.setBounds(35, 26, 77, 24);
add(lblProductName);
JLabel lblProductDescription = new JLabel("Product Description:");
lblProductDescription.setBounds(10, 50, 106, 24);
add(lblProductDescription);
textField = new JTextField();
textField.setBounds(116, 28, 141, 20);
add(textField);
textField.setColumns(10);
JTextArea textArea = new JTextArea();
textArea.setBounds(116, 66, 141, 112);
add(textArea);
JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnClose.setBounds(223, 244, 89, 23);
add(btnClose);
}
}
I tried using CardLayout but it only has NSEW formatting.
What does that mean? A CardLayout simply contains two or more panels. Only one panel is visible at a time. Each panel can use whatever layout it wants to layout the components on the panel.
when I click it I want it to switch to another JPanel.
That is exactly what CardLayout does. See the Swing tutorial on How to Use Card Layout for a working example and explanation.
Whenever I see code like remove/add/revalidate/repaint it should almost always be replaced with a CardLayout
I think that with CardLayout you can resolve it, but another way is using for example a Handler to switch your panels.
private JComponent container; // this could be your Frame
private JComponent loadedComponent;
public void loadContent(JComponent component, Object object ) {
if (loadedComponent != null) {
loadedComponent.setVisible(false);
container.remove(loadedComponent);
loadedComponent = null;
}
//TODO may check layout
container.add(component,object);
component.setVisible(true);
loadedComponent = component;
container.validate();
}
The problem is pobably located at the following lines in class OnlineShopAdPane.java
OnlineShopMainFrame MainFrame = new OnlineShopMainFrame();
MainFrame.removeAll();
MainFrame.add(new AddProduct());
MainFrame.revalidate();
MainFrame.repaint();
your not referring to the frame where your JPanel is nested. instead your creating a new OnlineShopMainFrame

Categories