Sunday, December 1, 2013

How to move elements around in Swing?


Hi I'm a beginner with the Java AWT/Swing package. And I'm wonder how to move around the x and y position of the elements. If we say that we have a screen and we won't to move that label for example to the left edge of the screen or to the right edge of the screen. How can you do that? I don't know what to use. But you guys that knows this, I'm sure you can help me out! :)


The code I've written for the program looks like this:


Window - The main java file



Java Code:



package JavaClasses.Testing;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Window extends JFrame implements KeyListener
{
public JLabel pressed = new JLabel();
public JLabel text = new JLabel("Press any key: ");
public JTextField userInput = new JTextField(20);

public Window(String title, int w, int h)
{
// Set the title of the window
super(title);

// Set the size of the window
super.setSize(w, h);

/*FlowLayout layout = new FlowLayout(FlowLayout.LEFT, 10, 10);
super.setLayout(layout);
userInput.addKeyListener(this);
super.add(text);
super.add(userInput);
super.add(pressed);*/

LinkedGUI gui = new LinkedGUI();
super.add(gui);

// Set default close operation
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Show the window
super.setVisible(true);
}

public void keyTyped(KeyEvent input)
{
char key = input.getKeyChar();
pressed.setText("You pressed: " + key);
}
public void keyPressed(KeyEvent input) {}
public void keyReleased(KeyEvent input) {}

public static void main(String[] args)
{
Window win = new Window("GUI", 326, 218);
}
}

FirstGUI - The file that creates the GUI


Java Code:



package JavaClasses.Testing;
import java.awt.*;
import javax.swing.*;

public class LinkedGUI extends JPanel
{
public LinkedGUI()
{
JPanel gui = new JPanel();

GridLayout layout = new GridLayout(3, 2);
gui.setLayout(layout);

JButton[] buttons = new JButton[5];
String[] nameOfButtons = {"Button 1", "Button 2", "Button 3"
, "Long-Named Button 4", "5"};
for (int i = 0; i < 5; i++)
{
buttons[i] = new JButton(nameOfButtons[i]);
gui.add(buttons[i]);
}

JPanel gui2 = new JPanel();

BorderLayout bordLayout = new BorderLayout(10, 10);
gui2.setLayout(bordLayout);

JLabel axis = new JLabel("Horizontal gap: " + " Vertical gap: ");
gui2.add(axis, BorderLayout.WEST);

super.add(gui);
super.add(gui2);
}
}

I'm just practice to create a good looking GUI in Java AWT/Swing. So it would be great if you can create the layout for

exactly how it should look like :)

No comments:

Post a Comment