I am trying to make a program to java and i have the common problem with flickering. I have try many things to eliminate but all the same. while the oval that i paint is moving the japplet is flickering. i need your help to solve this problem. here is my code:
import java.awt.Color;
public class all extends JApplet implements Runnable {
double x=0;
double y=0;
int m=0;
int n=0;
int f=30;
int μ=0;
Thread kinisi;
JPanel panel;
JFrame frame;
private boolean running = false;
private JTextField textField1;
private JTextField textField2;
Image backGround;
JPanel panel_3;
Image bf = createImage(m, n);
private Graphics doubleg;
private Image i;
public void init() {
this.setSize(800, 700);
}
public all() {
getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Start");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String b=textField2.getText();
String z =textField1.getText();
if (textField1.getText().equals("") ||
textField2.getText().equals("")){
JOptionPane.showMessageDialog(
new JFrame(),
"Δωστε τιμή για το φ και το μ!",
"ERROR",JOptionPane.ERROR_MESSAGE);
} else{
f = Integer.parseInt(b);
μ = Integer.parseInt(z);
Start(); }
}
});
btnNewButton.setBounds(469, 168, 89, 23);
getContentPane().add(btnNewButton);
JButton btnStop = new JButton("Pause");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pause();
}
});
btnStop.setBounds(588, 168, 89, 23);
getContentPane().add(btnStop);
JButton btnReset = new JButton("Reset");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Reset();
}
});
btnReset.setBounds(701, 168, 89, 23);
getContentPane().add(btnReset);
JLabel label = new JLabel("\u03BC");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(549, 63, 46, 14);
getContentPane().add(label);
textField1 = new JTextField();
textField1.setBounds(529, 101, 86, 20);
getContentPane().add(textField1);
textField1.setColumns(10);
JLabel label_1 = new JLabel("\u03C6");
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setBounds(681, 63, 46, 14);
getContentPane().add(label_1);
textField2 = new JTextField();
textField2.setBounds(667, 101, 86, 20);
getContentPane().add(textField2);
textField2.setColumns(10);
JButton btnNewButton_1 = new JButton("");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(
new JFrame(),
"Οδηγίες προγράμματος","Οδηγίες",
JOptionPane.INFORMATION_MESSAGE);
}
});
btnNewButton_1.setIcon(
new ImageIcon(all.class.getResource("/Images/info.png")));
btnNewButton_1.setBounds(732, 5, 39, 35);
getContentPane().add(btnNewButton_1);
JLabel label_2 = new JLabel("");
label_2.setIcon(
new ImageIcon(all.class.getResource("/Images/earth.jpg")));
label_2.setBounds(-20, 0, 820, 361);
getContentPane().add(label_2);
JPanel panel_1 = new JPanel();
panel_1.setBorder(
new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel_1.setBounds(10, 372, 369, 290);
getContentPane().add(panel_1);
JPanel panel_2 = new JPanel();
panel_2.setBorder(
new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel_2.setBounds(408, 372, 369, 290);
getContentPane().add(panel_2);
}
public void paint(Graphics g){
super.paint(g);
g.drawLine(0,f,350,200);
g.drawLine(0,200,350,200);
g.drawOval(m,n,40,40);
Color brown=new Color(137,66,0);
g.setColor(brown);
g.fillOval(m, n, 40, 40);
//Graphics2D g2d = (Graphics2D) g;
g.drawLine(460,400,460,650);
g.drawLine(20, 620, 350, 620);
g.drawLine(50,400,50,650);
g.drawLine(430, 620, 760, 620);
}
public void Start() {
kinisi = new Thread(this);
kinisi.start();
running = true;
}
public void run() {
while (running) {
if (x < 340){
double l = 200-f;
double k = l/350;
double y=k*x+f-30;
x= x+1;
m = (int) x;
n = (int) y;
repaint();
try {
Thread.sleep(μ);
} catch (InterruptedException ie) {}
}
}
}
public void update(Graphics g) {
if(i==null){
i=createImage(800,700);
doubleg = i.getGraphics();
}
doubleg.setColor(getBackground());
doubleg.fillRect(0,0,800,700);
doubleg.setColor(getForeground());
paint(doubleg);
g.drawImage(i,0,0,this);
}
public void paint1(Graphics g){
g.drawLine(0, f ,350, 200);
g.drawOval(m, n, 40, 40);
Color brown=new Color(137,66,0);
g.setColor(brown);
g.fillOval(m, n, 40, 40);
}
public void pause() {
if (kinisi != null) {
running = false;
}
}
public boolean Reset() {
if (kinisi != null) {
running = false;
kinisi.interrupt();
kinisi = null;
x=0;
y=0;
f=30;
m=0;
n=0;
repaint();
textField1.setText("");
textField2.setText("");
}
Graphics g = getGraphics();
g.drawOval(m,n,40,40);
Color brown=new Color(137,66,0);
g.setColor(brown);
g.fillOval(m, n, 40, 40);
return false;
}
public static void main(String[] args) {
JFrame frame = new JFrame("FISIKI");
frame.getContentPane().add(new all());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 700);
frame.setVisible(true);
frame.setResizable(false);
}
}
Thank you very much and sorry for my english are not very good!
There are a number of things that jump out at me.
You're extending from JApplet, but are adding it to a JFrame
You're mixing components with you custom painting
Not using layout managers.
Using getGraphics.
Firstly...
You should never override paint of a top level container (like JApplet). There are many reasons and you've found one. Top level containers are not double buffered. Instead, you should be creating a custom component (by extending something like JPanel) and overriding it's paintComponent method...
Secondly
Decided how you application is going to be. Is it an applet or application? If you follow the first point, then it really doesn't matter, as you only simply need to add the panel to the top level container.
Thirdly
I would create a panel that did the custom painting. Then I would create separate containers for all the fields and other parts of the application. This will allow you to separate the areas of responsibility. It would also allow you to use layout managers ;)
Fourthly
Use layout managers. The layout manager API has being designed to solve one of this most annoying aspects of GUI design, you're asking for a lot of trouble and work you decided to discard it - IMHO.
Fifthly
getGraphics should never be used. Apart from the fact that it can return null, it is only a snap shot of what is currently on the screen. As soon as the RepaintManager decides to perform a repaint, anything rendered to it will be lost. You should use paintComponent to update the state of your custom pane.
Related
I have been working on some side project involving MySQL, with will use tree different screens: 'menu, ' add breed', 'browse breed'.
At this point section initialize is getting quite large and I would like to split it into 3 different classes.
Is it possible to initialize for example JPanel outside Window class?
public class Window {
public static void setBreed()
{
for(int i=0; i<16;i++) {
breedLabels[i].setText(breedInfo[i]);
breedLabels[i].setBounds(600,100+i*30,300, 100);
breedLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(breedLabels[i]);
}
}
public static void setText()
{
for(int i=0; i<16;i++) {
textLabels[i].setText(text[i]);
textLabels[i].setBounds(300,100+i*30,300, 100);
textLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(textLabels[i]);
}
}
public static String URL = "jdbc:mysql://localhost:3306/chooseyourpuppy";
public static String user = "root";
public static String password = "";
public static String query = "select * from breeds";
static String [] breedInfo = new String[16];
static String [] text = new String[16];
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
View.connect(URL, user, password, query);
}
public Window() {
initialize();
}
private JFrame frame;
public JPanel addBreed;
public static JPanel viewBreed;
public JPanel menu;
public static JLabel[] textLabels;
public static JLabel[] breedLabels;
private void initialize() {
final int WIDTH = 1280, HEIGHT = 720;
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("MyBREEDS Viewer");
frame.setResizable(false);
frame.setVisible(true);
//header
JPanel red = new JPanel();
red.setBounds(400, 0, 888, 80);
frame.getContentPane().add(red);
red.setBackground(new Color(204, 0, 0));
red.setLayout(null);
JPanel darkGrey = new JPanel();
darkGrey.setBounds(0, 0, 387, 80);
frame.getContentPane().add(darkGrey);
darkGrey.setBackground(new Color(51, 51, 51));
darkGrey.setLayout(null);
JLabel txtpnChoose = new JLabel();
txtpnChoose.setForeground(new Color(240, 240, 240));
txtpnChoose.setBounds(56, 11, 367, 63);
txtpnChoose.setFont(new Font("Verdana", Font.BOLD, 46));
txtpnChoose.setText("Choose your");
txtpnChoose.setBackground(null);
darkGrey.add(txtpnChoose);
JLabel txtpnPuppy = new JLabel();
txtpnPuppy.setBounds(5, 11, 166, 63);
txtpnPuppy.setForeground(new Color(240, 240, 240));
txtpnPuppy.setFont(new Font("Nunito-Bold", Font.BOLD, 46));
txtpnPuppy.setText("puppy");
txtpnPuppy.setBackground(null);
red.add(txtpnPuppy);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, WIDTH, HEIGHT);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
JButton btnMenu = new JButton("Back to menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(menu);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnMenu.setForeground(Color.WHITE);
btnMenu.setBackground(new Color(51, 51, 51));
btnMenu.setFont(new Font("Verdana", Font.BOLD, 18));
btnMenu.setBounds(660, 20, 180, 40);
btnMenu.setBorderPainted(false);
btnMenu.setFocusPainted(false);
red.add(btnMenu);
//menu
menu = new JPanel();
menu.setBackground(Color.WHITE);
layeredPane.add(menu, "name_410359960271086");
menu.setLayout(null);
JButton btnBrowse = new JButton("Browse breeds");
btnBrowse.setBounds(100, 300, 400, 200);
btnBrowse.setFont(new Font("Verdana", Font.PLAIN, 40));
btnBrowse.setBorder(new LineBorder(Color.DARK_GRAY));
btnBrowse.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnBrowse.setBackground(Color.WHITE);
btnBrowse.setRequestFocusEnabled(false);
btnBrowse.setVisible(true);
btnBrowse.setFocusPainted(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(viewBreed);
layeredPane.repaint();
layeredPane.revalidate();
setText();
setBreed();
}
});
btnBrowse.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnBrowse.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnBrowse.setBackground(Color.WHITE);
}
});
menu.add(btnBrowse);
addBreed = new JPanel();
layeredPane.add(addBreed, "name_410359942089403");
addBreed.setVisible(false);
addBreed.setBackground(Color.WHITE);
addBreed.setLayout(null);
//view breed window
viewBreed = new JPanel();
layeredPane.add(viewBreed, "name_410359924014670");
viewBreed.setLayout(null);
viewBreed.setVisible(false);
viewBreed.setBackground(Color.WHITE);
ImageIcon previous = new ImageIcon("src/images/previous.png");
ImageIcon previousHover = new ImageIcon("src/images/previousHover.png");
JButton prevBreed = new JButton(previous);
prevBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
prevBreed.setIcon(previousHover);
}
#Override
public void mouseExited(MouseEvent e) {
prevBreed.setIcon(previous);
}
});
prevBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(false);
}
});
prevBreed.setBounds(30, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(prevBreed);
prevBreed.setRequestFocusEnabled(false);
prevBreed.setOpaque(false);
prevBreed.setContentAreaFilled(false);
prevBreed.setBorderPainted(false);
prevBreed.setFocusPainted(false);
ImageIcon next = new ImageIcon("src/images/next.png");
ImageIcon nextHover = new ImageIcon("src/images/nextHover.png");
JButton nextBreed = new JButton(next);
nextBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
nextBreed.setIcon(nextHover);
}
#Override
public void mouseExited(MouseEvent e) {
nextBreed.setIcon(next);
}
});
nextBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(true);
}
});
nextBreed.setBounds(1140, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(nextBreed);
nextBreed.setRequestFocusEnabled(false);
nextBreed.setVisible(true);
nextBreed.setOpaque(false);
nextBreed.setContentAreaFilled(false);
nextBreed.setBorderPainted(false);
nextBreed.setFocusPainted(false);
//add breed window
JButton btnAdd = new JButton("Add new breed");
btnAdd.setBounds(780, 300, 400, 200);
btnAdd.setFont(new Font("Verdana", Font.PLAIN, 40));
btnAdd.setBorder(new LineBorder(Color.DARK_GRAY));
btnAdd.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnAdd.setBackground(Color.WHITE);
btnAdd.setRequestFocusEnabled(false);
btnAdd.setFocusPainted(false);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(addBreed);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnAdd.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnAdd.setBackground(Color.WHITE);
}
});
menu.add(btnAdd);
breedLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
breedLabels[i] = new JLabel(breedInfo[i]);
}
textLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
textLabels[i] = new JLabel(breedInfo[i]);
}
}
}
Is it possible to initialize for example JPanel outside Window class?"
Yes. A different class might contain a method that creates & returns a JPanel.
Other tips:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
new Font("Verdana", Font.PLAIN, 20) Use defaults or logical fonts (E.G. Font.SERIF) unless the font is supplied with your app. as an embedded resource.
The loop and array of labels that are added to viewBreed suggest it should be a JList rather than a JPanel
layeredPane.removeAll(); .. Ugh.. Use a CardLayout as shown in this answer.
What is the purpose of the JLayeredPane? I expect it's unnecessary purely on the basis that there is so little use for them.
Hi I'm making a game in Java that randomly generates 100 numbers, and then
ask the user to memorize as many as then can and then try to recall as many as they can. My game uses a JPanel and a Graphics g object to do all the drawing. How do I "draw" a JTextfield or get one to work on a jpanel?
Add a ActionListener to JTextField and then add that JTextField to JPanel. Now add this JPanel to JFrame using this.add(jpnel, BorderLayout.SOUTH);
Create a new JPanel class Board where you draw things. Add that JPanel to JFrame as, this.add(new Board(), BorderLayout.CENTER);.
Here I coded one example for you. Now you should have an idea how to do that...
Board class
public class Board extends JPanel {
int[] numbers = {3, 25, 5, 6, 60, 100};
int index = 0;
static String num;
boolean once = true;
FontMetrics fm;
Board() {
setPreferredSize(new Dimension(400, 200));
setBackground(Color.decode("#ffde00"));
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
if (index < 6) {
num = numbers[index] + "";
} else {
num = "Game Ended.";
Window.ans.setEditable(false);
}
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Arial", Font.PLAIN, 50));
if(once){
fm = g2.getFontMetrics();
once = false;
}
int x = ((getWidth() - fm.stringWidth(num)) / 2);
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g2.drawString(num + "", x, y);
index++;
}
}
Window class
public class Window extends JFrame {
JPanel p = new JPanel();
JLabel lbl = new JLabel("Enter the number if you have seen it before, Else empty.");
JLabel res = new JLabel("....");
static JTextField ans = new JTextField(10);
Board board = new Board();
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(board, BorderLayout.CENTER);
p.setLayout(new BorderLayout(8, 8));
p.add(lbl, BorderLayout.WEST);
ans.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (ans.getText().equals(Board.num)) {
res.setText("Good");
} else {
res.setText("Bad");
}
ans.setText("");
board.repaint();
}
});
p.add(ans, BorderLayout.CENTER);
p.add(res, BorderLayout.EAST);
p.setBorder(new EmptyBorder(10, 10, 10, 10));
this.add(p, BorderLayout.SOUTH);
setResizable(false);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
}
I am trying to make a flashing light in my jframe by creating a list of the colors and then cycling through them with a for loop and then repainting. but when I add a for loop to my code the whole thing bugs out and I get a black screen and it frezzes. Why is this happening?
public class bb {
static Color colors[] = {Color.ORANGE, Color.GRAY};
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(400, 525);
JPanel panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
JButton smallerButton = new JButton("Flash");
JButton largerButton = new JButton("Steady");
JPanel southPanel = new JPanel();
southPanel.add(smallerButton);
southPanel.add(largerButton);
frame.add(southPanel, BorderLayout.SOUTH);
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(180, 110, 10, 30);
g.drawRect(180, 140, 9, 30);
g.fillRect(180, 170, 10, 30);
g.drawRect(180, 200, 9, 30);
g.fillRect(180, 230, 10, 30);
g.drawRect(180, 260, 9, 30);
g.fillRect(180, 290, 10, 30);
g.drawRect(180, 310, 9, 30);
g.fillRect(180, 340, 10, 30);
int i = 0;
g.setColor(colors[i]);
for(i=0; i <= colors.length; i++){
g.fillOval(160, 70, 50, 50);
if (i ==colors.length){
i=0;
}
frame.repaint();
}
smallerButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if (action.equals("Flash")){
}
}
});
}
};
frame.add(panel);
frame.validate();
}
}
This statement resets your loop index to 0 causing it to loop indefinitely blocking the EDT
if (i == colors.length) {
i = 0;
}
since you exceed the last array index in the for statement.
Take a look at using a Swing Timer to achieve this functionality.
I am working on a little menu program with clickable buttons and an image that changes based on button clicks. If I click a button I get a shadow of the button at the bottom where I change the JLabel text. I cannot figure it out for the life of me. Any advice would be greatly appreciated. Visuals below...thanks
public class SampleGUI
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
System.out.println("Created GUI on EDT? " +
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Robert's VICI Prototype");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel
{
// Fields
Image imageDisplayed;
JLabel status;
// Methods
public MyPanel()
{
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setLayout(null);
JLabel title = new JLabel("CS380 TEAM 5 VICI Prototype");
title.setFont(new Font("Tahoma", Font.BOLD, 20));
title.setBounds(425, 10, 400, 40);
add(title);
status = new JLabel("Please click an option above.");
status.setFont(new Font("Tahoma", Font.BOLD, 14));
status.setBounds(425, 740, 400, 40);
add(status);
JButton choice1 = new JButton("Search Class");
choice1.setBounds(50, 50, 150, 40);
add(choice1);
JButton choice2 = new JButton("Add Class");
choice2.setBounds(225, 50, 150, 40);
add(choice2);
JButton choice3 = new JButton("Drop Class");
choice3.setBounds(400, 50, 150, 40);
add(choice3);
JButton choice4 = new JButton("Verify Reg Hold");
choice4.setBounds(575, 50, 150, 40);
add(choice4);
JButton choice5 = new JButton("Verify Reg Date");
choice5.setBounds(750, 50, 150, 40);
add(choice5);
JButton choice6 = new JButton("Schedule Advisor");
choice6.setBounds(925, 50, 150, 40);
add(choice6);
choice6.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Schedule Advisor button pressed.");
status.setText("Choose a date.");
imageDisplayed = new ImageIcon("C:\\Temp\\sa01.jpg").getImage();
}
});
JButton exit = new JButton("EXIT");
exit.setBounds(940, 750, 150, 40);
add(exit);
exit.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
imageDisplayed = new ImageIcon("C:\\Temp\\main.jpg").getImage();
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(1100, 800);
}
#Override
public void paintComponent(Graphics g)
{
g.drawImage(imageDisplayed, 100, 120, 900, 600, this);
}
}
You've broken the paint chain...
#Override
public void paintComponent(Graphics g)
{
g.drawImage(imageDisplayed, 100, 120, 900, 600, this);
}
The first thing you should be calling is super.paintComponent(g)
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(imageDisplayed, 100, 120, 900, 600, this);
}
The Graphics context is shared resource, meaning that the Graphics context you get has also been used to paint the other components that have also been painted. One of the jobs of paintComponent is to clear the Graphics context ready for the component to be painted (fill the background)
See Painting in AWT and Swing and Performing Custom Painting for more details
You should, also, avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify. See Why is it frowned upon to use a null layout in SWING? for more details...
Before you go all defensive over getting your screen laid out just nicely, you shouldn't be doing it this way. You controls should be laid out on separate containers (using appropriate layout managers) and you "drawing surface" should be it's own component. See Laying Out Components Within a Container for more details...
If you're still not convicned, take a look at Why setting setPreferredSize() on JFrame is bad? and java expandable JDialog for examples of differences between Mac and Windows
Thank you I finally got the button to work properly but now I'm stuck at making the shape I just create to stay on screen. Every time I click to create new shape I select the other shape I just create disappear. I look at custom paint but still confuse
public class ShapeStamps extends JFrame {
Random numGen = new Random();
public int x;
public int y;
private JPanel mousePanel, Bpanel;
private JButton circle, square, rectangle, oval;
private int choice = 0;
public ShapeStamps() {
super("Shape Stamps");
Bpanel = new JPanel();
circle = new JButton("Circle");
square = new JButton("Square");
rectangle = new JButton("Rectangle");
oval = new JButton("Oval");
circle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 1;
}
});
square.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 2;
}
});
rectangle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 3;
}
});
oval.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 4;
}
});
mousePanel = new JPanel();
mousePanel.setBackground(Color.WHITE);
MouseHandler handler = new MouseHandler();
setVisible(true);
addMouseListener(handler);
addMouseMotionListener(handler);
add(mousePanel);
Bpanel.add(circle);
Bpanel.add(square);
Bpanel.add(rectangle);
Bpanel.add(oval);
add(Bpanel, BorderLayout.SOUTH);
setSize(500, 500);
setVisible(true);
}
private class MouseHandler extends MouseAdapter implements
MouseMotionListener {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
}
public void paint(Graphics g) {
super.paintComponents(g);
setBounds(0, 0, 500, 500);
Graphics2D g2d = (Graphics2D) g;
if (choice == 0) {
g2d.setFont(new Font("Serif", Font.BOLD, 32));
g2d.drawString("Shape Stamper!", 150, 220);
g2d.setFont(new Font("Serif", Font.ITALIC, 16));
g2d.drawString("Programmed by: None", 150, 245);
}
if (choice == 1) {
Color randomColor1 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor1);
g2d.drawOval(x - 50, y - 50, 100, 100);
}
if (choice == 2) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.drawRect(x - 50, y - 50, 100, 100);
}
if (choice == 3) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.draw(new Rectangle2D.Double(x - 75, y - 50, 150, 100));
}
if (choice == 4) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.draw(new Ellipse2D.Double(x - 50, y - 25, 100, 50));
}
}
}
Everytime the JFrame gets repainted it will go through the drawing process, somif you stamp something on the screen you would have to have a data structure to hold the "objects" that were stamped. This way, each time the drawing process gets called it will repaint the objects on their correct position (and maybe colors with you decide to change this too)