Create JLabel in actionPerformed in Java - java

Hi I have a JButton that I want to program so that when pressed, a new JLabel is displayed on screen. I have added the JLabel to the frame and it is visible. It shows outside of actionPerformed but not inside it.
The label is declared as lbl outside the method and then it is created in the actionPerformed method
public void actionPerformed(ActionEvent e) {
JLabel lbl = new JLabel("ONE");
}
Can anybody help me to make the label appear when the button is pressed? Thanks

This is the way you do it:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonname){
labelname.setVisible(true);
}
}
Also, don't forget to do
buttonname.addActionListener(this);
and in your method where you layout the form add this:
yourPanel.Add(labelname)
Hope this helps!
Arno

You created the JLabel, but you did not add it to any container. That is why it is not showing. What you wrote is good, all you need is to add the label to the container it is supposed to be on.
JLabel lbl = new JLabel("ONE");
yourPanel.Add(lbl);

You have also declared it inside the actionPerformed method - this declaration is perhaps hiding the earlier one (outside the method). Can you post more code? The following code works fine for me:
public class NewLabel
{
public static void main(String[] args)
{
final JFrame frame = new JFrame();
JButton button = new JButton("Add label");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JLabel lbl = new JLabel("ONE");
frame.add(lbl);
frame.setSize(100, 100);
// or you can't see the new button without resizing manually!
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
(In some cases you may also need to tell the container/frame to re-layout, by calling revalidate() on it...)

Related

How do I modify the text of a JTextfield from a different class? (Java)

I'm trying to make a calculator as practice (I'm pretty bad at Java), but now I face a problem that I can't fix. I have a frame with a CardLayout, and on one of those cards is a JTextfield. I made the textfield in my main class:
JTextField textfield = new JTextField();, and did some things with it:
textfield.setBounds(50, 130, 380, 60);
textfield.setEditable(false);
textfield.setFont(font);
Now, I want to modify the text on the textfield from a different class (which makes the calculator work): main.textfield.setText(main.textfield.getText() + "ans");, but that doesn't work. I am trying to modify the text in an ActionPerformed method.
Does anyone know what I am doing wrong?
I tried doing it via a method in my main class, and repainting and revalidating the frame and the panel, which both didn't work.
#DanielJunglas asked for more information so here we go :p. I'll all the code that could possibly have effect on my problem.
frame.setBounds(700, 250, 500, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setResizable(false);
contPanel.setLayout(cards); //set the cardlayout to the container panel
contPanel.setBounds(0, 0, 500, 700);
createBegPanel(); //creating the panels
createNorPanel();
createTriPanel();
//createEquPanel();
contPanel.add(beginPanel, "p1");
contPanel.add(normalCalcPanel, "p2");
contPanel.add(triCalcPanel, "p3");
//contPanel.add(equCalcPanel, "p4");
cards.show(contPanel, "p1");
frame.add(contPanel);
frame.setVisible(true);
public void createNorPanel() { //these are the things i do with the textfield
textfield.setBounds(50, 130, 380, 60);
textfield.setEditable(false);
textfield.setFont(font);
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
main.textfield.setText("test");
So any button is pressed, it should set the text of the textfield to 'text', but it doesnt. Is this enough info?
Thanks in advance!
I guess you never call actionPerformed.
If you have a button then you need to add an ActionListener to it that implements the method actionPerformed(ActionEvent e).
It looks like you have a class that implements an ActionListener (which is generally not a good solution). In that case you have to add this as ActionListener to the button.
JButton b = new JButton();
b.addActionListener(this);
A better solution would be to add a separate ActionListener to each button.
JButton b = new JButton();
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
main.textfield.setText("test");
}
});
ActionListener is a functional interface (it has only one method) wich means you could also use a Lambda expression.
b.addActionListener(e -> main.textfield.setText("test"));

Close windows without closing Application

Good afternoon!
I have this code:
private static class ClickListener implements ActionListener {
public ClickListener() {
}
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame();
JLabel label = new JLabel("Opção Indisponivel");
JPanel panel = new JPanel();
frame.add(label, BorderLayout.CENTER);
frame.setSize(300, 400);
JButton button = new JButton("Voltar");
button.addActionListener(new CloseWindowListener());
panel.add(button);
frame.add(panel, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
private static class CloseWindowListener implements ActionListener {
public CloseWindowListener() {
}
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
}
What I want to do is when i click on the button "voltar" (which is in another window, not on the "main" one as you can see) it closes the windows but not the app itselft. The setVisible line gives me an error about that it cannot be referenced by a static context which I understand because I need the reference of the frame. How do I solve this?
EDIT: Changed JFrame to JDialog but still no sucess. Both windows are shutdown.
Thanks in advance,
Diogo Santos
The setVisible line gives me an error about that it cannot be referenced by a static context which I understand because I need the reference of the frame. How do I solve this?
You can access the component that generated the event. Then you can find the window the component belongs to. This will give you generic code to hide any window:
//setVisible(false);
JButton button = (JButton)e.getSource();
Window window = SwingUtilities.windowForComponent(button);
window.setVisible(false);
You can also check out Closing an Application. The ExitAction can be added to your button. Now when you click the button it will be like clicking the "x" (close) button of the window. That is whatever default close operation your specify for the window will be invoked.

How to make a JButton do something

I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?
Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
See How to Write an Action Listener.
I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.
Hope this helps
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});

Java- How to add more textfields by clicking a button?

I have created a frame in Java which has some textfields and buttons in it. Assuming that user wants more textfields (for example to add more data), I want to put a button and when a user clicks the button, then a new textfield should appear. then user can fill data in it and again by clicking that button another textfield should appear.
How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?
Thank you !
It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameExample
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public JFrameExample()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add JTextField");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate(); // For JDK 1.7 or above.
//frame.getContentPane().revalidate(); // For JDK 1.6 or below.
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new JFrameExample().displayGUI();
}
});
}
}
Supposing that you have a main container called panel and a button variable button which is already added to panel, you can do:
// handle the button action event
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// create the new text field
JTextField newTextField = new JTextField();
// add it to the container
panel.add(newTextField);
panel.validate();
panel.repaint();
}
});
When adding the new text field, you may need to mention some layout related characteristics, depending on the layout manager you are using (for instance if you use GridBagLayout, you will need to specify the constraints).

hide/show label and button produce noise in jdialog in java?

i create a dialog box in java desktop application . But when i hide/show label and button by applying condition on checkbox .its produce graphical noise by showing some part of background application part(like red box on both label and buttons also checkbox layout causes problem). i write this condition on checkbox.
checkbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (checkbox.isSelected()) {
baisvalue.setVisible(true); //label
plusbais.setVisible(true); //button
minisbais.setVisible(true); //button
}
if (!checkbox.isSelected()) {
minisbais.setVisible(false); //label
plusbais.setVisible(false); //button
baisvalue.setVisible(false); //button
}
}
});
note:
i also call repaint(); & validate(); but same problem occurs.
I wasn't able to recreate your problem - I see no graphical noise. I've attached a sscce of what I tried - Can you reproduce your problem with this example? If so, can you provide us with more information about your java version/platform? If not, can you modify this example to recreate your problem (and edit your question with the code)?
import java.awt.event.*;
import javax.swing.*;
public class MainPanel extends Box{
JCheckBox checkbox = new JCheckBox("Select Me");
JLabel baisvalue = new JLabel("baisvalue");
JButton plusbais = new JButton("plusbais");
JButton minisbais = new JButton("minisbais");
public MainPanel(){
super(BoxLayout.Y_AXIS);
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (checkbox.isSelected()) {
baisvalue.setVisible(true); //label
plusbais.setVisible(true); //button
minisbais.setVisible(true); //button
}
if (!checkbox.isSelected()) {
minisbais.setVisible(false); //label
plusbais.setVisible(false); //button
baisvalue.setVisible(false); //button
}
}
};
checkbox.addActionListener(l);
add(checkbox);
add(baisvalue);
add(plusbais);
add(minisbais);
//Performs the action on initialization
l.actionPerformed(new ActionEvent(checkbox, ActionEvent.ACTION_PERFORMED, ""));
}
public static void main(String[] args){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPanel());
frame.pack();
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Try to use this.setOpaque(false); in constructor.

Categories

Resources