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);
}
}
Related
I want to remove JButton when user click JButton.
I know that I should use remove method, but it did not work.
How can I do this?
Here is my code:
class Game implements ActionListener {
JFrame gameFrame;
JButton tmpButton;
JLabel tmpLabel1, tmpLabel2, tmpLabel3, tmpLabel4;
public void actionPerformed(ActionEvent e) {
gameFrame.remove(tmpLabel1);
gameFrame.getContentPane().validate();
return;
}
Game(String title) {
gameFrame = new JFrame(title);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setBounds(100, 100, 300, 500);
gameFrame.setResizable(false);
gameFrame.getContentPane().setLayout(null);
tmpLabel4 = new JLabel(new ImageIcon("./images/bomber.jpg"));
tmpLabel4.setSize(200, 200);
tmpLabel4.setLocation(50, 100);
tmpButton = new JButton("Play");
tmpButton.setSize(100, 50);
tmpButton.setLocation(100, 350);
tmpButton.addActionListener(this);
gameFrame.getContentPane().add(tmpLabel4);
gameFrame.getContentPane().add(tmpButton);
gameFrame.setVisible(true);
}
}
If hiding the button instead of removing works for your code then you can use:
public void actionPerformed(ActionEvent event){
tmpButton.setVisible(false);
}
for the button.But the button is just hidden not removed.
The simplest solution might be to...
Attach an ActionListener to the button, see How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
When the ActionListener is clicked, extract the source of the event, JButton buttonThatWasClicked = (JButton)actionEvent.getSource()
Remove it from it's parent...
For example...
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revaidate();
parent.repaint();
As some ideas...
First of all in your actionPerformed method you need to check that the button is clicked or not. And if the button is clicked, remove it. Here's how :
if(e.getSource() == tmpButton){
gameFrame.getContentPane().remove(tmpButton);
}
add this to your actionPerformed Method
don't add your button to jframe but add each component you want!
public void actionPerformed(ActionEvent event)
{
//gameFrame.getContentPane().add(tmpButton); -=> "Commented Area"
gameFrame.getContentPane().validate();
}
or hide your button like this
public void actionPerformed(ActionEvent event)
{
tmpButton.setVisible(false);
}
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);
Hi guys I have a question about Applets. I have an game applet that I would like to embed in a webpage. However I would like to add a "Start Screen" to the applet which comes up first and has a few parameter buttons and a start button. The "Game Screen" should load when the start button is pressed. What would be the best way to go about implementing this? Here is a simple 1-screen Applet as an example.
public class AppletExample extends Applet implements ActionListener{
Button okButton;
Button cancelButton;
TextField _textField;
public void init(){
okButton = new Button("Press");
cancelButton = new Button("Cancel");
_textField = new TextField("Ready", 10);
okButton.addActionListener(this);
cancelButton.addActionListener(this);
add(okButton);
add(_textField);
add(cancelButton);
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == okButton){
_textField.setText("Running...");
}
else { _textField.setText("Cancelled");
}
}
}
You could use CardLayout to manage navigation between panels.
Have a look also at using the lightweight Swing JApplet rather the old AWT applet. The start panel could be a JPanel containing the necessary components. Use next, previous or show as appropriate to navigate between game panels.
public void init() {
setLayout(new CardLayout());
JPanel startPanel = new JPanel();
okButton = new JButton("Press");
startPanel.add(okButton);
...
add(startPanel, "Card 1");
...
}
anyone know or have an idea as to why my button disappears after i resize the applet?
this is my code:
import java.awt.event.*;
import javax.swing.*;
import acm.program.*;
public class button extends ConsoleProgram {
public void init(){
hiButton = new JButton("hi");
add(hiButton, SOUTH);
addActionListeners();
}
public void actionPerformed(ActionEvent e){
if(hiButton == e.getSource()){
println("hello") ;
}
}
private JButton hiButton;
}
I'm not sure if it is a good Idea to redefine the init-method. When I have a look at http://jtf.acm.org/javadoc/student/acm/program/ConsoleProgram.html I would expect that you have implement only the run-method. Overriding init without calling super.init() Looks strange to me.
Maybe I would be better to derive from JApplet directly for your first steps in Applet programming.
Assuming that
your ConsoleProgram extends (directly or indirectly) JApplet
You declared SOUTH as a static final variable that has the value BorderLayout.SOUTH (otherwise your code doesn't compile)
The code should work, no need to repaint (unless you would like to do some application-specific optimization). I just copied and pasted your code (by expliciting the two assumptions above), I see the applet and the button doesn't disappear on resize.
Anyway there are few "not good" things in the code:
First of all, a naming convention issue: the class name should be "Button" with the first letter capitalized (on top of that, it's a poor name for an Applet)
Second, action listeners should be attached before adding the component;
Third, as Oracle doc suggests here, the code that builds the GUI should be a job that runs on the event dispatcher thread. You can do that by wrapping the build gui code in a Runnable using a SwingUtilities.invokeAndWait(Runnable()
Have you tried calling super.init() at the start of your init() method?
Try explicitly using a layout for your Console and then use relative positioning.
To re-size a button in Applet:
public class Button extends JApplet implements ActionListener {
private JButton button;
public void init() {
Container container = getContentPane();
container.setLayout(null);
container.setBackground(Color.white);
button = new JButton("Press Me");
button.setSize(getWidth()/2,20);
button.setLocation(getWidth()/2-button.getSize().width/2, getHeight()/2-button.getSize().height/2);
container.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
int width = (button.getSize().width == getWidth()/2) ? getWidth()/4 : getWidth()/2;
int height = button.getSize().height;
button.setSize(width,height);
button.setLocation(getWidth()/2-width/2, getHeight()/2-height/2);
}
}
To re-size a button in JFrame:
public class Button extends JFrame implements ActionListener {
private JButton button;
public Button(String title) {
Container container = getContentPane();
container.setLayout(null);
container.setBackground(Color.white);
setTitle(title);
setSize(400,400);
button = new JButton("Press Me");
button.setSize(getWidth()/2,20);
button.setLocation(getWidth()/2-button.getSize().width/2,
getHeight()/2-button.getSize().height/2);
container.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
int width = (button.getSize().width == getWidth()/2) ? getWidth()/4 : getWidth()/2;
int height = button.getSize().height;
button.setSize(width,height);
button.setLocation(getWidth()/2-width/2, getHeight()/2-height/2);
}
public static void main(String[] args) {
Button button = new Button("Test");
button.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setVisible(true);
}
}
Have you declared the repaint method...???
You are using swing. It needs to have declared a repaint.
Please define a custom repaint mwthod
I am making an applet and as part of my applet, I want this to happen: When the user presses "OK", the old components (some radio buttons) are removed, and a new JPanel is added, with a bunch of textfields.
However, I cannot figure out how to add a new component to the applet after it has started. I made the problem simpler by ignoring the removal part (Which I know how to do) and just adding a simple JLabel instead, but even that won't add!
Here is my code so far:
// imports omitted
public class Class extends Applet implements ActionListener
{
Button okButton;
CheckboxGroup radioGroup;
Checkbox radio1;
Checkbox radio2;
Checkbox radio3;
JLabel j;
public void init()
{
setLayout(new FlowLayout());
okButton = new Button("OK");
j = new JLabel("hello");
radioGroup = new CheckboxGroup();
radio1 = new Checkbox("Red", radioGroup,false);
radio2 = new Checkbox("Blue", radioGroup,true);
radio3 = new Checkbox("Green", radioGroup,false);
add(okButton);
add(radio1);
add(radio2);
add(radio3);
okButton.addActionListener(this);
}
public void repaint(Graphics g)
{
if (radio1.getState()) add(j);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == okButton) repaint();
}
}
What am I doing wrong?
You shouldn't override the repaint method, and certainly not add a component in this method. Just remove the radio buttons from the applet (using its remove method) and add the label in the applet in your actionPerformed method, the same way you add them in the init method.
You might have to call validate after.
Add components and then call validate() of your container. In this case yourApplet.validate(). This will trigger repainting and rearranging of all elements.
you could do something like
JFrame fr= new JFrame(); // global variables
JPanel panelToBeAdded = new JPanel();
JPanel initialPanel = new JPanel();
JTextField fieldToBeAdded = new JTextField();
panelToBeAdded.setPreferredSize( new Dimension(400,400));
initialPanel.setPreferredSize( new Dimension(400,400));
initialPanel.setVisible(true);
fr.add(initialPanel);
fr.setVisible(true);
fr.pack();
public void actionPerformed(ActionEvent ae) {
initialPanel.setVisible(false);
//radiobuttons.setVisible(false);---> hide the radio buttons
panelToBeAddedd.add(fieldToBeAddedd);
panelToBeAddedd.setVisible(true);
fr.add(panelToBeAddedd);
}
public void repaint( Graphics g ) {
// do something
}
What am I doing wrong?
Your repaint(Graphics) method is not the same method you are calling in your actionPerformed method.
Also, repaint is a pretty bad name for a method which is adding a new component.
public void swapComponents()
{
if (radio1.getState()) {
remove(radio1);
remove(radio2);
remove(radio3);
add(j);
validate();
}
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == okButton) {
swapComponents();
}
}
When the user presses "OK", the old components (some radio buttons) are removed, and a new JPanel is added, with a bunch of textfields.
Use a CardLayout, as shown here. It is perfect for situations like this.