How to add JPanel from another class to frame - java

Im trying to figure out how to add a JPanel into my main Frame. However, the Panel is in a different class. Essentially, I need the user to press the start button,once pressed it needs to create an object of a class (this class creates a JPanel) and add to main frame. My issue is that once I press the start button nothing happens.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;
public class Display extends JFrame{
private JPanel right,left,center,south;
private JButton start, stop,car1,car2,car3,car4;
private JTextArea text1,text2;
private TitledBorder title1,title2;
private JLabel label,label2,label3;
private RaceDisplay rd;
private Environment env;
public Display() {
super("CAR GAME");
/* ---------------------------------
* BOARD PANELS
-----------------------------------*/
//right panel uses a different layout
right = new JPanel();
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
right.setBackground(Color.GRAY);
//center panel uses default layout
center = new JPanel();
//left panel uses a different layout
left = new JPanel();
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
left.setBackground(Color.GRAY);
//south panel
south = new JPanel();
south.setBackground(Color.GRAY);
/* ---------------------------------------
* Text area used to diaply the results.
------------------------------------------*/
text1 = new JTextArea();
text2 = new JTextArea();
// ------------>car images to be used in the Car class<------------------
ImageIcon img = new ImageIcon("./images/Car1-small.gif");
ImageIcon img2 = new ImageIcon("./images/car2-small.gif");
ImageIcon img3 = new ImageIcon("./images/car3-small.gif");
ImageIcon img4 = new ImageIcon("./images/car4-small.gif");
ImageIcon imgFlag = new ImageIcon("./images/flag1.png");
ImageIcon imgFlag2 = new ImageIcon("./images/flag2.png");
label2 = new JLabel(imgFlag);
label3 = new JLabel(imgFlag2);
center.add(label3);
label = new JLabel("BEST TEAM EVER RACE GAME");
label.setFont(new Font("Georgia", Font.CENTER_BASELINE, 16));
/* ----------------------------------------------------
* creates the buttons and adds the proper image to them
--------------------------------------------------------*/
car1 = new JButton("BRITISH MOTOR COMPANY",img);
car2=new JButton("FAST AND FURIOUS",img2);
car3=new JButton("SCOOBY GANG",img3);
car4=new JButton("SPEEDY CADDY",img4);
start=new JButton("START");
stop = new JButton("STOP");
/* ----------------------------------------------------
* creates the title border and adds them to panels
--------------------------------------------------------*/
title1 = new TitledBorder("RESULTS");
title2 = new TitledBorder("CHOOSE YOUR RACER!");
//adds the title borders to the Panels.
right.setBorder(title1);
left.setBorder(title2);
/* ----------------------------------------------------
* This TextArea is added to the right Panel and it where
* the result will be displayed
--------------------------------------------------------*/
text1 = new JTextArea(" ",100,30);
right.add(text1);
text1.setLineWrap(true);
/* ----------------------------------------------------
* adds the buttons to the proper panels
--------------------------------------------------------*/
south.add(start);
south.add(stop);
left.add(car1);
left.add(car2);
left.add(car3);
left.add(car4);
left.add(label);
left.add(label2);
/* ----------------------------------------------------
* adds the panels to the main Frame at proper location
--------------------------------------------------------*/
add(right,BorderLayout.EAST);
add(left,BorderLayout.WEST);
add(south,BorderLayout.SOUTH);
add(center,BorderLayout.CENTER);
/* -------------------------------------------------
* Gives actions to the buttons
---------------------------------------------------- */
car1.addActionListener(new Car1Button());
car2.addActionListener(new Car2Button());
car3.addActionListener(new Car3Button());
car4.addActionListener(new Car4Button());
start.addActionListener(new Start());
/* ----------------------------------------------------
* sets up the main frame's components
--------------------------------------------------------*/
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1900,700);
setVisible(true);
}//end of constructor
/**
*
*/
private class Start implements ActionListener{
public void actionPerformed(ActionEvent event){
rd = new RaceDisplay();
add(rd);
}
}
This is the other class where the panel is created.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class RaceDisplay extends JPanel implements ActionListener{
private Image img1,img2,img3,img4;
private int velX;
private int x;
private Timer tm;
private Environment env;
private Car car;
public RaceDisplay(){
tm = new Timer(30,this);
x=0;
//velX=car.getSpeed();
velX=x;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon car1 = new ImageIcon("./images/Car1-small.gif");
ImageIcon car2 = new ImageIcon("./images/car2-small.gif");
ImageIcon car3 = new ImageIcon("./images/car3-small.gif");
ImageIcon car4 = new ImageIcon("./images/car4-small.gif");
img1 = car1.getImage();
img2 = car2.getImage();
img3= car3.getImage();
img4= car4.getImage();
g.drawImage(img1,x,100,null);
g.drawImage(img2,x,200,null);
g.drawImage(img3,x,300,null);
g.drawImage(img4,x,400,null);
tm.start();
}
//method runs the images from left to right
public void actionPerformed(ActionEvent e) {
x = x+velX;
if(x>=600){
x=0;
x=x+velX;
// // this.wait();
// } catch (InterruptedException ex) {
// Logger.getLogger(RaceDisplay.class.getName()).log(Level.SEVERE, null, ex);
// }
repaint();
}
repaint();
}
public int getX(){
return x;
}
}

When you add a component to a visible GUI the basic code is:
panel.add(...);
panel.revalidate(); // to invoke the layout manager
panel.repaint();

What exactly do you want? I mean you want the added cars to start running??? for that case you need to write a thread. your start button works perfectly.

Related

How to call this method into my other file?

I want to be able to call the Introduction.Intro() method into my main file code, but it tells me I am unable to call a non-static method intro from a static context. Since I am still fairly new to coding I'm not entirely sure what the problem is. I've added my codes down below. I've tried countless online methods but sadly none have seemed to work.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Start extends JFrame implements ActionListener
{
private JFrame Main;
private JPanel PanelA, PanelB, PanelC;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public Start ()
{
//Button
Button = new JButton("Start");
Button.addActionListener(new ButtonListener());
//Text
Text = new JLabel("Welcome To The Game"); //ADD NAME OF THE GAME
//Image
Image = new ImageIcon(getClass().getResource("download.jfif")); //ADD THE IMAGE FOR WELCOME
ImageL = new JLabel(Image);
//Top Panel (PanelA) - Image
PanelA = new JPanel();
PanelA.setBorder(BorderFactory.createEmptyBorder(0,200,150,200));
PanelA.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelA.add(ImageL);
//Middle Panel (PanelB) - Text
PanelB = new JPanel();
PanelB.setBorder(BorderFactory.createEmptyBorder(50,200,10,200));
PanelB.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelB.add(Text);
//Bottom Panel (PanelC) - Buttons
PanelC = new JPanel();
PanelC.setBorder(BorderFactory.createEmptyBorder(0,200,20,200));
PanelC.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelC.add(Button);
//Main Frame
Main = new JFrame ();
Main.add(PanelA, BorderLayout.NORTH);
Main.add(PanelB, BorderLayout.CENTER);
Main.add(PanelC, BorderLayout.SOUTH);
Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main.setTitle("GAME TITLE"); //ADD THIS LATER
Main.pack();
Main.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae)
{
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button)
{
Introduction.Intro1(); //THESE LINE RIGHT HERE
return null; //THESE LINE RIGHT HERE
}
}
}
public static void main(String[] args)
{
new Start();
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Introduction
{
private JFrame Main;
private JPanel PanelD;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public void Intro()
{
Image = new ImageIcon(getClass().getResource("guy.jfif"));
ImageL = new JLabel(Image);
PanelD = new JPanel();
PanelD.setBorder(BorderFactory.createEmptyBorder(0,100,10,100));
PanelD.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelD.add(ImageL);
PanelD.setVisible(true);
Main.add(PanelD, BorderLayout.NORTH);
}
}
EDIT: So I made another method in the Introduction class where I added this line of code, it managed to fix the error, however, the panel isn't being saved and my JFrame is outputting blank.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}
If you are looking to initialize the Introduction class in main method of Start class, You can add belo code in main method after Start()
Introduction M = new Introduction();
You main method becomes :
public static void main(String[] args)
{
new Start();
Introduction M = new Introduction();
m.Intro
}
Looking at this set of code, It looks like there is incompatible issue, as you have declare JFrame as return type, while you are returning instance of Introduction.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}

Why am I not able to add a JPanel to a JPanel?

I would like to draw something like this weather map:
On the top, there is a header which contains information (title, ...) and below there is the actual picture. I tried to model the program like the following but it does not show the image of the weather map.
Later I would like to be able to resize the whole weather map (title and picture).
public class Application {
public static void main(String[] args) {
Window meteoWindow = new Window();
meteoWindow.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
Container c;
WeatherMap wm1;
public Window() {
c = getContentPane();
// Loading weather maps
wm1 = new WeatherMap("http://www.link-to-image.com/weatherimage.png");
// ---
c.add(wm1);
setTitle("Meteoview Alpha");
setSize(new Dimension(1920, 1080));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
public class WeatherMap extends JPanel {
private DescriptionPanel descriptionPanel;
private ImagePanel imagePanel;
private WeatherImage weatherImage;
public WeatherMap(String urlPath) {
imagePanel = new ImagePanel();
descriptionPanel = new DescriptionPanel("Wetterkarte 1");
weatherImage = new WeatherImage("http://www.linktoweatherimage/image.png");
}
}
import javax.swing.*;
import java.awt.*;
public class DescriptionPanel extends JPanel {
private String name;
private JLabel nameLabel;
public DescriptionPanel(String name) {
this.name = name;
nameLabel = new JLabel(name, JLabel.LEFT);
setLayout(new FlowLayout());
add(nameLabel);
}
}
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
public class ImagePanel extends JPanel {
private BufferedImage image;
public ImagePanel() {
//setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
try {
image = ImageIO.read(new URL("http://www.linktoimage/image.png"));
System.out.println("Successfully read...");
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
As you can see, I tried it with a few different approaches, but nothing really works. Can you help me to model this? (JPanel on JPanel, or BufferedImage on JPanel, ...)
imagePanel = new ImagePanel();
descriptionPanel = new DescriptionPanel("Wetterkarte 1");
weatherImage = new WeatherImage("http://www.modellzentrale.de/WRF4km/12Z/15h/RR3h_eu.png");
You create 3 components, but you don't add the components to the panel.
Not really sure what you are trying to do since you attempt to read the same image twice, so I don't know why you have a "WeatherImage" and an "ImagePanel".
So I will just suggest you first try something like the following to understand how to use a panel with a layout manager.
imagePanel = new ImagePanel();
descriptionPanel = new DescriptionPanel("Wetterkarte 1");
setLayout( new BorderLayout() );
add(descriptionPanel, BorderLayout.PAGE_START);
add(imagePanel, BorderLayout.CENTER);
Also, then is no need to create a custom painting to simply paint an image at it actual size. You can just add the Image to a JLabel by using an ImageIcon:
image = ImageIO.read(…);
JLabel imageLabel = new JLabel( new ImageIcon(image) );
Now you add the label to any panel you want.

Java GUI ButtonHandler issue

I'm not sure what exactly I am doing wrong but I keep getting an error with the ButtonHandler. I have a GUI class and a GUI Test class. The GUI class is the first one and the GUI_Test class is at the bottom. I am using NetBeans IDE 11.0. Everything else works on here but the ButtonHandler. I believe I followed the directions wrong or something because it just keeps telling me to create a new class for the ButtonHandler or break it up. But neither of those things are what I want.
The checkboxes also will not appear in the output text area when you run it.
package javaapplication20;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class Week3GUI extends JFrame {`
//variables
private JRadioButton radCoffee, radTea;
private JCheckBox chkFootball, chkBasketball, chkBaseball;
private JTextArea txtMessage;
public Week3GUI()
{
//instantiate the GUI components
// this sets 5 rows, 20 columns as default size
txtMessage = new JTextArea(5,20);
radCoffee =new JRadioButton("Coffee");
radTea =new JRadioButton("Tea");
//instantiate checkboxes
chkFootball =new JCheckBox("football");
chkBasketball =new JCheckBox("basketball");
chkBaseball =new JCheckBox("baseball");
//create panel for the radio buttons
JPanel p1 =new JPanel();
JPanel p2 =new JPanel();
//set layout for the panel and add the components
p1.setLayout(new FlowLayout());
p1.add(radCoffee);
p1.add(radTea);
// set layout for the panel and add the components
p2.setLayout(new FlowLayout());
p2.add(chkFootball);
p2.add(chkBasketball);
p2.add(chkBaseball);
//need to group the buttons together
ButtonGroup b =new ButtonGroup();
b.add(radCoffee);
b.add(radTea);
//add event handlers for radio buttons
RBHandler rb =new RBHandler();
radCoffee.addItemListener(rb);
radTea.addItemListener(rb);
//use grid layout for the frame
//1 column, multiple rows
setLayout(new GridLayout(0,1));
//first "row" of the frame is the label
add(new JLabel("Which do you like?"));
//next "row" is the panel p1 with radio buttons
add(p1);
//third "row" is the textfield
add(p2);
// fourth "row" is the textfield
add(txtMessage);
} //end constructor
private class RBHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(radCoffee.isSelected())
txtMessage.setText("You like coffee");
else if(radTea.isSelected())
txtMessage.setText("You like tea");
}
private void processChoices()
{
//"read" the radio buttons first
if(radCoffee.isSelected())
txtMessage.setText("You like\ncoffee");
else if (radTea.isSelected())
txtMessage.setText("You like\ntea");
else
{
JOptionPane.showMessageDialog(null,"Must select a beverage",
"Error",JOptionPane.ERROR_MESSAGE);
return; //do NOT continue this method
}
//now read the check boxes and APPEND to textarea
if(chkFootball.isSelected())
txtMessage.append("\nfootball");
if(chkBasketball.isSelected())
txtMessage.append("\nbasketball");
if(chkBaseball.isSelected())
txtMessage.append("\nbaseball");
}
private class ButtonHandler implements ActionListener
{
ButtonHandler h = new ButtonHandler();
#Override
public void actionPerformed(ActionEvent actionEvent)
{
processChoices();
radCoffee.addActionListener(h);
radTea.addActionListener(h);
chkFootball.addActionListener(h);
chkBaseball.addActionListener(h);
chkBasketball.addActionListener(h);
}
}
}
} //end class
package javaapplication20;
import javax.swing.JFrame;
public class Week3GUI_Test {
public static void main(String[] args)
{
Week3GUI g =new Week3GUI();
g.setSize(300,200);
g.setVisible(true);
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Radio button event handlers

I'm having some trouble with a java project. I've made an empty GUI interface, and now I need to add some functionality to it. I'm stuck, however, on how to go about that. The basic layout has 4 radio buttons, Rectangle, Box, Circle, and Cylinder. I have a group panel that has 4 separate panels that each have text boxes with labels for entering height, length, width, and radius. Here's how it looks: GUI layout. Depending on the radio button that is selected, certain boxes that aren't needed should be hidden. For example, if Rectangle is selected, only the boxes for length and width should be visible.
The main frame that will display everything is here:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import java.awt.Font;
public class GUIFrame extends JFrame
{
//private final BorderLayout layout;
private final FlowLayout layout;
private final JLabel lblTitle;
private final JButton btnProc;
public GUIFrame()
{
super("GUI Layout");
Font titleFont = new Font("Verdana", Font.BOLD, 26);
btnProc = new JButton("Click to Process");
lblTitle = new JLabel("Figure Center");
lblTitle.setFont(titleFont);
widthPanel myWidth = new widthPanel();
myWidth.setLocation(0, 400);
lengthPanel myLength = new lengthPanel();
heightPanel myHeight = new heightPanel();
radiusPanel myRadius = new radiusPanel();
radioButtonPanel myButtons = new radioButtonPanel();
//layout = new BorderLayout(3, 2);
layout = new FlowLayout();
JPanel txtGroup = new JPanel();
txtGroup.setLayout(new GridLayout(2, 2));
txtGroup.add(myWidth);
txtGroup.add(myLength);
txtGroup.add(myRadius);
txtGroup.add(myHeight);
setLayout(layout);
add(lblTitle);
add(myButtons);
add(txtGroup);
add(btnProc);
if(myButtons.btnRectangle.isSelected())
{
myHeight.setVisible(false);
myRadius.setVisible(false);
}
}
private class RadioButtonHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent event)
{
}
}
}
I can get this working using if statements, but I'm supposed to be using event handlers and I'm lost on how to code that to get it to work properly.
if it helps, here's the code for the button panel:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import java.awt.GridLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class radioButtonPanel extends JPanel
{
private final JRadioButton btnRectangle;
private final JRadioButton btnBox;
private final JRadioButton btnCircle;
private final JRadioButton btnCylinder;
private final ButtonGroup radioButtonGroup;
private final JLabel label;
private final JPanel radioPanel;
public radioButtonPanel()
{
radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(5,1));
btnRectangle = new JRadioButton("Rectangle", true);
btnBox = new JRadioButton("Box", false);
btnCircle = new JRadioButton("Circle", false);
btnCylinder = new JRadioButton("Cylinder", false);
label = new JLabel("Select A Figure:");
radioPanel.add(label);
radioPanel.add(btnRectangle);
radioPanel.add(btnBox);
radioPanel.add(btnCircle);
radioPanel.add(btnCylinder);
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(btnRectangle);
radioButtonGroup.add(btnBox);
radioButtonGroup.add(btnCircle);
radioButtonGroup.add(btnCylinder);
add(radioPanel);
}
}
And a sample of one of the panels. They all follow the same setup, just different variable names.
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.GridLayout;
public class heightPanel extends JPanel
{
private final JLabel lblHeight;
private final JTextField txtHeight;
private final JPanel myHeight;
public heightPanel()
{
myHeight = new JPanel();
myHeight.setLayout(new GridLayout(2,1));
lblHeight = new JLabel("Enter Height:");
txtHeight = new JTextField(10);
myHeight.add(lblHeight);
myHeight.add(txtHeight);
add(myHeight);
}
}
The below code should give you a quick introduction of how to use event listener/handler for your button group (JRadioButtons).
but I'm supposed to be using event handlers and I'm lost on how to
code that to get it to work properly.
//add listener to the rectangle button and should be the same for the other `JRadioButtons` but with different `identifiers`.
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRectangle){
//TODO
}
}
});
Depending on the radio button that is selected, certain boxes that
aren't needed should be hidden. For example, if Rectangle is selected,
only the boxes for length and width should be visible.
//To hide JTextFields use
void setVisible(boolean visible) method. You should pass false as the argument to the method if you want to hide the JTextField.
Example:
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRectangle){
TextFieldName.setVisible(false); // set the textfields that you want to be hidden once the Rectangle button is chosen.
}
}
});

How to put button where I want on screen.

Okay I want to place my button in a certain place on the screen. Is there any way to place it at an exact pixel location? Right now it places it to the far right of my screen. I have an image that I would want it to go over too.
import java.awt.AWTException;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.WritableRaster;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class UnfollowGUI extends JFrame{
private JLabel label;
private JButton button;
private ImageIcon bgi;
private JLabel bgl;
public static Rectangle gameSquare;
public static boolean rock = true;
public static boolean runningMine = true;
public static int stray = 0;
public static int strayCount = 0;
public static void main(String[] args) {
UnfollowGUI gui = new UnfollowGUI ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
//gui.setSize(886, 266);
gui.pack();
gui.setVisible(true);
gui.setTitle("Solid Cloud Inc - Twitter Unfolower");
}
public UnfollowGUI(){
setLayout(new FlowLayout());
bgi = new ImageIcon(getClass().getResource("tu.png"));
bgl = new JLabel (bgi);
add(bgl);
ImageIcon start = new ImageIcon(getClass().getResource("start.png"));
button = new JButton (start);
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
add(button);
label = new JLabel ("");
add(label);
Events e = new Events();
button.addActionListener(e);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
label.setText("Searching");
try {
Unfollow();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components.
To organize the components for a robust GUI, instead use layout managers (or combinations of them), along with layout padding & borders for white space.
Yet another way to achieve what you describe can be done this way (there are many alternatives, but in the end, it all depends on how you want your components to be relatively positionned to each other and what happens when the size of the parent container changes):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestLoginGridBagLayout {
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame("Background image");
frame.getContentPane().setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel background = new JLabel(new ImageIcon(new URL("http://images2.layoutsparks.com/1/161318/city-lights-bridge-decoration.jpg")));
background.setVerticalAlignment(JLabel.BOTTOM);
background.setHorizontalAlignment(JLabel.LEFT);
background.setLayout(new BorderLayout());
frame.add(background);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
buttonPanel.setOpaque(false);
buttonPanel.add(new JButton("Some button in the bottom left"));
background.add(buttonPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestLoginGridBagLayout().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}
You can place things in the exact place you want by not using a Layout Manager. This is called absolute positioning, and you can read a tutorial on it here: http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
Here's a snippet of code from inside that tutorial:
pane.setLayout(null);
JButton b1 = new JButton("one");
JButton b2 = new JButton("two");
JButton b3 = new JButton("three");
pane.add(b1);
pane.add(b2);
pane.add(b3);
Insets insets = pane.getInsets();
Dimension size = b1.getPreferredSize();
b1.setBounds(25 + insets.left, 5 + insets.top,
size.width, size.height);
size = b2.getPreferredSize();
b2.setBounds(55 + insets.left, 40 + insets.top,
size.width, size.height);
size = b3.getPreferredSize();
b3.setBounds(150 + insets.left, 15 + insets.top,
size.width + 50, size.height + 20);
...//In the main method:
Insets insets = frame.getInsets();
frame.setSize(300 + insets.left + insets.right,
125 + insets.top + insets.bottom);
That ends up looking like this:

Categories

Resources