Swing JLabel text change on the running application - java

I have a Swing window which contains a button a text box and a JLabel named as flag. According to the input after I click the button, the label should change from flag to some value.
How to achieve this in the same window?

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:
jLabel.setText("new Value");
A simple demo code will be:
JFrame frame = new JFrame("Demo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250,100);
final JLabel label = new JLabel("flag");
JButton button = new JButton("Change flag");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
label.setText("new value");
}
});
frame.add(label, BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.setVisible(true);

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}

Related

Removing a textfield from JFrame dynamically

I want to remove the text field upon selecting the radio button "don't show field" but unable to do so. I have used repaint and revalidate methods. I also tried making the field invisible by setting visibility to false but nothing seems to be working.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
new Frame();
}
}
class Frame
{
private JFrame frame;
private JButton button;
private ImageIcon img;
private JRadioButton b1;
private JRadioButton b2;
private JTextField text;
public Frame()
{
frame = new JFrame();
text=new JTextField(10);
b1=new JRadioButton("show Field");
b2=new JRadioButton("Dont show field");
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
img = new ImageIcon("Letter-S-icon.png");
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg) {
if(arg.getSource()==b1)
{
frame.add(text);
frame.revalidate();
frame.repaint();
}
else if(arg.getSource()==b2)
{
text.setVisible(false);
frame.remove(text);//cannot remove this even after repaint();
frame.revalidate();
frame.repaint();
}
}
});
frame.add(b1);
frame.add(b2);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
frame.setBounds(500, 200, 200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setIconImage(img.getImage());
}
}

how to align buttons in the middle java

I am a beginner in Java, but somehow have a bit of knowledge but still beyond. I wanted to ask , how do align buttons in this main menu I just created. The buttons are somehow aligned horizontally.
This is my code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class mainmenu extends JFrame
{
JButton b1;
JLabel l1;
JButton b2;
public mainmenu() {
setResizable(false);
setLocation(100, 100);
setSize(500, 500);
setVisible(true);
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Master Boat\\Desktop\\PH\\BG HOROR.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
b2=new JButton(" EXIT! ");
b1.addActionListener(new btnFunc());
background.add(l1);
background.add(b1);
background.add(b2);
}
public void armaged() {
add(new gamesamplingbeta());
}
public static void main(String args[])
{
new mainmenu();
}
public class btnFunc implements ActionListener {
public void actionPerformed (ActionEvent e) {
}
}
public class btnFunc2 implements ActionListener {
public void actionPerformed2 (ActionEvent e) {
System.exit(1);
}
}
}
You should take a look at Swing Layouts for a whole bunch of different layout managers that allow you to position your components in a bunch of different ways.
The one I believe you should be using for this question is the Box Layout if you would like your buttons centered vertically.
Here is an example of one.
import javax.swing.*;
import java.awt.*;
public class MainFrame
{
JFrame mainFrame = new JFrame("Main Frame");
JPanel mainPanel = new JPanel();
JLabel label1 = new JLabel("Vertical Buttons");
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
public MainFrame()
{
label1.setAlignmentX(Component.CENTER_ALIGNMENT);
button1.setAlignmentX(Component.CENTER_ALIGNMENT);
button2.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(label1);
mainPanel.add(button1);
mainPanel.add(button2);
mainFrame.add(mainPanel);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
If you would like to add spacing in between any of the components, use a Rigid Area like so
container.add(component);
container.add(Box.createRigidArea(new Dimension(100, 100));
container.add(component1);

How to add a button to a JFrame Gui

I'm trying to add a button to a frame gui.
i tried making a panel and adding it to that, but it does not work.
please help!
here is my code:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button;
JPanel panel;
// my error lines are under the "panel" and "button"
// it says i must implement the variables. what does that mean???
panel.add(button);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
Change:
JButton button;
JPanel panel;
to:
JButton button = new JButton();
JPanel panel = new JPanel();
You can also pass a String value in JButton() constructor for that string value to be shown on the JButton.
Example: JButton button = new JButton("I am a JButton");
Example Code:
import javax.swing.*;
public class Agui extends JFrame {
public Agui() {
setTitle("My Gui");
setSize(400, 400);
// Create JButton and JPanel
JButton button = new JButton("Click here!");
JPanel panel = new JPanel();
// Add button to JPanel
panel.add(button);
// And JPanel needs to be added to the JFrame itself!
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Agui a = new Agui();
}
}
Output:
Note:
Create the JButton and JPanel using new JButton("..."); and new JPanel()
Add the JPanel to the JFrame's content pane using getContentPane().add(...);
If you can Change this Program, You can adjust the button place also
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class agui extends JFrame
{
agui()
{
setTitle("My GUI");
setSize(400,400);
setLayout(null);
JButton button = new JButton("Click Here..!");
button.setBounds(50,100,100,50); /*Distance from left,
Distance from top,length of button, height of button*/
add(button);
setVisible(true);
}
public static void main(String[] args)
{
JFrame agui = new agui();
}
}
Output

Swing Methods on submission of button

How to close current frame (Frame1) and open a new frame (Frame2) already created and pass the data to frame2 from frame1 on the clicking of button?
Use a CardLayout1. Either that or one JFrame and one or more JDialog2 instances.
How to Use CardLayout
How to Make Dialogs
The very best way to accomplish this, is very much told to you by #Andrew Thompson.
And the other way to accomplish, the motive of the question as described in the code. Here as you make object of your new JFrame, you have to pass the things you need in the other class as an argument to the other class, or you can simply pass the object(with this you be passing everything in one go to the other class)
A sample code for a bit of help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFramesExample
{
public JFrame frame;
private JPanel panel;
private JButton button;
private JTextField tfield;
private SecondFrame secondFrame;
public TwoFramesExample()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
tfield = new JTextField(10);
tfield.setBackground(Color.BLACK);
tfield.setForeground(Color.WHITE);
button = new JButton("NEXT");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Here we are passing the contents of the JTextField to another class
// so that it can be shown on the label of the other JFrame.
secondFrame = new SecondFrame(tfield.getText());
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(tfield, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFramesExample();
}
});
}
}
class SecondFrame
{
private JFrame frame;
private JPanel panel;
private JLabel label;
private JButton button;
private TwoFramesExample firstFrame;
public SecondFrame(String text)
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
label = new JLabel(text);
button = new JButton("BACK");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
firstFrame = new TwoFramesExample();
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(label, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
}
Hope this be of some help.
Regards

java - How would I dynamically add swing component to gui on click?

What I am looking to do is a similar principle to adding attachments to emails, you can click a button and a new browse box would open increasing the number of separate attachments you can have.
I'm fairly new so if someone could point me towards an example?
Sample code to add Buttons on the fly dynamically.
panel.add(new JButton("Button"));
validate();
Full code:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
public class AddComponentOnJFrameAtRuntime extends JFrame implements ActionListener {
JPanel panel;
public AddComponentOnJFrameAtRuntime() {
super("Add component on JFrame at runtime");
setLayout(new BorderLayout());
this.panel = new JPanel();
this.panel.setLayout(new FlowLayout());
add(panel, BorderLayout.CENTER);
JButton button = new JButton("CLICK HERE");
add(button, BorderLayout.SOUTH);
button.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
this.panel.add(new JButton("Button"));
this.panel.revalidate();
validate();
}
public static void main(String[] args) {
AddComponentOnJFrameAtRuntime acojfar = new AddComponentOnJFrameAtRuntime();
}
}
Resource
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setLayout(new GridLayout(0, 1));
frame.add(new JButton(new AbstractAction("Click to add") {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.add(new JLabel("Bla"));
frame.validate();
frame.repaint();
}
});
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
Component was not visible until setSize() was called:
component.setSize(100,200);
jPanel.add(component);
jPanel.revalidate();
jPanel.repaint();
panel.add(button);
panel.revalidate();
panel.repaint();
Java : Dynamically add swing components
for Example : count=3
//Java Swing: Add Component above method
public void dya_addcomp(int count)
{
//Dynamicaly Delete Image_icon
BufferedImage Drop_Tablefield = null;
try {
Drop_Tablefield = ImageIO.read(this.getClass().getResource("/images/drop.png"));
} catch (IOException ex) {
msg(" Error: drop and edit icon on Table, "+ex);
}
//count Items: 3 times for loop executed..
for(int i=0;i<count;i++)
{
//cnt++;
//lblcount.setText("Count : "+cnt);
JTextField txtcolnm=new JTextField("",20);
JComboBox cmbtype=new JComboBox();
JTextField txtcolsize=new JTextField("",20);
JButton Drop_Table_Field = new JButton(new ImageIcon(Drop_Tablefield));
cmbtype.addItem("INTEGER"); cmbtype.addItem("FLOAT");
cmbtype.addItem("STRING"); cmbtype.addItem("BOOLEAN");
colnamepanel.add(txtcolnm); colnamepanel.add(cmbtype);
colnamepanel.add(txtcolsize); colnamepanel.add(Drop_Table_Field);
colnamepanel.setAutoscrolls(true);
//refresh panel
colnamepanel.revalidate();
colnamepanel.repaint();
//set the layout on Jpanel
colnamepanel.setLayout(new FlowLayout(FlowLayout.LEFT,5,0));
}//end for loop
}//end method

Categories

Resources