I'm trying to create a JButton
(r
) and to set its absolute position. I also want to change the background color. When I insert a new FlowLayout
like this: setLayout(new FlowLayout());
the color of the background doesn't change while the absolute position does.
Meanwhile when removing this: setLayout(new FlowLayout());
the absolute position doesn't change while the color does. So can anyone explain me why this happens and how can I change the code in a way thet both of them the color and the posiotion absolute of the JButton
change?
This is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.Random;
public class Back extends JFrame{
private JButton r;
private JButton c;
private Container container;
public Back(){
super("title");
//setLayout(new FlowLayout());
ran = new Random();
value = nextValue();
r=new JButton("ROLL");
add(r,BorderLayout.SOUTH);
thehandler hand=new thehandler(this);//konstruktori i handler merr nje instance te Background
r.addActionListener(hand);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event) {
}
}
public static void main(String[] args) {
Back d = new Back() ;
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.getContentPane().setBackground(Color.GREEN);
d.setSize(700,500);
d.setVisible(true);
}
}
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Back extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton r;
public Back(){
super("title");
setLayout(null);
r=new JButton("ROLL");
r.setBounds(20, 20, 70, 30);
add(r);
Thehandler hand=new Thehandler(this);//konstruktori i handler merr nje instance te Background
r.addActionListener(hand);
}
private class Thehandler implements ActionListener{
private JFrame frame;
public Thehandler(JFrame frame) {
this.frame = frame;
}
public void actionPerformed(ActionEvent event) {
Random ra = new Random();
int r = ra.nextInt(255);
int g = ra.nextInt(255);
int b = ra.nextInt(255);
Color c = new Color(r, g, b);
frame.getContentPane().setBackground(c);
}
}
public static void main(String[] args) {
Back d = new Back() ;
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.getContentPane().setBackground(Color.GREEN);
d.setSize(700,500);
d.setVisible(true);
}
}