Gui does not paint the panel - java

hi guys i have wird problem i have here my GUI class is working good at begining just by showing loggin screen. but i have second class called DataLayer that is responsible for reading from files and creating objets with infromaton.
the problem is that when i try to create new DataLayer() in GUI class the panel doesn show until i resize screen and even after that the keylistener doesn't work.
`package View;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import dto.DataLayer;
import dto.ProductDTO;
public class GUI extends JPanel {
private DataLayer dt;
private ComponentAbstract korzen;
private GUI self;
public GUI() {
this.setFocusable(true);
this.dt=new DataLayer();`
self=this;
this.stworz_PanelLogowania();
this.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
korzen.tryPressKey(e);
repaint();
}
});
this.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
korzen.tryClick(e.getX(), e.getY());
repaint();
}
});
this.repaint();
}
#Override
protected void paintComponent(Graphics g ) {
super.paintComponent(g);
korzen.repaint();
System.out.println("omatko");
korzen.draw((Graphics2D)g);
}
private void zmien_panel(ComponentAbstract newkorzen){
korzen=newkorzen;
self.repaint();
}
private void stworz_PanelLogowania(){
LinearPanel lp=new LinearPanel(220, 10, 300, 300);
lp.setOrientarion(Orientation.VERTICAL);
LinearPanel labels_panel=new LinearPanel(220,0,50,80);
labels_panel.setOrientarion(Orientation.VERTICAL);
labels_panel.addComponent(new Label(0, 0, 350, 40, "Witamy w castorama APP"));
lp.setPadding(6);
LinearPanel textpanel1=new LinearPanel(0, 0, 350, 80);
textpanel1.setPadding(0);
textpanel1.addComponent(new Label(0,0,350,40,"Login:"));
textpanel1.addComponent(new TextBox(0, 0, 350, 40));
LinearPanel textpanel2=new LinearPanel(0, 0, 35, 80);
textpanel2.setPadding(0);
textpanel2.addComponent(new Label(0,0,350,40,"Hasło:"));
textpanel2.addComponent(new TextBox(0, 0, 350, 40));
lp.addComponent(labels_panel);
lp.addComponent(textpanel1);
lp.addComponent(textpanel2);
LinearPanel buttons_panel=new LinearPanel(00, 00, 350, 40);
buttons_panel.setOrientarion(Orientation.HORIZONTAL);
buttons_panel.addComponent(new Button(170,40,"Zaloguj"){
#Override
public void onClick() {
TextBox tlogin=(TextBox)korzen.getComponent(1).getComponent(1);
TextBox tpass=(TextBox)korzen.getComponent(2).getComponent(1);
if(dt.autoryzacja_uzytkownika(tlogin.getText(), tpass.getText())){
System.out.println("Puszczamy typa");
}
}
});
buttons_panel.addComponent(new Button(170,40,"Wyjdz"){
#Override
public void onClick() {
System.exit(0);
}
});
lp.addComponent(buttons_panel);
korzen=lp;
System.out.println("kuniec");
}
private void stworz_panelGlowny(){
LinearPanel glowny=new LinearPanel(220,0,50,80);
}
}

the problem is that when i try to create new DataLayer() in GUI class the panel doesn show until i resize screen
When you add (or remove) components from a visible GUI the basic code is:
panel.add(...);
panel.revalidate(); // to invoke the layout manager
panel.repaint(); // to paint the components.
even after that the keylistener doesn't work.
Probably because some other component has focus and KeyEvents area only dispatched to the component with focus. Try using the requestFocusInWindow() method on the panel.
panel.requestFocus

Related

rendering an Image to a JPanel

I am currently trying to render an Image to a JPanel. Here is my Code:
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ScreenSaver extends JPanel {
private static final long serialVersionUID = 001;
public static void main(String[] args) {
new ScreenSaver();
}
public ScreenSaver() {
new Window(1600, 900, "ScreenSaver", this);
}
public Image ball;
public void initCode() {
try {
File pathToBall = new File("ball.png");
ball = ImageIO.read(pathToBall);
} catch (IOException ex) {
ex.printStackTrace();
}
renderImage()
}
public void renderImage(Graphics g) {
g.drawImage(ball, 0, 0, 100, 100, null);
}
}
The "initCode()" method gets called after the JFrame has loaded. My problem now is that I want to call the "renderImage()" method. In the parameters I have to put "Graphics g" to use the "g.drawImage" function. Sadly I now dont know what to put in the brackets when I want to call "renderImage()". Can someone help?
The painting of pictures and graphic elements works a little differently than in your question.
Here is a working example:
import java.awt.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
public class PaintExample extends JFrame{
private BufferedImage ball;
public static void main(String[] args) {
new PaintExample();
}
public PaintExample(){
initCode();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(1600, 900));
setMinimumSize(new Dimension(800, 600));
add(new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(ball, 0, 0, 100, 100, this);
}
});
pack();
setLocationRelativeTo(null);
setTitle("Paint Example");
setVisible(true);
}
public void initCode() {
try {
File pathToBall = new File("ball.png");
ball = ImageIO.read(pathToBall);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I hope this solves your problem.
Swing is event driven, this means that you never directly call painting methods.
Basics for a custom painting component:
extends JComponent
override paintComponent(Graphics g), this is the point where you can put your rendering code
override getPreferredSize(), so that the layout managers can do their duty, a suitable value is your image size
In addition I don't understand this line:
new Window(1600, 900, "ScreenSaver", this);

Java Graphics Only Paint on Button Click

I'm not sure how java graphics work. It seems
to be executing something itself so I am trying to break it
down.
I'm trying to create the blank JPanel and then only draw to it
once the JButton has been clicked but it doesn't work
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
public class testGui {
// global ======================================================================
static gui gc_gui;
// main ========================================================================
public static void main(String[] args) {
gc_gui = new gui();
gc_gui.cv_frame.setVisible(true);
listeners();
}
// action listeners ============================================================
public static void listeners() {
ActionListener ll_square = new ActionListener() {
public void actionPerformed(ActionEvent event) {
gc_gui.cv_content.draw(graphic);
}
};
gc_gui.cv_button.addActionListener(ll_square);
}
// gui =========================================================================
public static class gui {
JFrame cv_frame;
JButton cv_button;
content cv_content;
public gui() {
cv_frame = new JFrame();
cv_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cv_frame.setTitle("Test GUI");
cv_frame.setSize(600, 400);
cv_frame.setLayout(new FlowLayout());
cv_button = new JButton("Square");
cv_content = new content();
cv_content.setBackground(Color.BLACK);
cv_content.setPreferredSize(new Dimension(500, 300));
cv_frame.add(cv_button);
cv_frame.add(cv_content);
}
}
// content =====================================================================
public static class content extends JPanel {
public void paint(Graphics graphic) {
super.paint(graphic);
}
public void update() {
super.repaint();
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
graphic2D.setPaint(Color.RED);
graphic2D.fillRect(10, 10, 100, 100);
}
}
}
I create the content JPanel without the draw function being
called and then I try to call it using my ActionListener
although it is crashing because of the graphic variable.
What is the correct way to use the java graphics utility?
UPDATE
Maybe I'm not asking this question right but it is possible to
create a blank image.
Then draw additional images to that images (squares) after a button
has been clicked?
not just updating the dimensions using global variables but generating
new images to that existing image
but it is possible to create a blank image. Then draw additional images to that images (squares) after a button has been clicked?
Check out Custom Painting Approaches for two common ways to do painting.
The example allows you to draws Rectangles with the mouse. In your case the logic will be simpler as you would just invoke the addRectangle(...) method when you click a button. Of course you need to set the size/location of the Rectangle somehow.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class TestGui {
public static Content content;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test GUI");
frame.setSize(429, 385);
frame.getContentPane().setLayout(null);
JButton cv_button = new JButton("Square");
cv_button.setBounds(10, 159, 70, 23);
frame.getContentPane().add(cv_button);
cv_button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Content.isToDraw = true;
content.paintImmediately(content.getBounds());
Content.isToDraw = false;
}
});
JButton cv_buttonClear = new JButton("Clear");
cv_buttonClear.setBounds(10, 179, 70, 23);
frame.getContentPane().add(cv_buttonClear);
cv_buttonClear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
content.paintImmediately(content.getBounds());
}
});
content = new Content();
content.setBorder(new LineBorder(new Color(0, 0, 0)));
content.setBounds(87, 11, 287, 312);
frame.getContentPane().add(content);
frame.setVisible(true);
}
}
class Content extends JPanel {
public static Boolean isToDraw = false;
public void paintComponent(Graphics arg0) {
if (isToDraw) {
arg0.setColor(Color.RED);
arg0.fillRect(0, 0, getWidth(), getHeight());
} else {
super.paintComponent(arg0);
}
}
}

Calling repaint() draws the new shape, but leaves the old shape there

I'm sure this is a simple answer, but I can't figure it out.
I am trying to make a basic shape that I can control in a window. Obviously it will be more involved when the whole project is complete, but I am working on the early steps still. I am using WindowBuilder to make the layout, and have a JPanel and a JButton. The JPanel draws a rectangle, and has a method to move it. The JButton calles that moving command. And that's it. The problem is in the repaint. The shape keeps all old versions of itself, and the button makes weird copies of itself. All these go away when I resize the window, which I thought was the same as calling repaint. Again, I'm sure is something simple I am missing. Below are my 2 classes.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Drawing {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Drawing window = new Drawing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Drawing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
drawpanel panel = new drawpanel();
panel.setBounds(58, 68, 318, 182);
frame.getContentPane().add(panel);
JButton btnMove = new JButton("move");
btnMove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.moves();
}
});
btnMove.setBounds(169, 34, 89, 23);
frame.getContentPane().add(btnMove);
}
}
^ This one, besides the buttonListener, was autocreated by WindowBuilder.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class drawpanel extends JPanel {
int x = 50, y = 50;
int sizeX = 50, sizeY = 50;
public void paintComponent( Graphics g) {
super.paintComponents(g);
g.setColor(Color.BLACK);
g.drawRect(x, y, sizeX, sizeY);
}
public void moves() {
x +=5;
repaint();
}
}
^ This one has my drawing of the shape and the moving/repainting method. It was written mostly from other examples I found on this site.
Thanks to any help in advanced.
public void paintComponent(Graphics g) {
super.paintComponents(g); // wrong method! (Should not be PLURAL)
Should be:
public void paintComponent(Graphics g) {
super.paintComponent(g); // correct method!

KeyPressed Not Working

I am trying to move an image up and down by using arrow keys.I have used ASCII values to check which key is pressed, but the handler for keyPressed is not getting called. I checked by applying a breakpoint but nothing happens.
package com.google.play;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class ShootingBubble extends JPanel implements ActionListener,KeyListener {
int y=250;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GRAY);
g.drawRect(0, 200, 300, 400);
g.fillRect(0, 200, 300, 400);
g.setColor(Color.GRAY);
g.drawRect(800, 200, 300, 400);
g.fillRect(800, 200, 300, 400);
g.setColor(Color.BLACK);
g.drawLine(1000,200, 350, 200);
g.setColor(Color.BLACK);
g.drawOval(295, 190, 20, 20);
g.fillOval(295, 190, 20, 20);
g.setColor(Color.BLACK);
g.drawLine(0,190, 300, 190);
g.setColor(Color.BLACK);
g.drawLine(310,190, 310, y);
ImageIcon ic=new ImageIcon("C:\\Users\\acer\\Desktop\\mario.gif");
ic.paintIcon(this, g, 295, y);//moving image with help of y variable
ic.paintIcon(this, g, 0, 150);
ic.paintIcon(this, g, 40, 150);
ic.paintIcon(this, g, 80, 150);
ic.paintIcon(this, g, 120, 150);
ImageIcon ic1=new ImageIcon("C:\\Users\\acer\\Desktop\\index.jpg");
ic1.paintIcon(this, g, 320, 130);
}
public ShootingBubble() {
setBackground(Color.WHITE);
setFocusTraversalKeysEnabled(false);
}
void init(){
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("c");
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("d");
}
public static void main(String[] args) {
ShootingBubble st=new ShootingBubble();
JFrame jf=new JFrame();
jf.setSize(1000, 600);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().add(st);
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
#Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode()==38){
y-=2;//updating image position in vertically upward direction
}
if(arg0.getKeyCode()==40)
{
y=y+2;//updating image position in vertically downward direction
}
System.out.println("Key Pressed "+arg0.getKeyCode()+ " "+arg0.getKeyChar());
repaint();;
}
}
Several problems, not all related to the KeyListener:
Don't do I/O in the paintComponent() method. The painting methods are for painting only. Swing will determine when the component needs to be repainted and you don't want to continually read the image over and over. Read the image in your constructor.
All components should be added to the frame BEFORE the frame.setVisible(...) method is invoked. This will make sure the layout manager is invoked on all components.
Don't use "magic numbers". I have no idea what "38" and "40" are. How do you even know what they are? If you copied that code from a tutorial then dump the tutorial! Instead you should use KeyEvent.VK_???
Even if you add the KeyListener to the frame, the code probably won't work, because KeyEvents are only dispatched to the component with focus and I don't know the frame will always have focus. Really the panel should have focus since it is the component doing the painting.
Don't use a KeyListener. Swing was designed to by used with Key Bindings. See Motion With the Keyboard for more information and examples.
You have to register the keylistener.
add jf.addKeyListener(this); to your main method.

Custom Jtable scrollbar

I am making a Swing based desktop application.
I would like to customize the scrollbar in a jtable. I have gotten the below code to customize the scroll bar but i am not sure how to apply it to a jtable.
public class MyScrollBarUI extends BasicScrollBarUI {
#Override
protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
g.setColor(Color.black);
g.fillRect(trackBounds.width / 2, trackBounds.y, 3, trackBounds.height);
if (this.trackHighlight == BasicScrollBarUI.DECREASE_HIGHLIGHT) {
this.paintDecreaseHighlight(g);
} else if (this.trackHighlight == BasicScrollBarUI.INCREASE_HIGHLIGHT) {
this.paintIncreaseHighlight(g);
}
}
#Override
protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
if (thumbBounds.isEmpty() || !this.scrollbar.isEnabled()) {
return;
}
g.translate(thumbBounds.x, thumbBounds.y);
g.setColor(this.thumbDarkShadowColor);
g.drawOval(2, 0, 14, 14);
g.setColor(this.thumbColor);
g.fillOval(2, 0, 14, 14);
g.setColor(this.thumbHighlightColor);
g.setColor(this.thumbLightShadowColor);
g.translate(-thumbBounds.x, -thumbBounds.y);
}
}
And i do the following to set the scrollbars look and feel at the start of my program
UIManager.put("ScrollBarUI", "mypackage.ui.customization.MyScrollBarUI");
If you do this on specific scrollbar of your UI, then simply set a new instance of your ScrollBarUI directly on the scrollpane wrapping your table.
The following shows you how you can do this:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicScrollBarUI;
import javax.swing.table.DefaultTableModel;
public class MyScrollBarUI extends BasicScrollBarUI {
protected static void initUI() {
JFrame frame = new JFrame("Test scrollbar UI");
JTable table = new JTable(new DefaultTableModel(30, 5));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getVerticalScrollBar().setUI(new MyScrollBarUI());
frame.add(scrollPane);
frame.pack();
frame.setSize(frame.getWidth(), frame.getHeight()-50); // Forces the vertical scroll bar to show up
frame.setVisible(true);
}
#Override
protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
g.setColor(Color.black);
g.fillRect(trackBounds.width / 2, trackBounds.y, 3, trackBounds.height);
if (this.trackHighlight == BasicScrollBarUI.DECREASE_HIGHLIGHT) {
this.paintDecreaseHighlight(g);
} else if (this.trackHighlight == BasicScrollBarUI.INCREASE_HIGHLIGHT) {
this.paintIncreaseHighlight(g);
}
}
#Override
protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
if (thumbBounds.isEmpty() || !this.scrollbar.isEnabled()) {
return;
}
g.translate(thumbBounds.x, thumbBounds.y);
g.setColor(this.thumbDarkShadowColor);
g.drawOval(2, 0, 14, 14);
g.setColor(this.thumbColor);
g.fillOval(2, 0, 14, 14);
g.setColor(this.thumbHighlightColor);
g.setColor(this.thumbLightShadowColor);
g.translate(-thumbBounds.x, -thumbBounds.y);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initUI();
};
});
}
}

Categories

Resources