Generating JLabels on demand - java

I would like to be able to generate a map, of sorts, which places small JLabels at coordinate locations on a panel. The problem is that I need them to be randomly generated, so I don't know in advance how many I will have. Is there a way to do that?
I hope this isn't breaking any Java coding taboos - I'm self-taught.
*Edit:
I know I was vague - my program is huge and cumbersome and I have developed my own conventions (which I'm sure would raise the hackles of real java coders :-P) I should have specified that I have a class Location, and I can easily generate random locations. The trouble I have is in creating a new jLabel for each of those locations. Here's what I have:
//Method called after a new Location has been created, to add it to the map
public void addLocation(Location newLocation)
{
int xx = newLocation.getXloc();
int yy = newLocation.getYloc();
for (int i=0;i<1;i++)
{
JLabel tempLabel = new JLabel(); //tempLabel instantiated elsewhere (is that a problem?)
tempLabel.setBackground(Color.BLACK);
tempLabel.setBounds(xx,yy,3,3);
Map.add(tempLabel); //Map is a JPanel with null layout manager
tempLabel.setVisible(true);
}
}
The problem is that it doesn't seem to do anything. No black dots appear on the map. Maybe now it's as simple as incorrect implementation of adding a label to a panel?

but do you happen to know if it's possible to add a mouselistener to each of these jlabels as they're created?
Sure its possible. You don't even need to create a new listener every time. You can create one listener that is used by all labels. Then inside the listener code you use:
JLabel label = (JLabel)event.getSource();
and you have access to the label that generated the MouseEvent.

Here is some code that might help you in some way, your question was a little vague on the details but i think this is what you are looking for.
public void generate(JPanel panel)
{
int panelWidth = 500;
int panelHeight = 500;
JLabel label;
Random random = new Random(Calendar.getInstance().getTimeInMillies());
int numberOfLabels = random.nextInt(100);
for(int x=0;x<numberOfLabels;x++)
{
int locX = random.nextInt(panelWidth);
int locY = random.nextInt(panelHeight);
label = new JLabel("Hello World!!");
label.setLocation(locX,locY);
label.setVisible(true);
panel.add(label);
}
}
If this is not the answer you are looking for or you need more help, let me know ill be glad to help. Hope this helped!!
Update: This is the way you would do it with a MouseListener:
public void generate(JPanel panel)
{
int panelWidth = 500;
int panelHeight = 500;
JLabel label;
Random random = new Random(Calendar.getInstance().getTimeInMillies());
int numberOfLabels = random.nextInt(100);
for(int x=0;x<numberOfLabels;x++)
{
int locX = random.nextInt(panelWidth);
int locY = random.nextInt(panelHeight);
label = new JLabel("Hello World!!");
label.setName("World Label");
// If some of your labels have the same Text then you should set a different
// name to each one so that you can tell the difference between them
// when you handle the mouse events.
label.addMouseListener(new PlayerListener());
// PlayerListener would be the class that implements MouseListener
label.setLocation(locX,locY);
label.setVisible(true);
panel.add(label);
}
}
This would be your MouseListener:
public void mousePressed(MouseEvent e)
{
JLabel label = (JLabel)e.getSource();
if(label.getName().equalsIgnoreCase("World Label"))
{
System.out.println("Hello World!!");
}
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
This MouseListener should only be added to JLabels because of the type cast. Hopefully this helped!

Related

How to create interactive panels with changing textures and colors in java?

I'm new here but I did some research before posting. My goal is to create a simple tower defense game using a couple of interesting ideas and moreover to train my development skills using javax.swing and java.awt. As far as I know, developers are mostly lazy guys and they do everything to make their life more simple.
There is map with a grid and for map loading my game uses a boolean matrix and a loading method to locate terrain on panels. I thought it will be quite simple solution. Because the matrix is 12 x 12, I would like to create it with some other application rather than entering a line of 144 numbers.
Here comes an idea to first create a map editor application and later do maps for levels in it. When I have such a tool I could make that map visually and then save its boolean matrix to a file, which later can be read by loading method and recreated in game. Next step is to make graphics and also panels that would react properly on user's actions. On the left there is a panel with buttons - after user clicks one of them, the field currentColor changes.
This field is used by method that implements actionListener and makes color change of the panel that is declared in its constructor. I wanted to change color of certain panel when its clicked. I use colors because its easier for now to make it working, later I want to replace color with a texture - obviously, I know I have to use a paintComponent method, but I assume that will work for it too, right? Also would be nice if the panel border changes color when I move my cursor over it and changes it back to normal when mouse is somewhere else.
The point here is that I'm having some trouble to make panels interactive. First problem is that panels are created in for loop and that makes it difficult to refer to a certain panel while mouse is over it. Another one comes with that I would like to change appearance of that panel after I click on it.
As far as I know, MouseListeners should do the work, but how to actually write it to have an effect on screen? I found some post about that, but for me it doesn't work. Here's the link: highlighting panels in java
My code:
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Editor extends JFrame
{
private JButton towers = new JButton(new ImageIcon("pu.gif"));
private JButton road = new JButton(new ImageIcon("pu.gif"));
private JButton start = new JButton(new ImageIcon("pu.gif"));
private JButton finish = new JButton(new ImageIcon("pu.gif"));
private String mapTitle = "testmap";
private Color currentColor;
private int width = Toolkit.getDefaultToolkit().getScreenSize().width;
private int height = Toolkit.getDefaultToolkit().getScreenSize().height;
private String currentMapType = "Standard";
private static final int currentHeight = 12;
private static final int currentWidth = 12;
private JPanel[][] currentMapPanel;
private int[][] currentMapField;
//Toolbar - a panel with buttons
private JPanel panel = new JPanel(new GridLayout(10,3));
//Container for map - a panel with map
private Dimension containerSize = new Dimension(height, height);
static JPanel container = new JPanel(new GridLayout(currentHeight, currentWidth), true);
//Separator
private JSplitPane separator = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel, container);
public Editor()
{
initComponents();
}
public void initComponents()
{
this.setTitle(mapTitle + ".map" + " - " + "Game Map Editor");
this.setSize(800, 600);
int frameWidth = this.getSize().width;
int frameHeight = this.getSize().height;
this.setLocation((width - frameWidth) / 2, (height - frameHeight) / 2);
this.setIconImage(Toolkit.getDefaultToolkit().getImage("pu.gif"));
towers.addActionListener(e -> {
currentColor = Color.CYAN;
System.out.println(currentColor);
});
road.addActionListener(e -> {
currentColor = Color.GRAY;
System.out.println(currentColor);
});
start.addActionListener(e -> {
currentColor = Color.LIGHT_GRAY;
System.out.println(currentColor);
});
finish.addActionListener(e -> {
currentColor = Color.BLACK;
System.out.println(currentColor);
});
new Map(currentMapType, currentWidth, currentHeight, false);
panel.add(towers);
panel.add(road);
panel.add(start);
panel.add(finish);
this.getContentPane().add(separator);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* Class that allows to load the graphic map and to view it in JFrame
*/
public class Map
{
public Map(String mapType, int rows, int columns, boolean load)
{
if (!load)
{
currentMapPanel = mapPanel(rows, columns);
currentMapField = new MapGenerator().mapFieldEmpty(rows, columns);
mapLoader(currentMapField, currentMapPanel);
}
else
{
currentMapPanel = mapPanel(rows, columns);
currentMapField = new MapGenerator().mapFieldGenerator(rows, columns);
mapLoader(currentMapField, currentMapPanel);
}
}
private JPanel[][] mapPanel(int rows, int columns)
{
JPanel[][] mapPanel = new JPanel[rows][columns];
for (int i = 0; i < rows - 1; i++)
{
for (int j = 0; j < columns - 1; j++)
{
mapPanel[i][j] = new JPanel(true);
mapPanel[i][j].setPreferredSize(new Dimension(height/12, height/12));
mapPanel[i][j].setBorder(new LineBorder(Color.BLACK));
mapPanel[i][j].addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
JPanel parent = (JPanel) e.getSource();
new colorListener(parent, Color.LIGHT_GRAY);
parent.revalidate();
}
#Override
public void mouseExited(MouseEvent e)
{
super.mouseExited(e);
JPanel parent = (JPanel) e.getSource();
new colorListener(parent, Color.GREEN);
parent.revalidate();
}
#Override
public void mouseClicked(MouseEvent e)
{
super.mouseClicked(e);
JPanel parent = (JPanel) e.getSource();
new colorListener(parent, currentColor);
parent.revalidate();
}
});
}
}
return mapPanel;
}
private void mapLoader(int[][] mapField, JPanel[][] mapPanel)
{
for (int i = 0; i < mapField.length - 1; i++)
{
for (int j = 0; j < mapField.length - 1; j++)
{
if (mapField[i][j] == 0)
{
mapPanel[i][j].setBackground(Color.GREEN);
container.add(mapPanel[i][j]);
}
else if (mapField[i][j] == 1)
{
mapPanel[i][j].setBackground(Color.GRAY);
container.add(mapPanel[i][j]);
}
else if (mapField[i][j] == 2)
{
mapPanel[i][j].setBackground(Color.LIGHT_GRAY);
container.add(mapPanel[i][j]);
}
else if (mapField[i][j] == 3)
{
mapPanel[i][j].setBackground(Color.BLACK);
container.add(mapPanel[i][j]);
}
else
{
System.out.println("An error occurred...");
}
}
}
}
private JPanel mapContainer(int rows, int columns)
{
container = new JPanel();
container.setLayout(createLayout(rows, columns));
container.setPreferredSize(containerSize);
container.setBounds(height/4, height/4, containerSize.width, containerSize.height);
return container;
}
private GridLayout createLayout(int rows, int columns){
GridLayout layout = new GridLayout(rows, columns);
return layout;
}
}
private class colorListener implements ActionListener
{
public colorListener(JPanel p, Color c)
{
this.panel = p;
this.color = c;
}
#Override
public void actionPerformed(ActionEvent e) {
panel.setBackground(color);
}
JPanel panel;
Color color;
}
public static void main(String[] args) {
new Editor().setVisible(true);
}
}
The question is broad and the answer complicated.
Essentially, you want to do some research into concepts such as "separation of responsibilities" and "decoupling code".
The idea is that you break down you functionality requirements so that your objects are doing a single, specialised job. You also "decouple" the code so that changing the implementation of one part won't adversely affect other parts of the program. This is commonly achieved through the use of interfaces.
You will also want to investigate the concept of "model-view-controller", where by the "data" or "state" is modelled in one or more classes, but is wholly independent of the UI. The UI is then free to "render" the model in what ever way it feels is appropriate.
In this way, the "view" (interacting with the controller) can change the state (or react to the change in state) of the model, making it easier to mange (no seriously, it does)
Code Review ...
This...
static JPanel container = new JPanel(new GridLayout(currentHeight, currentWidth), true);
is dangerous and a bad idea. It voids the concept of encapsulation and allows any one to create new instance of container at any time, without notification, which will disconnect it from what the program was previously using. In fact, you actually do this.
static is not your friend. Used correctly, it's useful, but used in this way, it's just a bad idea and should be avoid.
You should instead favour "dependency injection", where the "elements" that any one object relies on are passed to it.
I would avoid things like...
this.setSize(800, 600);
int frameWidth = this.getSize().width;
int frameHeight = this.getSize().height;
this.setLocation((width - frameWidth) / 2, (height - frameHeight) / 2);
Windows are complicated components, which also contain window decorations which wrap about the content. This means that the available space to the content is window size - window decorations. Instead. You should rely on the layout manager API to provide appropriate sizing hints and pack the frame.
On most modern OSs you have "other" system elements, which, again, reduces the amount of available space on the screen (docks, task bars, other funky stuff). Instead, you can use setLocationRelativeTo(null) to centre the window more reliably on the screen.
Instead of setIconImage, you should be using Window#setIconImages(List), which allows you to pass a number of images which can be used by the API to represent the application in different places that require different resolution images.
Not sure what ...
new Map(currentMapType, currentWidth, currentHeight, false);
but it's not really helping.
If you find yourself just creating an instance of class without actually maintaining a reference to it, then it's probably a good sign of a bad design.
Your Map class raises a bunch of questions which aren't easily answered. It kind of makes me worried that the Map class is modifying the state of the parent class and screams "dependency injection" instead.
This...
mapPanel[i][j].setPreferredSize(new Dimension(height / 12, height / 12));
is best avoided. You should prefer overriding getPreferredSize and it should simply return a "desired" size, which could then be used by things like GridLayout to layout the component more effectively.
This then leads into the "separation of responsibility". This section suggestions you should have a "tile" class, which would be self managed and responsible for a single element from the model.
There are a number of things wrong with your mouse event handling...
#Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
JPanel parent = (JPanel) e.getSource();
new colorListener(parent, Color.LIGHT_GRAY);
parent.revalidate();
}
You shouldn't be calling super.mouseXxx(e) on of the jobs of those methods is to call the delegate MouseListeners, so, mess right there.
You can more easily use e.getComponent() to get a reference to the component which generated the event, but if panel was a self contained unit of work (ie Tile) and the MouseListener an anonymous or inner class, you'd be able to forego the cast altogether.
new colorListener(parent, Color.LIGHT_GRAY); scares me as it's setting up a bunch of strongly references objects which can't be easily dereferenced, nor am I clear on there intent.
parent.revalidate(); isn't doing what you seem to think it's doing.
revalidate generates a new layout pass, what you seem to want is repaint.
These...
container.setPreferredSize(containerSize);
container.setBounds(height / 4, height / 4, containerSize.width, containerSize.height);
are just bad ideas. Let the content of the container, along with the layout manager deal with.
So, the short answer is, you have a lot of research left to do, things like:
OO design patterns
OO good practices, including "separation of responsibilities", "code decoupling" and in a more general sense, "dependency injection"
Model-View-Controller, coding to interface instead of implementation
just to name a few

Change color on click using repaint() method within Anonymous class

I spent 5 hours looking for solution to my question, but I really cannot.
I have only learnt java swing for 2 days to do this assignment.
( my professor didn't teach what is needed to finish assignment and only talked about swing for less then 30 mins)
I also tried to read Swing documentation, but I have no clue how to read documentation. Because getting into the read question I want to ask 2 irrelevant question.
How to search for method() like repaint() method which I cannot find in the documentation, but I found it on other website.
When learning new language, How would I start learning it from reading documentation? Do I read the tutorial or there are better way?
Questions above are raised because, in this situation, I found myself in loops of confusion, and I just do not know where to start/learn and how.
Anyway, Lets get to the point.
What make this question so confusing to me are all the conditions and requirements that need to be met.
Goal: to have 3 buttons with color's name on it that when is clicked on the color of circle icon changed.
Requirements(confusing part to me)
button label must be color's name in this case red/green/blue
displays a simple icon with a circle initially colored solid red
the circle color must change to that indicated by the
button's label.
when a button is clicked you need to change the icon's color, then
call the label's repaint() method. This, in turn will call the icon's paintIcon() [Jlabel calls paintIcon for us]
the buttons' action listener objects must be of anonymous classes.
button must create in main() and set up in loop.
for (i=0; i<3; i++) {
btn[i] = createButton(i, ......);
}
The createButton() function you will write gets an index (0 to 2) and creates the green, blue, and red buttons, depending on the valus of i. JButton objects are returned with the proper listener attached.
Hint: Use a Color array that can be indexed by i:
Color[] colors = new String[]{"RED", "GREEN", "BLUE"};
Then, create the color with the required color:
Below are my current code:
The problems I have are:
how to label create color object that contain string. ( required by professor, but his code does not even work)
How do I use repaint() in ActionPerform to send "signal" to paintIcon, so that when I click a button. Circle shape changes color.
public class Button_hw implements Icon {
private int size;
private Color color;
public Button_hw(int aSize)
{
size = aSize;
}
// #Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double planet = new Ellipse2D.Double(x,y,size,size);
g2.setColor(color);
g2.fill(planet);
}
#Override
public int getIconWidth() {
return size;
}
#Override
public int getIconHeight() {
return size;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
final Color[] colors;
colors = new Color[3];
colors[0]= Color.GREEN;
colors[1]= Color.RED;
colors[2]= Color.BLUE;
Button_hw Circle = new Button_hw(50);
final JLabel label = new JLabel(Circle);
final int FIELD_WIDTH = 20;
JButton btn[];
btn = new JButton[3];
for (int i=0; i<3; i++) {
btn[i] = new JButton(String.valueOf(colors[i]));
}
JTextField textField = new JTextField(FIELD_WIDTH);
textField.setText("Click a button!");
btn[0].addActionListener(new
ActionListener(){
public void actionPerformed(ActionEvent event)
{
textField.setText("green");
label.repaint();
}
});
btn[1].addActionListener(new
ActionListener(){
public void actionPerformed(ActionEvent event)
{
textField.setText("red");
label.setColor(Color.RED);
label.repaint();
}
});
btn[2].addActionListener(new
ActionListener(){
public void actionPerformed(ActionEvent event)
{
textField.setText("blue");
label.repaint();
}
});
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(btn[0]);
frame.add(btn[1]);
frame.add(btn[2]);
frame.add(textField);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
So I stumbled upon this question and answer and converted it to suit your example. Probably the same class, different year. This is what I got:
public class ColorChanger implements Icon {
private Color color;
public ColorChanger() {
color = Color.red;
}
#Override
public int getIconWidth() {
return 10;
}
#Override
public int getIconHeight() {
return 10;
}
public void setColor(Color color) {
this.color=color;
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double circle = new Ellipse2D.Double(0, 0, 10, 10);
g2.setColor(color);
g2.fill(circle);
}
public static void main(String[] args) {
JFrame myFrame = new JFrame();
ColorChanger myCircle = new ColorChanger();
final JLabel myLabel = new JLabel(myCircle);
final int FIELD_WIDTH = 20;
JTextField textField = new JTextField(FIELD_WIDTH);
textField.setText("Click a button!");
final String[] colors = new String[]{"RED", "GREEN", "BLUE"};
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < colors.length; i++) {
if(e.getActionCommand().equals(colors[i])) {
switch (colors[i]) {
case "RED":
myCircle.setColor(Color.RED);
break;
case "GREEN":
myCircle.setColor(Color.GREEN);
break;
case "BLUE":
myCircle.setColor(Color.BLUE);
break;
default:
myCircle.setColor(Color.BLACK);
break;
}
textField.setText(colors[i]);
break;
}
}
myLabel.repaint();
}
};
JButton btn[];
btn = new JButton[3];
for (int i=0; i<3; i++) {
btn[i] = new JButton(colors[i]);
btn[i].addActionListener(listener);
}
myFrame.setLayout(new FlowLayout());
myFrame.add(myLabel);
for (int i=0; i<3; i++) {
myFrame.add(btn[i]);
}
myFrame.add(textField);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
}
Your Circle class must implement the Icon interface to behave as an Icon and implement the paintIcon methods. That is most likely where you went wrong.
I also added a single listener and used the ActionCommand to determine which color was selected. It just makes it a little more concise to write. Please do ask if you do not understand.
To answer your two irrelevant questions at the beginning.
All methods should be available in the documentation. It may be in different classes or interfaces which are extended and implemented but it must be there.
I would not start by reading the documentation. I would start with learning the syntax with introductory tutorials and from there look for examples on what you want to do. Documentation is in my opinion for official reference and explanation, not learning. In other words if you want to know what a method does in detail - read the documentation. If you want to know how to use it - find an example.

Placing an invisible button on top of an Image

I'm making a small java game for fun to practice with my GUI programming. I want to have the center of my content pane's borderLayout be an image, and I would like to put "invisible" buttons on top of the image in specific places (to be placed later, I just want to get one working for now). My issue is getting the button to actually be invisible, it seems to leave a white square where it is now. I looked around but the only things that seem to be suggested were the .setOpaque, .setContentAreaFilled, and .setBorderPainted. (game is space related, explains the names)
galaxyButton1 = new JButton();
galaxyButton1.setFont(starSystem);
galaxyButton1.setBorder(BorderFactory.createEmptyBorder(25,25,25,25) );
galaxyButton1.setOpaque(false);
galaxyButton1.setContentAreaFilled(false);
galaxyButton1.setBorderPainted(false);
Color invis = new Color(Color.TRANSLUCENT);
galaxyButton1.setForeground(invis);
galaxyButton1.setBackground(invis);
galaxyButton1.addActionListener( new ButtonHandler() );
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout( 1,0,5,5 ) );
buttons.setOpaque(false);
buttons.add(galaxyButton1);
centerPanel.add(buttons,BorderLayout.CENTER);
centerImg.setLayout(new GridBagLayout());
centerImg.add(centerPanel);
contentPane.add(centerImg, BorderLayout.CENTER);
Here is a code outline of how to make your own button. You will need to set up a the actual mouse in some other class.
public class InvisibleButton implements MouseListener{
private final Rectangle rectangle;
public InvisibleButton(int x, int y, int width, int height){
rectangle = new Rectangle(x,y,width,height);
}
#Override
public void mouseClicked(MouseEvent e) {
int x = 0; // Set this to Mouse X
int y = 0; // Set this to Mouse Y
if(rectangle.contains(x,y)){
//Set Something to True or do action here
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}

Check location of each button

I have a frame that contains 81 buttons, lets say all the buttons contain no name, are all equal in size, and are all set automatically. So when I click one I would like to know which one is clicked. If I use a class that implements MouseListener and with this method
mouseClicked(MouseEvent e){
temp[0]= e.getX();
temp[1]= e.getY();
}
How can I check with these coordinates?
Do I have to set each of the buttons with its own location to do that?
I believe this is what you are looking for.
public static final int BUTTONS_WIDTH_COUNT = 9;
public static final int BUTTONS_HEIGHT_COUNT = 9;
public static final Button[][] BUTTONS = new Button[BUTTONS_WIDTH_COUNT][BUTTONS_HEIGHT_COUNT]
...
// I'll assume that the buttons are taking up the entire frame so no offsets are taken into account
frame.addMouseListener(
new MouseAdaptor() {
mouseClicked(MouseEvent e) {
// The X Y coordinates are relative to the component so
int frameWidth = frame.getBounds().getWidth();
int frameHeight = frame.getBounds().getHeight();
Button buttonClicked = buttons[e.getX()/(frameWidth/BUTTONS_WIDTH_COUNT)][e.getY()/(frameHeight/BUTTONS_HEIGHT_COUNT)];
}
}
EDIT: Actually it will be a lot better to assign the same MouseAdaptor to all the buttons and use e.getSource() to know which button was invoking in the listener.

A class that separatley creates a JTextField with implemented keyListener, however it remains undetected when called in this way from main function

I wish to make a rough and ready load of reusable swing classes to save a bit of coding and to recap on what I once new however I cannot understand what it is in my problem that is not working; apart from some fundamental basic understanding of course.
Now I have looked at lots of questions about focuses and implementing keylistener, I actually tried a combination of all other threads on this problem and still don't have the answer that works.
In the Easyswing class, I hoped to take advantage of java knowing which constructor to use to determine the component I got, please also suggest a better way of doing it if you know it
here is my main snippet
public class mainbox
{
static Easyswing tix = new Easyswing(300,500);;
public static void main(String[] args) {
System.out.println(tix.getText());
}
And here is the Easyswing class:
public class Easyswing
{
String text;
int locationx, locationy;
JTextArea tarea;
JTextField tfield;
JScrollPane scrollpane;
boolean istarea;
//text on startup, size in rows, size in columns, is editable, might take advantage of different constructors to give different uses to this class outputting messages
Easyswing(String t, int x, int y,int lx, int ly){
//create and initialise text areas starting text, size in number of rows and columns
tarea = new JTextArea("",x, y);
//create slight border to avoid text right on edge
tarea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
//adds the text area to the scroll pane
scrollpane = new JScrollPane(tarea);
JFrame frame1 = new JFrame(t);
frame1.setSize(x,y);
frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
frame1.add(scrollpane);
frame1.setLocation(locationx = lx, locationy = ly);
frame1.setVisible(true);
//if it is a text area then true
istarea = true;
}
//this will create a basic text input field
Easyswing(int lx, int ly){
tfield = new JTextField();
scrollpane = new JScrollPane(tfield);
JFrame frame1 = new JFrame("Write");
frame1.setSize(250,75);
frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
frame1.add(scrollpane);
frame1.setLocation(locationx = lx, locationy = ly);
frame1.requestFocus();
//HERE HERE THIS IS WHAT I DID HERE WHY DOESNT THIS WORK???
frame1.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e) {
System.out.println("whut");
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
});
frame1.setVisible(true);
istarea = false;
}

Categories

Resources