Can I add and draw a component through code in Swing (Java)? - java

I'm trying to add and draw buttons using merely my code. To be more specific, my goal is visualizing several buttons after another button has been pressed. This must be done programmatically because the number of buttons that have to be drawn depends on the user's input.
I've seen this piece of code in another thread and tried to implement it, but it didn't quite work:
// Adds a single button to a panel and paints it programmatically
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
JButton button = new JButton();
jPanel1.add(button);
jPanel1.revalidate();
jPanel1.repaint();
}
Any suggestions?
Thanks in advance.
Note: I'm using NetBeans 8.0.2.

Related

Loading Image in Java using JFrame

so i have a very basic java application, there is a panel and inside that is a button. When a user clicks the button, i want a picture to come up in another panel in the same form.
I searched up ways to load images from web/from my folder and this is the code i've come up with:-
private void buttonActionPerformed(java.awt.event.ActionEvent evt)
{
ImageIcon icon = new ImageIcon("URL-of-the-image");
panel2.setIcon(icon);
}
~~what panel 2 looks like~~
where am i going wrong?
it says that the method "setIcon()" is causing a problem but i don't know any other method to do this job. Please Guide!
If panel2 is a JPanel, it doesn't have a setIcon method.
Use a JLabel instead , it has such a method.

Switch between multiple JFrames

I'm relatively new to Java and I'm trying to make some kind of quiz. I created 3 JFrames, all in the same package. On my main frame, there are two buttons (one for the english version and the other one for the german version). I want to switch JFrames after pressing these buttons (so that I can, by pressing "English", see and interact with my english quiz frame). Looking it up didn't help me the slightest, because I'm not really experienced with it. Is it even possible to do it like this? If not, how could I do it?
The standard approach is to use the Card Layout, which allows you to use the same JFrame as you populate it with different things at different points in your application. So initially, your JFrame would show the loading screen, then the user presses a button and you load a new set of components without discarding the current JFrame you have. In some cases, you might also need to make some size adjustments.
It is difficult to say without seeing any code, but usually, what is done is that you do something like so:
new Frame(args);
this.dispose();
The code above assumes that the constructor of Frame takes care of launching and making the components visible. The this.dispose(); disposes of the current JFrame (assuming your class extends JFrame).
You have two buttons in your frame 1 right? So first, double click the button which says "English". Lets say the variable name for that button is jButton1. Inside that button type this.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
EnglishFrame eng = new EnglishFrame();
eng.setVisible(true);
}
Then double click the other button which says "German" (jButton2). Inside that type this.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
GermanFrame german = new GermanFrame();
german.setVisible(true);
}
this.dispose() - This will cause the jFrame window to close
Then you create an object of the other two forms. (In your case the form for English and Germany)
.setVisible(true) - This will show you the form.
Create a single Jframe window. After that create JPanels with all the compenents such as buttons, textfields and labels you want. Make sure the panel is the same size as your Jframe. Panel's work about the same as JFrame's, code wise.
This code will stitch everything together for you:
panel.setSize(Jframe.getSize()) //That wont
panel.add(button); //Just remember you need to add more code to position the buttons correctly.
//If you using netbeans builder:
//You just have to use this one line in the constructor/intialiser method
frame.add(panel); //This will add the panel to the Jframe/Window
//No need to add extra code for positioning.
If you want to swap between the panels. In the button press method, use this
frame.setContentPane(panel); //panel = panel you want to change too.
frame.repaint(); //Ensures that the frame swaps to the next panel and doesn't get stuck.
frame.revalidate(); //Ensures that the frame swaps to the next panel and doesn't get stuck.
When you first start the java application you have to set the content pane or else it will appear as a blank window.
frame.setContentPane(panel); //Starting Panel
frame.setVisible(true); //Make the frame visible
Sorry if the explanation is bad, I don't have enough time to explain it fully.

jFrame multiple event listeners on one button

I'm quite new to the whole GUI scene of Java but I decided to give it a try. I have a project in NetBeans and I am using their little auto generator thing and was wondering if you can have multiple even listeners on one button? Right now I have it so when you click it changes the button to a certain color and I was wondering if you can make it so when you click it again, it changes the color back to the default color?
This is what my button looks like right now
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jButton1.setBackground(Color.black);
jButton1.setForeground(Color.yellow);
}
I have an idea of how it would look but I can't really get it to work. I know you have to set it back to the regular color like this.
jButton1.setBackground(null);
Any help is appreciated!
You can add a check in your event listener to see if the color is already changed:
if(jButton1.getBackground().equals(Color.black)) {
... // revert color
} else {
jButton1.setBackground(Color.black);
jButton1.setForeground(Color.yellow);
}

Adding JButton dynamically to the JPanel not working with Netbeans

I created a JFrame Class with Netbeans 7.3 and added two panels from the palette.
I have added a button in the first panel on the click of which I want to add a new button in the second panel(topoPane).
Below is the button click event that I have written for the same. But, the button is not getting added to the panel even when the event is getting called.
Please tell me what's wrong in it.
private void jButton1MouseClicked(java.awt.event.MouseEvent evt)
{
// TODO add your handling code here:
System.out.println("Creating the Button");
JButton but = new JButton();
but.setBackground(Color.red);
but.setText("New Button");
but.setBounds(500, 500, 500, 500);
topoPane.add(but);
topoPane.revalidate();
}
From your use of setBounds, it is obvious that you are using a null layout. Because of this you need to call repaint() as containers with no layout do not automatically repaint added components on revalidate.
Apart from the fact that calling repaint is good practice, layout managers can remove the need to make this call along with manage the sizing and positioning of components. This makes it a good reason to use a layout manager.

Keyboard input stops working in Swing application (a calculator) after clicking on a JButton

I'm making a calculator using Swing. So far I have created a GUI that consists of a JFrame with BorderLayout, and in its center I put a JPanel that has a JLabel (representing the screen of the calculator) and some JButtons (representing the keys).
I want the calculator to be able to receive input directly from the keyboard, so I included the method addKeyListener in a class that extends JFrame and I put as an argument a reference to an object of a class that implements KeyListener.
When I run the application it accepts keyboard input until I click on one of the JButtons. After that using the keyboard doesn't work anymore.
I suspect the problem is about focus, but it is not a problem that I could fix by clicking anywhere on the application. I added the following code:
setFocusable(true);
to the JFrame but it did not help. I have read that using Key Bindings maybe a better option than using a KeyListener, but I am not really sure about this approach.
Swing components are lightweight and use KeyBindings, where KeyListeners are for AWT components which are heavyweight. and known to have focus issues when mixed with Swing components. Thus I suggest changing to KeyBindings (but I see you have heard of them). You would use them something like:
final JButton b=..;
//method to add keybindings to a JComponent ie JButton,JPanel,JTextField etc
private void addKeyBindings(JComponent jc) {
//not the getInputMap(..) call it could also be JComponent.WHEN_FOCUSED etc
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "D pressed");
jc.getActionMap().put("D pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
//do something when d is pressed
b.doClick();
}
});
}
For general knowledge a very hacky solution would be calling requestFocusInWindow() on the component to which the listeners are attached whenever focus is lost (like after button click etc)
It's another hacky approach, but you could alter the properties of the JButton when you create it so that it can't take the focus in the first place i.e:
myJbutton.setFocusable(false);
This worked for me.

Categories

Resources