I want to make a background image for a game I'm designing but I cant figure out the right way to get the effect I want, I want a background that can be seen behind text etc. basically having the background cover the whole JFrame / JPanel not just one section of the layout (e.g. BorderLayout.Center) I think it does this anyway but if it does do that how do I make the background for those transparent to see the background which is behind...
Confusing i know but I hope someone here understands what I am trying to do and can help... this is my current code. I have been playing around with the background so dont read to much in how i have written it.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class GamePanel extends JPanel {
private JTextPane playertext;
private JTextField wealthstring, currentwealth;
public GamePanel() {
super();
setLayout(new BorderLayout());
setBackground(Game.getBackgroundColor());
Border raised = BorderFactory.createRaisedBevelBorder();
Border lowered = BorderFactory.createLoweredBevelBorder();
setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(4, 4, 4, 4), (BorderFactory.createCompoundBorder(raised, lowered))));
add(northpanel(), BorderLayout.NORTH);
add(eastpanel(), BorderLayout.EAST);
}
private JLabel northpanel() {
Font northfont = new Font("Engravers MT", Font.BOLD, 12);
ImageIcon banner = new ImageIcon("images/banner.png", "North Background");
playertext = new JTextPane();
playertext.setFont(northfont);
playertext.setEditable(false);
playertext.setText("Player: \n" + Game.getName());
playertext.setBackground(Game.getBackgroundColor());
playertext.setBorder(new EmptyBorder(10,10,10,10));
wealthstring = new JTextField("Money: ");
wealthstring.setFont(northfont);
wealthstring.setEditable(false);
wealthstring.setHorizontalAlignment(wealthstring.RIGHT);
wealthstring.setBorder(null);
wealthstring.setBackground(Game.getBackgroundColor());
currentwealth = new JTextField();
currentwealth.setFont(northfont);
currentwealth.setEditable(false);
currentwealth.setHorizontalAlignment(wealthstring.RIGHT);
currentwealth.setBackground(Game.getBackgroundColor());
currentwealth.setBorder(null);
String wealthrounded = String.format("%.2f", Game.getMoney());
currentwealth.setText(wealthrounded);
JPanel wealthtext = new JPanel();
wealthtext.setLayout(new GridLayout(2, 1));
wealthtext.setBackground(Game.getBackgroundColor());
wealthtext.setBorder(new EmptyBorder(10,10,10,10));
wealthtext.add(wealthstring);
wealthtext.add(currentwealth);
JLabel northpanel = new JLabel();
northpanel.setLayout(new BorderLayout());
northpanel.setIcon(banner);
northpanel.add(new JSeparator(), BorderLayout.PAGE_END);
northpanel.add(playertext, BorderLayout.WEST);
northpanel.add(wealthtext, BorderLayout.EAST);
return northpanel;
}
private JPanel eastpanel() {
JButton tab1 = new JButton("Tab 1");
JButton tab2 = new JButton("Tab 2");
JButton tab3 = new JButton("Tab 3");
JPanel easttabs = new JPanel();
easttabs.setLayout(new GridLayout(1, 3));
easttabs.add(tab1);
easttabs.add(tab2);
easttabs.add(tab3);
JPanel eastpanels = new JPanel();
eastpanels.setLayout(new BorderLayout());
eastpanels.setBackground(Game.getBackgroundColor());
eastpanels.add(easttabs, BorderLayout.NORTH);
return eastpanels;
}
}
So if you already have a JPanel that has your image as Background and you want to add another panel over it with your components you can use Opacity to achieve this. Only the components added to this panel will be visible. Here's the code :
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class TransparentPane extends JPanel {
public TransparentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0f));
g2d.setColor(getBackground());
g2d.fill(getBounds());
g2d.dispose();
}
}
Create a class that extends from JPanel and in its paint method draw an image over it.
Now create a class the extends from JFrame and in its constructor set its contentpane to the object of that JPanel class like below. Now you can add components to jframe.
class SimpleTest extends JFrame {
JButton btn = new JButton("A Game");
public SimpleTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new CPane());
getContentPane().setBackground(Color.red);
getContentPane().add(btn, BorderLayout.NORTH);
setSize(new Dimension(300, 300));
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleTest();
}
});
}
}
class CPane extends JPanel {
Image back;
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
back = ImageIO.read(getClass().getResource("back.jpg"));
} catch (Exception ex) {
}
g.drawImage(back, 0, 0, this);
}
}
If you want to make a jpanel transparent then do
panel.setOpaque(false);
Related
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import reactiontimer.ReactionTimer;
class MyPanel1 extends JPanel
{
boolean showEllipse;
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.red);
g2.drawOval(0, 0, 36, 36);
}
}
public class DrawOval extends JFrame implements ActionListener
{
Boolean flag1=false;
Boolean flag2=false;
Boolean flag3=false;
JButton name;
JButton oval;
JButton rectangle;
JPanel centerPanel;
MyPanel1 leftPanel;
JPanel rightPanel;
JLabel centerLabel;
JPanel botPanel;
JLabel label1;
JLabel label2;
JLabel label3;
public static void main(String args[])
{
// [Add Your Name and section number Below]
Gui rt = new Gui("Chengjie Lin, Section 012");
rt.setVisible(true);
}
public DrawOval(String title)
{
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
this.setVisible(true);
Font buttonFont = new Font(Font.SANS_SERIF, Font.BOLD, 24);
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());
botPanel=new JPanel();
name = new JButton("Name");
name.setFont(buttonFont);
botPanel.add(name);
//
oval = new JButton("Oval");
oval.setFont(buttonFont);
botPanel.add(oval);
//
rectangle = new JButton("Rectangle");
rectangle.setFont(buttonFont);
botPanel.add(rectangle);
contentPane.add(botPanel, BorderLayout.SOUTH);
Font bigLabelFont = new Font(Font.SANS_SERIF, Font.BOLD, 48);
label1=new JLabel("1");
label1.setFont(bigLabelFont);
label1.setHorizontalAlignment(SwingConstants.CENTER);
label2=new JLabel("2");
label2.setFont(bigLabelFont);
label2.setHorizontalAlignment(SwingConstants.CENTER);
label3=new JLabel("3");
label3.setFont(bigLabelFont);
label3.setHorizontalAlignment(SwingConstants.CENTER);
centerPanel = new JPanel();
leftPanel=new MyPanel1();
rightPanel=new JPanel();
leftPanel.setLayout(new BorderLayout());
rightPanel.setLayout(new BorderLayout());
centerPanel.setLayout(new BorderLayout());
// centerPanel.add(label1, BorderLayout.EAST);
centerPanel.add(label2, BorderLayout.CENTER);
// centerPanel.add(label3, BorderLayout.WEST);
contentPane.add(leftPanel, BorderLayout.EAST);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(rightPanel, BorderLayout.WEST);
name.addActionListener(this);
oval.addActionListener(this);
rectangle.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
String command = e.getActionCommand();
System.out.println(command);
// [Add Menu Code 3]
if (source == name)
{
updateView1();
}
if (source == oval)
{
updateView2();
}
if(source==rectangle){
}
}
void updateView1()
{
// [ADD Center Panel Code 2]
if(flag2==false){
label2.setText("cj");
}else{
label2.setText(null);
}
flag2=!flag2;
repaint();
}
void updateView2()
{
// [ADD Center Panel Code 2]
//leftPanel.add(label1);
if(flag1==false){
}else{
//leftPanel.removeAll();
}
flag1=!flag1;
leftPanel.repaint();
}
}
I am new to the Java.This might be a stupid question to ask.I tried to draw an oval in the leftPanel when the oval button is clicked. But nothing happened when I clicked the Button. Can someone help me out plz?
Your MyPanel1 panel has a size of (0, 0) so there is nothing to paint.
Override the getPreferredSize() method of the class to return the Dimension of your custom painting.
Read the section from the Swing tutorial on Custom Painting for more information and a working example.
I've made a GUI using swing with a BorderLayout and GridLayout in the center. I want to add a triangle I've made in another class to the JPanel east in my BorderLayout but cant get it to show.
When I set a bgcolor for said JPanel I got a weird little result, if you like you can have a look at the code: gistlink
I have a feeling the issue is in the TriGoButton constructor but I'm not sure how to test further. I've tried different variations of paint() but have never been able to see the green triangle.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#SuppressWarnings("serial")
public class TestGUI extends JFrame implements ActionListener {
private JPanel content;
private JTextField placeTxtField;
public static void main(String[] args) {
TestGUI frame = new TestGUI();
frame.pack();
frame.setVisible(true);
}
#SuppressWarnings("rawtypes")
public TestGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
content = new JPanel();
content.setLayout(new BorderLayout());
setContentPane(content);
// issue
JPanel rightPanel = new JPanel();
content.add(rightPanel, BorderLayout.EAST);
rightPanel.add(new TriGoButton());
// issue?
JPanel leftPanel = new JPanel();
content.add(leftPanel, BorderLayout.WEST);
JPanel centerPanel = new JPanel();
content.add(centerPanel, BorderLayout.CENTER);
centerPanel.setLayout(new GridLayout(3, 3, 0, 20));
JLabel countyLbl = new JLabel("County");
centerPanel.add(countyLbl);
JComboBox countyDropDown = new JComboBox();
centerPanel.add(countyDropDown);
JLabel muniLbl = new JLabel("Munipalicity");
centerPanel.add(muniLbl);
JComboBox muniDropDown = new JComboBox();
centerPanel.add(muniDropDown);
JLabel placeLbl = new JLabel("City or place");
placeLbl.setToolTipText("search");
centerPanel.add(placeLbl);
placeTxtField = new JTextField();
centerPanel.add(placeTxtField);
placeTxtField.setColumns(15);
placeTxtField.setToolTipText("enter w/e");
JPanel bottomPanel = new JPanel();
content.add(bottomPanel, BorderLayout.SOUTH);
JButton goBtn = new JButton("Clicky");
bottomPanel.add(goBtn);
goBtn.setToolTipText("Please click.");
goBtn.addActionListener(this);
JPanel topPanel = new JPanel();
content.add(topPanel, BorderLayout.NORTH);
JLabel headlineLbl = new JLabel("headline");
topPanel.add(headlineLbl);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class TriGoButton extends JPanel {
public TriGoButton() {
add(new JPanel(), BorderLayout.EAST);
setBackground(new Color(100,100,250)); //blue //wtf
}
public void paint(Graphics g) {
super.paint(g);
int[]x={90,90,300};
int[]y={150,0,90};
g.setColor(new Color(23,201,10)); //green
g.fillPolygon(x,y,3);
}
}
EDIT:
////////////
I don't know why you are adding a JPanel to your TriGoButton class, but this is going to cause you issues.
It's not recommended that you override paint, this can cause no end of issues, as the parent container isn't always included in updates when it's children are painted. See Painting in AWT and Swing and Performing Custom Painting for more details.
BorderLayout will use the component's preferredSize tomake decisions about how it should sized. Your TriGoButton class should override the getPreferredSize method and return an appropriate default size..
I've added your code. I think that your issue is that your TriGoPanel doesn't override getPreferredSize, and so it may be sizing itself quite small. Consider adding to the class something like:
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
where you have int constants, PREF_W, PREF_H, for your width and height dimensions.
__________________________________________________
Edit: and I strongly second everything that MadProgrammer recommended!
I wrote a program to compose a GUI using swing/awt framework for my assignment. So far, I am able to get the pieces working together, but when I put them all into a JFrame, they are not coming out as expected.
I have recently started working on Java GUI framework, and not sure what is missing in my code. How can I get this working properly?
I am also attaching the screen shots (see at the bottom) of the output I am getting.
public class MainFrame extends JFrame {
public MainFrame() {
addComponentsToPane(this.getContentPane());
}
private void addComponentsToPane(Container pane) {
// Set layout
GridBagConstraints gbc = new GridBagConstraints();
this.setTitle("Test tool");
this.setSize(600, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2, 1));
// Add video JComponent
mMainPanel = new MainPanel();
pane.add(mMainPanel, 0);
// Add conference screen panel
mFeedPanel = new FeedPanel();
pane.add(mFeedPanel, 1);
// Add a button panel
mButtonPanel = new ButtonPanel();
pane.add(mButtonPanel, 2);
this.setResizable(true);
this.setVisible(true);
this.pack();
}
}
// In actual output, there is 1 screen in this panel.
// mScreen1 is derived from JComponent object.
public class MainPanel() extends JPanel {
public MainPanel() {
addMainPanelComponents();
}
private void addMainPanelComponents() {
this.setSize(352, 240);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 2));
add(mScreen);
setVisible(true);
}
}
// In actual output, there are 3 screens in this panel. I have shown code for 1 screen only
// mScreen1 is derived from JComponent object.
public class FeedPanel extends JPanel {
public FeedPanel() {
addFeedPanelComponents();
}
private void addFeedPanelComponents() {
String img1 = "images/screen1.png";
setSize(352, 150);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 3));
Image image1 = ImageIO.read(new File(img1));
mScreen1.setImage(image1);
add(mScreen1);
setVisible(true);
}
}
public class ButtonPanel extends JPanel {
public ButtonPanel() {
addButtonPanelComponents();
}
private void addButtonPanelComponents() {
this.setSize(352, 150);
this.setBackground(Color.yellow);
this.setLayout(new GridLayout(1,
5));
// Add Button to panel
mStartButton = new JButton("Start");
this.add(mStartButton);
mStartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StartButtonActionListener(ae);
}
});
mStopButton = new JButton("Stop");
this.add(mStopButton);
mStopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StopButtonActionListener(ae);
}
});
setVisible(true);
}
}
This comes by default on running the code.
This comes after manually resizing the frame.
The combination of BorderLayout , GirdLayout and BoxLayout can do this for you(Actually it's not the only choice).
Here is the code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridLayoutTest {
public void createUI(){
JFrame frame = new JFrame();
JPanel topPanel = new TopPanel();
JPanel buttomPanel = new ButtomPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel,BorderLayout.CENTER);
mainPanel.add(buttomPanel,BorderLayout.SOUTH);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
GridLayoutTest test = new GridLayoutTest();
test.createUI();
}
#SuppressWarnings("serial")
class TopPanel extends JPanel{
public TopPanel(){
setLayout(new GridLayout(2, 3));
ImageIcon icon = new ImageIcon("capture.png");
JLabel label1 = new JLabel(icon);
label1.setVisible(false);
JLabel label2 = new JLabel(icon);
JLabel label3 = new JLabel(icon);
label3.setVisible(false);
JLabel label4 = new JLabel(icon);
JLabel label5 = new JLabel(icon);
JLabel label6 = new JLabel(icon);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);
add(label6);
}
}
#SuppressWarnings("serial")
class ButtomPanel extends JPanel{
public ButtomPanel(){
JButton startButton = new JButton("start");
JButton stopButton = new JButton("stop");
JButton recordButton = new JButton("record");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
}
}
}
BoxLayout is so good too provide white space and help you to center the component.
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
Add Glue before the first component and after the last component will help you too center the component and add strut can help you to provide white space you want. you can refer to https://stackoverflow.com/a/22525005/3378204 for more details.
Here is the effect:
The BoxLayout won't affect your component's size. Hope it can help you.
Try this :
public class Main{
private JFrame f;
private JLabel l1, l2, l3,l4;
private JPanel p1, p2, p3;
private JButton b1, b2, b3;
public Main(){
this.f = new JFrame();
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.f.setLayout(new GridLayout(3,1));
this.p1 = new JPanel();
this.p1.setLayout(null)
this.p1.setSize(yoursize);
this.l1 = new JLabel();
this.l1.setBounds(x,y,xspan,yspan);
this.p1.add(l1);
this.p2 = new JPanel();
this.p2.setLayout(new GridLayout(1,3));
this.l2 = new JLabel();
this.l3 = new JLabel();
this.l4 = new JLabel();
this.p2.add(l2);
this.p2.add(l3);
this.p2.add(l4);
this.p3 = new JPanel();
this.p3.setLayout(new GridLayout(1,3));
this.b1 = new JButton();
this.b2 = new JButton();
this.b3 = new JButton();
this.p3.add(b1);
this.p3.add(b2);
this.p3.add(b3);
this.f.add(p1);
this.f.add(p2);
this.f.add(p3);
this.f.pack();
this.f.setResizeable(false)
}}
Add your video components instead of labels and you can change the color of the components as you wish.
Also if you want more control over the size and position of the components, use null layout and place them individually using setBounds() function as once shown in the program above. It is surely time consuming but makes the layout perfect.
I'm creating a slideshow using swing and trying to place it in the center of my JFrame. The slideshow works fine, but it's taking up the entire center section. How would I limit it to a small place under the banner?
Here's a picture of what it looks like.
Here's a picture of what I want it to look like
This is what I have so far, you run this class.
package com.RBV2.engine;
import javax.swing.*;
import com.RBV2.Settings;
import com.RBV2.panels.News;
import com.RBV2.panels.SlideShow;
import com.RBV2.panels.SlideShow.MovingPanel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;
/*
* Author Jon & David
*
*/
#SuppressWarnings("serial")
public class Client extends JFrame implements ActionListener {
private JPanel bottomPanel, news;
private JButton launch;
private JLabel loading, banner;
private MovingPanel slideshow;
protected boolean updated = false;
private void createLayout() {
createPanel();
addPanel();
setVisible(true);
}
private void createPanel() {
bottomPanel = new JPanel(new BorderLayout());
news = new News();
slideshow = new SlideShow.MovingPanel();
launch = new JButton(new URL("http://www.runerebellion.com/clientImages/launch.png"));
loading = new JLabel(new URL("http://www.runerebellion.com/clientImages/loader.gif"));
banner = new JLabel(new URL("http://www.runerebellion.com/clientImages/201457.gif"));
launch.addActionListener(this);
}
private void addPanel() {
setTitle("RuneRebellionV2 Launcher");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Bottom Panel
add(bottomPanel, BorderLayout.SOUTH);
bottomPanel.add(new JLabel(" Launcher, release " + Settings.version), BorderLayout.WEST);
bottomPanel.setBackground(Color.BLACK);
bottomPanel.add(launch, BorderLayout.EAST);
launch.setPreferredSize(new Dimension(120, 40));
//News Feed
add(news, BorderLayout.CENTER);
news.add(banner, BorderLayout.CENTER);
banner.setPreferredSize(new Dimension(500, 70));
//slideshow
slideshow.setPreferredSize(new Dimension(610, 331));
add(slideshow, BorderLayout.CENTER);
//Sets size
setSize(Settings.width, Settings.height);
}
public Client() throws IOException {
createLayout();
}
public static void main(String args[]) throws IOException {
final Client l = new Client();
l.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
l.setVisible(true);
}
});
}
These specific lines of code call the slideshow(I commented out exactly where)
private void addPanel() {
setTitle("RuneRebellionV2 Launcher");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
//Bottom Panel
add(bottomPanel, BorderLayout.SOUTH);
bottomPanel.add(new JLabel(" Launcher, release " + Settings.version), BorderLayout.WEST);
bottomPanel.setBackground(Color.BLACK);
bottomPanel.add(launch, BorderLayout.EAST);
launch.setPreferredSize(new Dimension(120, 40));
//News Feed
add(news, BorderLayout.CENTER);
news.add(banner, BorderLayout.CENTER);
banner.setPreferredSize(new Dimension(500, 70));
//slideshow here
slideshow.setPreferredSize(new Dimension(610, 331));
add(slideshow, BorderLayout.CENTER);
//Sets size
setSize(Settings.width, Settings.height);
}
Here is my slideshow class, you may need this also.
package com.RBV2.panels;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class SlideShow extends JFrame {
public static class MovingPanel extends JPanel {
public int i = 0;
public MovingPanel() {
Timer timer = new Timer(3000, new TimerListener());
timer.start();
}
protected void paintComponent(Graphics x) {
super.paintComponent(x);
int y = i % 25;
Image showImg = new ImageIcon("bin/slide/" + y + ".png").getImage();
x.drawImage(showImg, 0, 0, getWidth(), getHeight(), 0, 0, 610, 331, null);
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
i++;
repaint();
if (i >= 5)
i = 1;
}
}
}
}
So my question is how would I limit the slideshow to be in a box in the very center under the banner.
Have a look at this picture (from Border layout Tutorial)
As you are only adding panels to the Center and South(PAGE_END) regions of the layout manager there is no other components to stop the center panel from stretching out as far as it can.
Note this relevant sentence of the tutorial
If the window is enlarged, the center area gets as much of the available space as possible. The other areas expand only as much as necessary to fill all available space. Often a container uses only one or two of the areas of the BorderLayout object — just the center, or the center and the bottom.
You either need to add blank panels on the other sides or make use of an empty border within your Center panel. See here about how to use borders.
I painted the background, then painted the images over the background
protected void paintComponent(Graphics x) {
super.paintComponent(x);
int y = i % 25;
Image showImg = new ImageIcon("bin/slide/" + y + ".png").getImage();
super.paintComponent(x);
x.drawImage((Settings.background).getImage(), 0, 0, getWidth(), getHeight(), this);
x.drawImage(showImg, 360, 260, getWidth(), getHeight(), 0, 0, 110, 31, null);
}
I hope this does not appear too much of a newbie question. I've not done graphical style programming before. My objective is to create a pinball advergame in an applet. However, I'm falling at one of the first hurdles. My applet is not displaying the results of the paintComponent method from my Table class (which extends the JPanel). I've tried several things, such as how I load the image (currently using double buffering but I did use a mediatracker before), seeing if not having any other GUI stuff would allow the painting to occur (since I wondered if it was being drawn underneath somehow) and other things. This problem has stumped me and I'm starting to wonder (and hope) if it's something small that I've overlooked, if it is, then I'm sorry but would still be grateful for help, as I can't go very far without this problem being fixed first. My code for my Pinball (applet) and Table class are below, the other classes aren't implemented yet. Once again, I appreciate any help.
import javax.swing.*; // useful for the drawing side, also going to be a JApplet
import java.awt.*;
import java.net.*;
public class Pinball extends JApplet {
// variables go here
Table table;
// further initialisation of the GUI
public void init() {
setSize(300, 300);
table = new Table(this);
add(table);
setContentPane(table); // makes our graphical JPanel container the content pane for the Applet
// createGUI(); // this has been moved onto the table class
}
public void stop() {
}
}
And now the Table class:
import java.awt.*; // needed for old style graphics stuff
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*; // gives us swing stuff
import java.io.IOException;
import java.net.*; // useful for anything using URLs
public class Table extends JPanel {
// attributes go here
Pinball pb;
Color bgColour;
JPanel eastPanel;
JPanel logoPanel;
JPanel livesPanel;
JPanel scorePanel;
JPanel tablePanel;
JPanel scrollTextPanel;
Image logo;
// constructor goes here
public Table(Pinball pb) {
setPreferredSize(new Dimension(300, 300));
this.pb = pb;
// this is not needed anymore, with the new loadImage class down the bottom
// Toolkit tk = Toolkit.getDefaultToolkit(); // needed to get images
// logo = tk.getImage(base + "images/logo.jpg");
logo = loadImage("logo.jpg");
createGUI();
}
// public methods go here
// all GUI creation stuff goes here
public void createGUI() {
/* allows the three parts (top, middle and right)
* to be made through (north, center and right) */
setLayout(new BorderLayout());
// setting the background colour
bgColour = new Color(190, 186, 221); // makes the sky blue colour for the background.
setBackground(bgColour);
// now putting a panel for the east side
eastPanel = new JPanel();
eastPanel.setBackground(bgColour);
eastPanel.setLayout(new BorderLayout(8, 8));
eastPanel.setPreferredSize(new Dimension(100, 280));
logoPanel = new JPanel();
logoPanel.setBackground(Color.WHITE);
logoPanel.setPreferredSize(new Dimension(100, 100));
logoPanel.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.white));
//JLabel label1 = new JLabel("Logos go here");
//logoPanel.add(label1);
eastPanel.add(logoPanel, "North");
livesPanel = new JPanel();
livesPanel.setBackground(Color.WHITE);
livesPanel.setPreferredSize(new Dimension(100, 100));
JLabel label2 = new JLabel("Lives go here");
livesPanel.add(label2);
eastPanel.add(livesPanel, "Center");
scorePanel = new JPanel();
scorePanel.setBackground(Color.WHITE);
scorePanel.setPreferredSize(new Dimension(100, 80));
JLabel label3 = new JLabel("Scores go here");
scorePanel.add(label3);
eastPanel.add(scorePanel, "South");
add(eastPanel, "East");
tablePanel = new JPanel();
tablePanel.setBackground(bgColour);
tablePanel.setPreferredSize(new Dimension(200, 280));
add(tablePanel, "Center");
scrollTextPanel = new JPanel();
scrollTextPanel.setPreferredSize(new Dimension(300, 20));
scrollTextPanel.setBackground(Color.WHITE);
scrollTextPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(scrollTextPanel, "North");
// repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(logo, 5, 5, 90, 90, null);
g.drawLine(0, 0, 300, 300); // for testing, does not work
}
// a little useful method for handling loading of images and stuff
public BufferedImage loadImage(String filename) {
BufferedImage image = null;
try {
URL url = new URL(pb.getCodeBase(), "images/" + filename);
image = ImageIO.read(url);
} catch (IOException e) {
}
return image;
}
}
Your Table JPanel is covered by other JPanels, which can be OK, but you won't be able to see through an opaque component that is covering it, in particular the tablePanel JPanel. For example, try:
tablePanel = new JPanel();
// tablePanel.setBackground(bgColour); //!! removed
tablePanel.setOpaque(false); //!! added
And see what happens.
An unrelated question for you regarding this code here:
public void init() {
setSize(300, 300);
table = new Table(this);
add(table);
setContentPane(table); // makes our graphical JPanel container the content
Why are you adding the table Table object twice, once to the JApplet's contentPane and then next as the JApplet's contentPane?
Run then examine this code & see if you can spot the source of the problem.
// <applet code='Pinball' width='300' height='300'></applet>
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*; // useful for the drawing side, also going to be a JApplet
import javax.imageio.ImageIO;
import java.net.*;
import java.io.IOException;
public class Pinball extends JApplet {
// variables go here
Table table;
// further initialisation of the GUI
public void init() {
table = new Table(this);
setContentPane(table); // makes our graphical JPanel container the content pane for the Applet
}
}
class Table extends JPanel {
// attributes go here
Pinball pb;
Color bgColour;
JPanel eastPanel;
JPanel logoPanel;
JPanel livesPanel;
JPanel scorePanel;
JPanel tablePanel;
JPanel scrollTextPanel;
Image logo;
// constructor goes here
public Table(Pinball pb) {
//setPreferredSize(new Dimension(300, 300));
this.pb = pb;
// this is not needed anymore, with the new loadImage class down the bottom
//Toolkit tk = Toolkit.getDefaultToolkit(); // needed to get images
//logo = tk.getImage(base + "images/logo.jpg");
int size = 100;
logo = //loadImage("logo.jpg");
new BufferedImage( size,size, BufferedImage.TYPE_INT_RGB);
Graphics g = logo.getGraphics();
g.setColor(Color.red);
g.fillRect(0,0,size,size);
createGUI();
}
// public methods go here
// all GUI creation stuff goes here
public void createGUI() {
/* allows the three parts (top, middle and right)
* to be made through (north, center and right) */
setLayout(new BorderLayout(20,20));
// setting the background colour
bgColour = new Color(190, 186, 221); // makes the sky blue colour for the background.
setBackground(bgColour);
// now putting a panel for the east side
eastPanel = new JPanel();
eastPanel.setBackground(bgColour);
eastPanel.setLayout(new BorderLayout(8, 8));
eastPanel.setPreferredSize(new Dimension(100, 280));
logoPanel = new JPanel();
logoPanel.setBackground(Color.WHITE);
logoPanel.setPreferredSize(new Dimension(100, 100));
logoPanel.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.green));
eastPanel.add(logoPanel, "North");
livesPanel = new JPanel();
livesPanel.setBackground(Color.WHITE);
livesPanel.setPreferredSize(new Dimension(100, 100));
JLabel label2 = new JLabel("Lives go here");
livesPanel.add(label2);
eastPanel.add(livesPanel, "Center");
scorePanel = new JPanel();
scorePanel.setBackground(Color.WHITE);
scorePanel.setPreferredSize(new Dimension(100, 80));
JLabel label3 = new JLabel("Scores go here");
scorePanel.add(label3);
eastPanel.add(scorePanel, "South");
add(eastPanel, "East");
tablePanel = new JPanel();
tablePanel.setBackground(bgColour);
tablePanel.setPreferredSize(new Dimension(200, 280));
add(tablePanel, "Center");
scrollTextPanel = new JPanel();
scrollTextPanel.setPreferredSize(new Dimension(300, 20));
scrollTextPanel.setBackground(Color.WHITE);
scrollTextPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(scrollTextPanel, "North");
}
#Override
public void paintComponent(Graphics g) {
System.out.println("paintComponent");
super.paintComponent(g);
g.setColor(Color.black);
g.drawImage(logo, 5, 5, 90, 90, this);
g.drawLine(0, 0, 300, 300); // for testing, does not work
}
// a little useful method for handling loading of images and stuff
public BufferedImage loadImage(String filename) {
BufferedImage image = null;
try {
URL url = new URL(pb.getCodeBase(), "images/" + filename);
image = ImageIO.read(url);
} catch (IOException e) {
// do NOT ignore exceptions in broken code.
}
return image;
}
}