I really cannot figure out what I'm doing wrong- The Option1 code just shows a white empty text field and Option 2 just says it's not initialized... I could really use some guidance. Thanks in advance
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Option1 extends JApplet implements ActionListener {
private int click = 0;
public Option1() {
JFrame base = new JFrame ("Button Click Counter");
base.getContentPane().setLayout(null);
base.setSize(500,500);
base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me!");
button.addActionListener(this);
JTextField count = new JTextField(click);
this.add(button);
this.add(count);
}
@Override
public void actionPerformed (ActionEvent e) {
click++; }
}
and the other one
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
public class Option2 extends JApplet implements MouseListener {
double x;
double y;
public void init() {
addMouseListener(this);
JFrame base = new JFrame("Mouse Coordinates");
base.getContentPane().setLayout(null);
base.setSize(500,500);
base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField answer = new JTextField(x + "," + y);
}
@Override
public void mouseClicked( MouseEvent e ) {
x = e.getX();
y = e.getY();
this.setBackground(new Color((int)(Math.random() * 0x1000000)));
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
also, if anyone could offer advice on how to a mouseclick to change the background to a random color (as attempted in Option2), that'd be great. Thanks!
JApplet
by default use BorderLayout
and you can add just one component in each section north, south, east, west and center. If you add another component in same section then previous component will be replaced by newly added one.
Use overloaded add()
method to add it in different section.
for example:
this.add(button, BorderLayout.SOUTH);
this.add(count); // added in CENTER by default
It's better to use JPanel
. Add components in it and finally add JPanel
in JApplet
.
Read more about How to Use BorderLayout
Never use null
layout. There is lots of Layout managers that is designed.
Please have a look at Swing Tutorial on How to Use Various Layout Managers