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);
}
Related
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);
I am currently trying to make a program using four panels. Three panels are grouped together on the left side of the JFrame using GridLayout and the last one takes up the right side of the screen. Ideally, the left panel will take up the 2/3 of the left side of the JFrame and the last third will be taken up by the fourth panel. I have attempted to do this in many ways and can't figure it out. The current display splits the screen in half and displays yellow, red, blue on top of each other, but only 540 pixels long, while the green is covering up the rest of the left panel.
This has the green rectangle representing the last panel and it is overlapping the yellow red and blue rectangles which should be 720 pixels long. I have accomplished properly displaying the way I want by re-sizing the JFrame until i made it work. By re-sizing till the rectangles line up i managed to make it look like it should. I moved the right side of the JFrame until the two respective panels lined up with no white space or overlap, unfortunately, in order to do this there is a ton of excess white space on the side.
Here is the code i used to make this display. I am a complete novice with swing and might have completely done this wrong. I am not set on using GridLayout, I just want to make this work correctly.
import java.awt.*;
import javax.swing.*;
class testJPanel1 extends JPanel //topLeft
{
int x,y;
//JPanel Tjp1;
public testJPanel1()
{
x=720;
y=250;
setSize(x,y);
setVisible(true);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//g.fillOval(x,y,50,50);
g.setColor(Color.yellow);
g.fillRect(0, 0, x, y);
g.setColor(Color.black);
g.drawString("1",x,y);
System.out.println("Hey 1 works");
}
}
class testJPanel2 extends JPanel //mid left
{
int x,y;
public testJPanel2()
{
x=720;
y=260;
setVisible(true);
setSize(x,y);
}
#Override
public void paintComponent(Graphics g)
{super.paintComponent(g);
//g.fillOval(x,y,50,50);
g.setColor(Color.red);
g.fillRect(0, 0, x, y);
g.setColor(Color.black);
g.drawString("2",x,y);
System.out.println("Hey 2 works");
}
}
class testJPanel3 extends JPanel //bot left
{
int x,y;
int boundsx;
int boundsy;
public testJPanel3()
{
x=720;
y=250;
boundsx=200;
boundsy=200;
setVisible(true);
setSize(x,y);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//g.fillOval(x,y,50,50);
g.setColor(Color.blue);
g.fillRect(0, 0, x, y);
g.setColor(Color.black);
g.drawString("3",x,y);
System.out.println("Hey 3 works");
// g.drawRect(0,0,boundsx,boundsy);
}
}
class testJPanel4 extends JPanel //BIG one on the right
{
int x,y;
int boundsx;
int boundsy;
public testJPanel4()
{
x=360;
y=760;
boundsx=200;
boundsy=200;
setVisible(true);
setSize(x,y);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.green);
//g.fillOval(x,y,50,50);
g.fillRect(0,0,x,y);
g.setColor(Color.black);
g.drawString("4",x,y);
System.out.println("Hey 4 works");
//g.drawRect(0,0,boundsx,boundsy);
}
}
class Left_Panel extends JPanel //Combines 1 and 2 and 3
{
testJPanel1 tjp1;
testJPanel2 tjp2;
testJPanel3 tjp3;
public Left_Panel()
{
setLayout(new GridLayout(3,1));
tjp1= new testJPanel1();
tjp2= new testJPanel2();
tjp3= new testJPanel3();
add(tjp1);
add(tjp2);
add(tjp3);
}
}
class combo_Panel extends JPanel //combines left and right panels together
{
Left_Panel lp;
testJPanel4 tjp4;
//GOAL IS TO MAKE THIS PANEL lp is 720,760 pixels and tjp4 360,760...still doesnt work
public combo_Panel()
{
setLayout(new GridLayout(1,2)); //HOW TO make this work the way i want it or use something else i want
lp= new Left_Panel();
lp.setSize(720,760);
tjp4= new testJPanel4();
tjp4.setSize(360,760);
add(lp);
add(tjp4);
}
}
class Paint_Window extends JFrame
{
combo_Panel combo;
Paint_Window(String title)
{
super(title);
//setLayout( new BoxLayout(combo,2));
combo = new combo_Panel();
setBounds(new Rectangle(1080,760));
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setLayout(new FlowLayout());
add(combo);
//add(tjp5);
//tjp1.repaint();
}
}
public class testJPanel
{
public static void main(String args[])
{
Paint_Window window = new Paint_Window("Make your choice");
}
You have a few options, you could try laying out all three panels in a single container using a GridLayout, but that might not be possible, the other choice might be to use a GridBagLayout and adjust the weightx property to suit your requirements, for example...
Note the red "border" around the blue and green panels, this is showing the parent container for these two components
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.PopupMenu;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class TestLayout {
public static void main(String[] args) {
new TestLayout();
}
public TestLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel leftSide;
private JPanel rightSide;
public TestPane() {
setLayout(new GridBagLayout());
leftSide = new JPanel(new GridLayout(1, 2));
leftSide.setBackground(Color.RED);
leftSide.setBorder(new EmptyBorder(1, 1, 1, 1));
leftSide.add(createPanel(Color.BLUE));
leftSide.add(createPanel(Color.GREEN));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.67;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(leftSide, gbc);
gbc.gridx = 1;
gbc.weightx = 0.33;
rightSide = createPanel(Color.MAGENTA);
add(rightSide, gbc);
}
protected JPanel createPanel(Color color) {
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(50, 100);
}
};
panel.setBackground(color);
return panel;
}
}
}
I'm working on a Java GUI and I have a JFrame thats 600x800 that I want to split into two portions, the top which has checkboxes for settings and is 600 x 200 and the bottom which is the "canvas" which will be painted on that is 600x600. I have a JFrame that has a JPanel that contains two other JPanels (one for the settings, the other for the canvas). I'm testing the "painting" and for some reason when I try to paint a 600x600 black rectangle, it paints a much smaller rectangle in the area that the settings JPanel occupies. Any ideas what's going on? I'm using the repaint method to call paintComponent and I've tried calling repaint in both the constructor of my JFrame and in the JPanel that is to be painted.
HPAProgram
public class HPAProgram {
public static void main(String[] args) {
MapWindow map = new MapWindow();
}
}
MapWindow
//import java.awt.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.*; //notice javax
public class MapWindow extends JFrame
{
private static final int WIDTH = 600, HEIGHT = 800;
JPanel panel = new JPanel();
SettingsButtonsPanel button_panel = new SettingsButtonsPanel();
MapImagePanel map_panel = new MapImagePanel();
public MapWindow()
{
setLocationRelativeTo(null);
setTitle("HPA* Test");
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(panel);
panel.setBounds(0, 0, 600, 800);
//panel.setLayout(new GridBagLayout());
/*GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;*/
panel.add(button_panel);
/*c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;*/
panel.add(map_panel);
button_panel.setLocation(0,0);
/*map_panel.setLocation(0,200);
map_panel.setSize(600,600);*/
map_panel.repaint();
}
}
SettingsButtonsPanel
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class SettingsButtonsPanel extends JPanel implements ItemListener{
private static final int WIDTH = 600, HEIGHT = 200;
private static final int NUM_MAP_TYPE = 2;
private JCheckBox[] map_type;
JPanel panel = new JPanel();
public SettingsButtonsPanel(){
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
this.setBounds(0,0,WIDTH, HEIGHT);
map_type = new JCheckBox[NUM_MAP_TYPE];
map_type[0] = new JCheckBox("Sparse");
map_type[0].setSelected(true);
//map_type[0].setSize(100,100);
map_type[1] = new JCheckBox("Maze");
map_type[1].setSelected(false);
//map_type[1].setSize(100,100);
for(int i = 0; i < NUM_MAP_TYPE; i++)
{
map_type[i].addItemListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = i;
this.add(map_type[i], c);
}
}
public void itemStateChanged(ItemEvent e)
{
Object source = e.getItemSelectable();
//if(source == )
}
}
MapImagePanel
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MapImagePanel extends JPanel{
public MapImagePanel()
{
this.setBounds(0,200, 600,600);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0,0,600,600);
}
}
The are a number of misconceptions you seem to have...
JPanel, by default uses a FlowLayout. FlowLayout makes use of each of the components preferred size to determine the size of each component. By default, a component has a preferred size of 0x0.
The layout manager is also responsible for positing the components, so using setBounds and setLocation and setSize is counter productive.
Assuming the size is also not always possible, especially when dealing with text, as this can change size based on differences in the fonts, display drivers, rendering pipelines etc...
This is why Java makes extensive layout managers. Take a look at Laying Out Components Within a Container for more details
Update with simple example
Don't be afaird to mix layouts, using compound components with different layouts, to achieve your desired results, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SimpleLayout100 {
public static void main(String[] args) {
new SimpleLayout100();
}
public SimpleLayout100() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JPanel header = new JPanel();
header.add(new JLabel("Hello, I'm the header"));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(header, BorderLayout.NORTH);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.GREEN);
g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
g2d.setColor(Color.RED);
g2d.fillRect(150, 50, 300, 100);
g2d.dispose();
}
}
}
I am trying to create a GUI that will take in the number of circles to draw, and draw them in drawPanel with random locations/sizes. On my actionListener, when I try to draw the circle, it gives me red lines on my drawOval
1st class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
*
* #author Chris
*
*/
public class CirclesPanel extends JPanel{
private JButton draw, clear;
private JTextArea textArea;
private JPanel panel, drawPanel, buttonPanel;
private int count;
/**constructor
* builds the frame
*/
public CirclesPanel(){
//creates buttons and textArea
draw = new JButton("Draw");
clear = new JButton("Clear");
textArea = new JTextArea(1,10);
textArea.setBorder(BorderFactory.createTitledBorder("Circles"));
//creats panel
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
setPreferredSize(new Dimension(620, 425));
//creates subpanel drawPanel
JPanel drawPanel = new JPanel();
drawPanel.setPreferredSize(new Dimension(450,400));
drawPanel.setBackground(Color.BLACK);
//creates subpanel buttonPanel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(3,1));
//adds all the content to the frame
add(panel);
add(buttonPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.EAST);
buttonPanel.add(textArea);
buttonPanel.add(draw);
buttonPanel.add(clear);
//reads if the draw button is clicked
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
count =Integer.parseInt(textArea.getText());//takes the count in
repaint();//repaints the picture to add the circles
}
});
//reads if the clear button is clicked
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
count=0;//sets the count to 0 so nothing is painted
repaint();//repaints the window
}
});
}
/**Paint component
* draws the random circles
*/
public void paintComponent(Graphics g) {
Random generator = new Random();
int x, y, diameter;
for(int i = 0; i < count; i++){ //loop that takes the count and does this "x" times
g.setColor(Color.BLUE);//sets color to blue
x = generator.nextInt(90);//random location for x
y = generator.nextInt(90);//random location for y
diameter = generator.nextInt(30);//random size
g.fillOval(x, y, diameter, diameter);//draws the circle
}
}
}
2nd class
import javax.swing.JFrame;
public class Circles {
public static void main(String[]args){
JFrame frame = new JFrame("Cicles HW9");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CirclesPanel());
frame.pack();
frame.setVisible(true);
}
}
So in your, I did little addition, first of all, I made the whole program in one class(CIRLCES PANEL), IF You want to use the second class, you can use it....
Problem is coming, your program is not the reading the ActionPerformed method for the drawing, means it is not located with the button, now I directly added it with your button(DRAW), now whenever you click on the button, it automatically reads the your textArea value, and draw your circles. I made your text area FINAL, So you can use it anywhere......
Now things that you need to do----
- this program is drawing circle on the whole frame, means not on your drawing Panel, you need to set the values, so it will draw on your draw panel area
- Also you need to add color for your oval, because it will either draw black color circle, which you will not able to see.....
and also one thing I forget to mentioned you, is that your, you also need to add code for your clear method...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class CirclesPanel extends JPanel{
private JButton draw, clear;
private JTextArea textArea;
private JPanel panel, drawPanel, buttonPanel;
private int count;
public CirclesPanel(){
JButton draw = new JButton("Draw");
JButton clear = new JButton("Clear");
final JTextArea textArea = new JTextArea(1,10);
textArea.setBorder(BorderFactory.createTitledBorder("Circles"));
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
setPreferredSize(new Dimension(620, 425));
JPanel drawPanel = new JPanel();
drawPanel.setPreferredSize(new Dimension(450,400));
drawPanel.setBackground(Color.BLACK);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(3,1));
add(panel);
add(buttonPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.EAST);
buttonPanel.add(textArea);
buttonPanel.add(draw);
buttonPanel.add(clear);
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
count =Integer.parseInt(textArea.getText());
repaint();
}
});
}
public void paintComponent(Graphics g) {
Random generator = new Random();
int x, y, diameter;
for(int i = 0; i < count; i++){
x = generator.nextInt(90);
y = generator.nextInt(90);
diameter = generator.nextInt(30);
g.drawOval(x, y, diameter, diameter);
}
}
}
What you want to do is drawing some random circles on the drawPanel when button clicked. I write you a simplified version to show how things work.
I only keep the drawButton and paintPanel to keep things simple.
public class PaintFrame extends JFrame {
private JPanel content = new JPanel();
private JButton drawButton = new JButton("Draw");
private PaintPanel paintPanel = new PaintPanel();
public PaintFrame() {
getContentPane().add(content);
content.setLayout(new BorderLayout());
drawButton.setSize(100, 500);
drawButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// drawButton is fired, repaint the paintPanel
paintPanel.repaint();
}
});
content.add(drawButton, BorderLayout.WEST);
content.add(paintPanel, BorderLayout.CENTER);
}
}
You need a new class extending the JPanel and override the paintComponent method to do the paint job for you. This makes sure you are drawing on the panel.
class PaintPanel extends JPanel {
public PaintPanel() {
setSize(500, 500);
setBackground(Color.BLACK);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Random random = new Random();
g.setColor(Color.WHITE);
// draw 5 random circles
int count = 5;
for (int i = 0; i < count; i++) {
g.drawOval(random.nextInt(250), random.nextInt(250),
random.nextInt(250), random.nextInt(250));
}
}
}
Main class
public class DrawMain {
public static void main(String[] args) {
JFrame frame = new PaintFrame();
frame.setDefaultCloseOperation(PaintFrame.EXIT_ON_CLOSE);
frame.setSize(600, 500);
frame.setVisible(true);
}
}
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;
}
}