Java method being called, but elements not displaying in GUI - java

I have the following Java method, which I am trying to use to add some buttons to a GUI:
private void addButtons(){
JButton addBtn = new JButton("Add");
JButton saveBtn = new JButton("Save");
addBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
/*Code to be added here */
}
});
addBtn.setBounds(1150, 135, 30, 15);
saveBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
/*Code to be added here */
}
});
saveBtn.setBounds(1190, 135, 30, 15);
System.out.println("'addButtons()' method is being called");
}
I am calling this method from a private void initialize() method in the same class. I know that initialize() is being called because all of the other method calls that it performs are happening, and displaying in the GUI.
However, for some reason, the buttons that I am trying to create and add to my GUI with this method are not being displayed...
Can anyone point out to me why this is, and what I'm doing wrong?
Edit
Apologies- I'm calling the method in a private void initialize() method in the same class:
private void initialize(){
...
(other code that is successfully adding stuff to the GUI)
...
addButtons();
}
I am seeing the System.out.println() message from the end of the addButtons() method in the console when I click the button that calls the initialize() method... and all of the other code from the `initialize()' method is being called (for example, it's opening a new window, and adding some text, textboxes and tables to the window)...
Edit 26/06/2014 # 09:15
The class where I have written this code extends JPanel:
public class JConfigurationPane extends JPanel implements UndoableEditListener, ChangeListener
I am now no longer using the addButtons() method that I had previously mentioned, and am trying to use my initialize() method to add the buttons to the JPanel:
public void initialize(){
// Code that initialises other elements in the GUI, such as Jlabels, layout, etc
JButton addBtn = new JButton("Add");
JButton saveBtn = new JButton("Save");
this.add(addBtn);
this.add(saveBtn);
}
But the buttons still don't appear when I run the application, even though all of the other graphical elements in the initialize() method do... Any ideas why this is? I've added some debug before and after where I create the buttons, and where I add them to the GUI- the debug is displayed in the console, so the code to create and add the buttons must be called...

Where are you adding these buttons to the form?
You are creating buttons in the method yes, and attaching listeners to these but the buttons themselves aren't being added to the form which is why you cant see them.
e.g you should be doing something like:
yourForm.add(addBtn);
yourForm.add(saveBtn);
or add these to a JPanel or something - finally making sure you add this JPanel

I managed to solve this by moving the code from my addButtons() method to my initialize() method, and setting the bounds of each button immediately after creating it:
JButton addBtn = new JButton("Add");
addBtn.setBounds(1000, 135, 75, 25);

Related

Positioning Applet Buttons

Hey my course requires me to do some applet stuff that I'm unfamiliar with and I'm trying to position my button to a certain position on the screen. I can get the size of the button to whatever I like but not the x and y position.
public void init() {
button1 = new Button ("HIT TARGET");
button1.setPreferredSize(new Dimension(100, 100));
add(button1);
button1.setLocation(300, 300);
button1.addActionListener(this);
}
I've tried to search for my course document and google about this but I haven't found anything.
You can use there setBounds() method and also set the setLayout(null) method as null.
You can also refer my code to understand how to use:
public class Ass extends Applet
{
String msb="";
Button btn;
public void init()
{
btn=new Button("BUTTON");
setLayout(null);
btn.setBounds(30,60,100,20);
add(btn);
}
}

Event handler in JDialog not working if placed after setVisible(true)

This is an interesting problem that didn't show up when I built the last JDialog, even though that one was way more complex than this. Anyways here is the code that causes the problem.
public class Test extends JDialog{
private final JButton cancel, ok;
private final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 5));
public Test(JFrame parent) {
//Initialize the JDialog
super(parent, "Select Chapters");
setLayout(new BorderLayout());
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(JDialog.ModalityType.APPLICATION_MODAL);
setSize(300, 300);
setLocationRelativeTo(null);
cancel = new JButton("Cancel");
ok = new JButton("OK");
buttonPanel.add(cancel);
buttonPanel.add(ok);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
dispose();
}
});
}}
And the main method
Test test = new Test(new JFrame());
I put the event listener in the constructor for testing but the actual implementation is supposed to happen in another class. Which is why this is a problem. If I put the action listener before setVisible(true), then everything works as it should. But I can't do that since the event handler is to be implemented in another class. What is causing this problem and how do I resolve it?
Event handler in JDialog not working if placed after setVisible(true)
Correct, because the JDialog is modal, so the statement after the setVisible() is not executed until the dialog is closed.
There is no reason you can't add the ActionListener to the button before the dialog is made visible. It doesn't matter that the code is in a separate class. You just create an instance of that class in the constructor of the class where you create the button.
I put setVisible() in the other class after I implemented the listeners
You are still doing something wrong. The setVisible() should be in your main class where you set the dialog properties and create all the components and add the component to the dialog.
I'm not sure why you are doing. Your code can be something like:
cancel = new JButton("Cancel");
cancel.addActionListener( new SomeActionListenerClass() );
...
setVisible( true );
You need to place setVisible(true) at the end of your constructor because the dialog is modal and in that case setVisible(true) will not return until you call setVisible(false).
Quoting Java doc:https://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.html#setVisible(boolean)
Notes for modal dialogs.
setVisible(true): If the dialog is not already visible, this call will
not return until the dialog is hidden by calling setVisible(false) or
dispose.
setVisible(false): Hides the dialog and then returns on
setVisible(true) if it is currently blocked.
It is OK to call this
method from the event dispatching thread because the toolkit ensures
that other events are not blocked while this method is blocked.

Java NullPointerException when adding listener to a JButton

I am displaying a table in a Java GUI. The user can currently add rows to the table by clicking an 'Add Row' button, and edit the values of the cells in the table. I am now trying to add a method to remove the selected row from the table by clicking a 'Remove Row' button.
I have declared the button as a global variable:
public JButton removeBtn = null;
Then I am adding the listener to the button in my addListeners() method:
private void addListeners(){
....
removeBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int selectedRow = jEntityFilterTable.getSelectedRow();
DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
model.removeRow(selectedRow);
}
});
}
However, when I now try to run my code, I get a NullPointerException that's stopping it from running... The exception says:
Exception in thread "main" java.lang.NullPointerException
The lines it's complaining about are:
removeBtn.addActionListener(new ActionListener(){
(which I guess means it could be anything inside the clock of code above, where I'm adding the ActionListener),
addListeners();
(where I'm calling the addListeners() method), and
JConfigurationPane panel = new JConfigurationPane();
(where I'm initialising the JConfigurationPane in my main() method. Can anyone spot what I'm doing wrong here?
You have not initialised the removeBtn variable. Replace
public JButton removeBtn = null;
with
public JButton removeBtn = new JButton("Remove");
In your current code, on the line
removeBtn.addActionListener(new ActionListener(){
removeBtn does not refer to an object so there is nothing to invoke the addActionListener method on. As a result, you receive a NullPointerException.
try to initialize your button like this:
removeBtn = new JButton("Remove");

How to place an image on the screen from an event?

I want to add an image on the screen when an event occurs. In my case, this would be from a button being clicked. I attempted to solve this myself, but the image isn't appearing. I don't know what is wrong.
My code:
JButton button2 = new JButton("+");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("button #2 working");
label2 = new JLabel(new ImageIcon(this.getClass().getResource("50.png")));
label2.setLocation(10, 60);
label2.setSize(300, 532);
add(label2);
//? Not working
}
});
button2.setSize(50, 40);
button2.setFont(new Font("Arial", 1, 20));
button2.setLocation(110, 592);
button2.setBackground(Color.ORANGE);
content.add(button2);
I actually have done something similar to what you are trying to achieve. However, I achieved this by using a different method instead. You could for example create a class MyPanel which extends JPanel and override the paintComponent() method. In the paintComponent() method you can call g.drawImage(yourImage, 0, 0,null); to add the image to your panel. Then it is a matter of creating an instance of MyPanel and adding it wherever you want on the GUI. Also, do not forget to call repaint() after you have clicked the button or you will not see the change.

Component passed to constructor doesn't display

I've created a class that creates a panel, and in the constructor I'm passing a button with an action listener attached.
This is the code for the button:
JButton back = new JButton("Back");
back.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
menus.show(contentPane, "Main");
}
});
It's then passed to a constructor like so:
lightsPane = new lightsPane(back).contents;
tasksPane = new Tasks(tasksBack).contents;
tvPane = new TV(tvBack).contents;
Inside the classes the button is added to a JPanel and that JPanel is then added to contents. Like so:
public class lightsPane{
JPanel contents;
lightsPane(JButton back){
contents = new JPanel(new BorderLayout);
//add back button to lower right of panel
JPanel backPane = new JPanel();
backPane.setLayout(new BorderLayout());
backPane.add(back, BorderLayout.CENTER);
contents.add(backPane, BorderLayout.SOUTH);
}
}
I know the constructor is working right as when I create a button inside it to add to contents it displays fine. What's going on here? Can I pass this button to the constructor or not? If I can why isn't this displaying?
yes, you can pass a button to a constructor as you are passing a reference which you used in another class it is perfectly fine.
There is nothing wrong with passing the JButton through the constructor if it is used properly. The class either is not using it at all or is using it but in the wonge way.

Categories