i am new to swing in java. i am trying to add the drawing made by the paintComponent() method in my a frame through layeredPane but it is not showing in the JFrame
However if i place the code frame.getContentPane().add(drawing) and comment the Layered part the code works..
what i am doing wrong?
here is the code:
frame class
public class FrameTest extends JFrame {
static JFrame frame= new JFrame("Frame");
public static void main(String[] args) {
FrameTest test= new FrameTest ();
}
public FrameTest (){
this.openfrane();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void openframe(){
//window properties
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1000,600);
frame.setResizable(false);
//changing icon of window
ImageIcon image = new ImageIcon("assets/icon.png");
card.setIconImage(image.getImage());
//label picture background
JLabel background = new JLabel();
ImageIcon back = new ImageIcon("assets/background.jpg");
background.setIcon(back);
background.setLocation(0,-125);
background.setSize(1000,700);
//label for first
JLabel first = new JLabel("Sample text");
first.setForeground(Color.RED);
first.setSize(500,200);
first.setLocation(31, 150);
Draw drawing = new Draw();
JLayeredPane layers = new JLayeredPane();
layers.add(drawing, new Integer(3));
layers.add(first, new Integer(2));
layers.add(background,new Integer(1));
frame.setLayeredPane(layers);
}
}
draw class:
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
int startX = 00;
int startY = 00;
// First circle
Ellipse2D circle1 = new Ellipse2D.Double(startX, startY, 30, 30);
g2.setColor(Color.Black);
g2.draw(circle1);
g2.fill(circle1);
// Second circle
Ellipse2D circle2 = new Ellipse2D.Double(startX+20, startY, 30, 30);
g2.setColor(Color.Black);
g2.draw(circle2);
g2.fill(circle2);
}
}
i am trying to add the drawing made by the paintComponent() method in my a frame through layeredPane but it is not showing in the JFrame
Your DrawPanel does not have a size, so the size is (0, 0) and there is nothing to paint.
However if i place the code frame.getContentPane().add(drawing) and comment the Layered part the code works..
When you add the DrawPanel directly to the content pane then the panel is added to the "CENTER" and the panel size is automatically set to the space available in the frame by the layout manager.
Related
I did exactly according to the excellent guide but it does not work, I want to click a button that will change the background of the program. I would love to make the picture change
Code Guide https://stackhowto.com/how-to-set-background-image-in-java-swing/
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Display an image in the background");
final ImageIcon icon = new ImageIcon("background.png");
JTextArea text = new JTextArea()
{
Image img = icon.getImage();
// instance initializer
{setOpaque(false);}
public void paintComponent(Graphics graphics)
{
graphics.drawImage(img, 0, 0, this);
super.paintComponent(graphics);
}
};
JScrollPane pane = new JScrollPane(text);
Container content = frame.getContentPane();
content.add(pane, BorderLayout.CENTER);
frame.setDefaultCloseOperation(3);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
I can't draw a oval, I can't understand where I'm wrong. I have already done research but I have not found answers, sorry for the trouble.
This is my simple code:
public class Ball extends JPanel{
public void paint(Graphics g) {
g.drawOval(100, 100, 50, 50);
}
public static void main(String[] args) {
JFrame game = new JFrame("Ball game!");
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setResizable(false);
game.setLayout(null);
game.setSize(300, 550);
game.setLocation(400, 200);
Ball d = new Ball();
game.add(d);
game.setVisible(true);
}
}
The inner content of a JFrame is its contentpane. You can just set the frame's contentpane to the panel that you want to draw, with JFrame.setContentPane(). Then your panel will be shown.
public class Ball extends JPanel{
public void paint(Graphics g) {
g.drawOval(100, 100, 50, 50);
}
public static void main(String[] args) {
JFrame game = new JFrame("Ball game!");
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setResizable(false);
game.setLayout(null);
game.setSize(300, 550);
game.setLocation(400, 200);
Ball d = new Ball();
game.setContentPane(d); // <- this line
game.setVisible(true);
}
}
The size of the added panel is (0, 0) since you are not using a Layout Manager (game.setLayout(null)) neither setting its size.
In that case you must set the position and size of any added Component:
Ball d = new Ball();
d.setLocation(0,0);
d.setSize(300, 500);
or just use a Layout Manager, e.g. the default one - BorderLayout for JFrame - and the added panel will occupy the whole area:
game.setResizable(false);
// game.setLayout(null);
game.setSize(300, 550);
The program is to display 3 buttons on the JPanel. The program is compiled successfully. The GUI Window then appears and is empty. When I minimise the window and then maximise it again the Buttons appear. On doing this again another set of Buttons appear. The button keeps on appearing when the window is refreshed and the older data is kept intact.
JPanel Class
class MyJPanel extends JPanel {
JButton jb1, jb2, jb3;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
jb1 = new JButton();
jb2 = new JButton("Green");
jb3 = new JButton("Blue");
//g.drawString("Welcome!", 100, 100);
ImageIcon img = new ImageIcon("next.png");
jb1.setIcon(img);
jb1.setToolTipText("Button 1");
this.add(jb1);
this.add(jb2);
this.add(jb3);
}
}
JFrame Class
class MyJFrame extends JFrame {
MyJPanel mjp;
public MyJFrame(String title) {
super(title);
mjp = new MyJPanel();
Container ct = getContentPane();
ct.add(mjp);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Driver Class
class Gui5JButton {
public static void main(String[] args) {
MyJFrame mjf = new MyJFrame("Prakhar");
mjf.repaint();
}
}
paintComponent is called everytime your panel needs to be redraw, so everytime you minimize the window it will put the button again. If I understood what you want to do correctly, you need to remove the override and put this code :
jb1 = new JButton();
jb2 = new JButton("Green");
jb3 = new JButton("Blue");
//g.drawString("Welcome!", 100, 100);
ImageIcon img = new ImageIcon("next.png");
jb1.setIcon(img);
jb1.setToolTipText("Button 1");
this.add(jb1);
this.add(jb2);
this.add(jb3);
in the constructor of your MyJPanel class.
New to Java and very new to Java's GUI classes. I'm making a GUI to showcase a few games, but am having difficulties switching panels. I read about CardLayout but I'm having an issue implementing it because I can't get the JPanels that hold the different games' GUIs to send their events back to the class that uses the CardLayout. (This is probably where I'm going wrong -- I can't get my head around how to structure this properly.)
This is my main menu (called mainContainer):
This is the overall structure of the GUI driver:
public class CasinoDriverGUI {
//CardLayout is here in the main method Container contentPane.add(cardLayout)
public static void main(String[] args) throws IOException
//MainContainer is MenuScreen: GridBagLayout for nice button placement
static class MainContainer extends JPanel implements ActionListener{...}
static class CrapsContainer extends JPanel implements ActionListener{...}
static class PokerContainer extends JPanel implements ActionListener{...}
//Button with custom look
class CButton extends JButton
}//end CasinoDriverGUI
Here is the main method: It grabs an image from a website and then adds the menu screen (mainContainer) to the contentPane. The menu screen uses GridBagLayout, but it's where the button components are added. Because of this, I can't figure out how to get the CardLayout of the contentPane to listen to the menu screen's buttons. I tried using ContainerListener but that seemed to be a dead end.
public class CasinoDriverGUI {
public static void main(String[] args) throws IOException {
// load the texture resource image
System.out.println("Please wait, Loading Texture : http://www.pngall.com/wp-content/uploads/2016/04/Casino-PNG-Pic.png");
MainContainer.textureImg = ImageIO.read(new URL("http://www.pngall.com/wp-content/uploads/2016/04/Casino-PNG-Pic.png"));
System.out.println("Loading finished. Starting the Casino!");
MainContainer.textureImg = MainContainer.textureImg.getSubimage(0, 0, 580, 309);
// Starting the Swing GUI in the EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final CardLayout cardLayout = new CardLayout();
JFrame frame = new JFrame("Midnight Casino");
// frame about the size of background src image
frame.setPreferredSize(new Dimension(580, 329));
final Container contentPane = frame.getContentPane();
contentPane.setLayout(cardLayout);
MainContainer mainContainer = new MainContainer();
mainContainer.setPreferredSize( frame.getPreferredSize() );
contentPane.add(mainContainer, "mainContainer");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
As I have it so far, I have just tried using the "menu screen" (mainContainer) to instantiate all the games' panels and use an ActionListener on some buttons to simply call thisGame.setVisible(true). but this is forcing the window to be minimized and re-opened for any change to be detectable.Edit: fixed this.
Any advice on how I can restructure this code to be able to switch the panels from the menu screen to the different game's panels? (Code is below, but the craps and poker GUIs are incomplete.. just using the code as placeholders.
public class CasinoDriverGUI {
public static void main(String[] args) throws IOException {
// load the texture resource image
System.out.println("Please wait, Loading Texture : http://www.pngall.com/wp-content/uploads/2016/04/Casino-PNG-Pic.png");
MainContainer.textureImg = ImageIO.read(new URL("http://www.pngall.com/wp-content/uploads/2016/04/Casino-PNG-Pic.png"));
System.out.println("Loading finished. Starting the Casino!");
MainContainer.textureImg = MainContainer.textureImg.getSubimage(0, 0, 580, 309);
// Starting the Swing GUI in the EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final CardLayout cardLayout = new CardLayout();
JFrame frame = new JFrame("Midnight Casino");
// frame about the size of background src image
frame.setPreferredSize(new Dimension(580, 329));
final Container contentPane = frame.getContentPane();
contentPane.setLayout(cardLayout);
MainContainer mainContainer = new MainContainer();
mainContainer.setPreferredSize( frame.getPreferredSize() );
contentPane.add(mainContainer, "mainContainer");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
static class MainContainer extends JPanel implements ActionListener
{
public BufferedImage gradientImage = null;
public static BufferedImage textureImg; // static for ease
public static boolean loadingFinished = false;
protected JButton pokerJBtn;
protected JButton crapsJBtn;
CrapsContainer crapsContainer;
PokerContainer pokerContainer;
public MainContainer() {
setBorder(new EmptyBorder(50, 50, 50, 50)); // setting the insets
setLayout(new GridBagLayout());
// working with GridBagConstraints
GridBagConstraints labCnst = new GridBagConstraints();
GridBagConstraints txtCnst = new GridBagConstraints();
labCnst.ipady = txtCnst.ipady = 10;
labCnst.fill = GridBagConstraints.HORIZONTAL;
labCnst.gridwidth = 1;
labCnst.weightx = 0.3;
labCnst.gridx = 2;
labCnst.gridy = 2;
labCnst.ipady = 13;
labCnst.insets = new Insets(0, 0, 0, 150);
pokerJBtn = new CButton("5-Card Poker");
add(pokerJBtn, labCnst);
labCnst.gridx = 2;
labCnst.gridy = 20;
labCnst.ipady = 13;
labCnst.insets = new Insets(0, 0, 0, 150);
crapsJBtn = new CButton("Craps");
add(crapsJBtn, labCnst);
crapsContainer = new CrapsContainer();
pokerContainer = new PokerContainer();
add(crapsContainer);
add(pokerContainer);
crapsContainer.setVisible(false);
pokerContainer.setVisible(false);
//Add Action Listeners
crapsJBtn.addActionListener(this);
pokerJBtn.addActionListener(this);
}
public void changeCompFont(JComponent comp)
{
comp.setForeground(Color.WHITE);
comp.setFont(getFont().deriveFont(Font.BOLD, 13));
}
// To PAINT THE TEXTURE ABOVE THE COMPONENTS
#Override
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D)g.create(); // cloning
Rectangle2D txRect = new Rectangle2D.Double(0, 0, textureImg.getWidth(), textureImg.getHeight());
TexturePaint txPaint = new TexturePaint(textureImg, txRect);
g2d.setPaint(txPaint);
//make the texture transparent
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.233f));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();// disposing the graphics object
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if(gradientImage==null || gradientImage.getHeight() != getHeight() )
{
gradientImage = createGradientImg();
}
g2d.drawImage(gradientImage, 0, 0, getWidth(), getHeight(), this);
g2d.dispose();
}
public BufferedImage createGradientImg()
{
BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
// background gradient paint, linear gradient paint for the background
// Gradient paint rendering could be made more optimized
LinearGradientPaint lgrPaint = new LinearGradientPaint(0.0f, 0.0f, getWidth(), getHeight(),
new float[] { 0.0f, 0.5f, 0.6f, 1.0f },
new Color[] { new Color(0x0530E),// new Color[] { new Color(0x002AFF),
new Color(0x0A31B),
new Color(0x0A31B),
new Color(0x0530E ) });
Graphics2D g2d = (Graphics2D) image.getGraphics();
g2d.setPaint(lgrPaint);
//g2d.shear(0.2, 0);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
g2d.drawImage(textureImg, 0, 0, getWidth(), getHeight(), null);
return image;
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == pokerJBtn)
{
pokerContainer.setVisible(true);
}
else if (e.getSource() == crapsJBtn){
this.setVisible(false);
invalidate();
crapsContainer.setVisible(true);
revalidate();
repaint();
}
}
}
//Either Flow, Border, or GridBag Layout
static class CrapsContainer extends JPanel implements ActionListener
{...}
//Either Flow, Border, or GridBag Layout
static class PokerContainer extends JPanel implements ActionListener
{...}
//Custom Button to change aesthetic look
class CButton extends JButton
{...}
}
as said my rectangle does not center vertically in a JPanel with GridLayout. I have 3 columns. 1st and 2nd column have JLabels and they are centered perfect, but my custom JPanel which is just a rectangle does not. It's y coordinate is always on top of the grid's row.
public class CustomJPanel {
/**
* #param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 200);
frame.setResizable(false);
JPanel panel = new JPanel(new GridLayout(0,3));
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setBounds(10, 50, 320, 200);
scrollPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
for(int i=0; i<3; i++){
JLabel nameLabel = new JLabel("Test"+i);
JLabel timeLabel = new JLabel();
timeLabel.setText("0h 0m 0s");
panel.add(nameLabel);
panel.add(timeLabel);
panel.add(new Bar());
}
frame.add(scrollPane);
frame.setVisible(true);
}
private static class Bar extends JPanel {
int width = 100;
Dimension maxDimension = new Dimension(100, 20);
#Override
public void paintComponent(Graphics g){
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.fillRect(0, 0, width, 5);
}
#Override
public Dimension getMaximumSize() {
return maxDimension;
}
#Override
public Dimension getPreferredSize(){
return this.getMaximumSize();
}
}
}
Do I have to add other methods to my Bar class?
Thank you :)
That happens because you draw rectangle from y=0, but you need to draw that at the middle of your panel. You can fill rectanle in the middle like next :
g2.fillRect(0, getSize().height/2, width, 5);