This is a noob question.
We are being taught applets in class, and I was trying something on my own.
The following is the code
import java.awt.*;
import javax.swing.*;
class controls extends JPanel{
#Override public void paintComponent(Graphics g) {
g.drawOval(50, 50, 50, 50); // <-- draws an oval on the panel
}
}
public class test extends JApplet{
public void init(){
final JPanel stage = new JPanel();
final JPanel controlPanel = new controls();
final JPanel banner = new JPanel();
final JLabel name = new JLabel("Test", JLabel.CENTER);
this.setLayout(new BorderLayout());
banner.setBackground(Color.CYAN);
banner.add(name);
this.add(controlPanel, BorderLayout.WEST);
this.add(banner, BorderLayout.NORTH);
}
}
As far as I understand, paintComponent() need not be called explicitly.
The controls class works well when used alone.
I mean the following code works.
public class test extends JApplet{
public void init(){
JPanel controlPanel = new controls();
this.add(controlPanel);
}
}
I am not able to understand the difference. Why does the same code work in this case, and not in the previous?
Thank you.
Override public Dimension getPreferredSize() (and return a new Dimension) in the controls class. When putting components in WEST the width will be determined by the preferredSize. If you don't override getPreferredSize, the preferred size will be 0. The CENTER will take up the rest of the space, after the WEST, ect is calculated. The second case works because it is in the CENTER of the default BorderLayout
Related
I am making an adaptation of a board game. The board will be drawn on a JPanel by overriding the paintComponent(Graphics g) method. The board can possibly be larger than the size of the JPanel it is drawn in, so I planned to use a JScrollPane to allow the user to scroll across the board to view it. As an example, I made the board a single large rectangle to see if I could get it to scroll across that, but to no avail. I have used JScrollPane successfully before but I cannot figure out why this case is any different from the way I previously used it.
Can anyone see why it is not working correctly?
Here is the code for the Game's JFrame:
public class GameFrame extends JFrame{
JPanel playerDeckPanel, contentPane;
JScrollPane gameScrollPane;
BoardPanel boardPanel;
public GameFrame(){
super();
SwingUtilities.invokeLater(new Runnable(){
public void run(){
boardPanel = new BoardPanel();
playerDeckPanel = new JPanel();
boardPanel.setLayout(new GridLayout(1,1));
playerDeckPanel.setLayout(new CardLayout());
boardPanel.setSize(1000,1000);
gameScrollPane = new JScrollPane(boardPanel);
gameScrollPane.setPreferredSize(new Dimension(300,300));
contentPane = ((JPanel) getContentPane());
contentPane.setLayout(new GridLayout(1,2));
contentPane.add(gameScrollPane);
contentPane.add(playerDeckPanel);
setMinimumSize(new Dimension(800,600));
}
});
}
public static void main(String[] args){
GameFrame gameFrame = new GameFrame();
gameFrame.setVisible(true);
}
private class BoardPanel extends JPanel{
public BoardPanel(){
super();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(100, 10, 700, 600);
revalidate();
}
}
}
This is my first time posting a question, so let me know if you need additional information to solve this problem
You need to setPreferredSize on BoardPanel, that seems to do the trick. Don't ask why ;-)
-#geert3
No matter what I do, I can't get the JFrame to show anything. Its just blank. I added the buttons starter and tutorialer to the JPanel game and added that JPanel to the the JPanel cards which I set to a cardLayout.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class layouter extends JFrame {
public static void main (String[]args){
layouter x = new layouter();
}
public layouter(){
setSize(600,600);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Pan p = new Pan();
setContentPane(p);
setVisible(true);
}
}
class Pan extends JPanel{
JButton starter;
JButton tutorialer;
JPanel start;
JPanel tutorial;
JPanel game;
JPanel cards;
CardLayout cl;
Pan(){
starter = new JButton("start");
tutorialer = new JButton("tutorial");
start = new JPanel();
tutorial = new JPanel();
game = new JPanel();
cards = new JPanel( new CardLayout());
cl= (CardLayout)(cards.getLayout());
game.setLayout(null);
starter.setBounds(150,150,100,50);
tutorialer.setBounds(150,200,100,50);
game.add(starter);
game.add(tutorialer);
cards.add(game,"game");
add(cards);
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
cl.show(cards,"game");
System.out.println("hello");
}
}
game.setLayout(null); <-- This is going to cause you issues as anything your add to this container will no longer be automatically laid out. Components by default have a size and position of 0x0
Make use of an appropriate layout manager. See Laying Out Components Within a Container for more details.
If you add any more containers to games, you may need to "show" the default view you want to been shown first
cl.show(cards, "game");
I have looked online, but I am still having trouble understanding how to add graphics to a JPanel
Here is the code for my panel class:
public class GamePanel extends JPanel {
public GamePanel(){
}
public void paintComponent(Graphics g) {
g.drawString("asd", 5, 5);
}
}
And my main method:
public static void main(String[] args) {
frame.setLayout(new FlowLayout());
frame.getContentPane().setBackground(Color.WHITE);
//i is an instance of GamePanel
frame.add(i);
frame.setPreferredSize(new Dimension(500, 500));
frame.pack();
frame.setVisible(true);
}
Text will only appear in a very tiny section of the screen (this applies to any graphics object I try to draw). What am I doing wrong?
FlowLayout respects preferred sizes of components. Therefore override getPreferredSize to give your JPanel a visible size rather than the default zero size Dimension that the panel currently has after JFrame#pack is called:
class GamePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g); // added to paint child components
g.drawString("asd", 5, 20);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
}
Edit:
To eliminate gap between JPanel and its containing JFrame, set the vertical gap to 0:
frame.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
Two things jump out
Your Game panel has no preferred size, which, by default, makes 0x0. FlowLayout will use this information to make decisions about how best to layout your panel. Because the size is 0x0, the repaint manager will ignore it. Try overriding the getPreferredSize method and return a appropriate size or use a layout manager that does not use the preferred size, like BorderLayout
Your paintComponent method MUST call super.paintComponet
I need to display chessboard. I have a BoardPanel class which extends JPanel and a GamePanel (also extending JPanel) class containing BoardPanel. GamePanel fills all the application frame.
I want BoardPanel to always be a square with size equal to the minimum of GamePanel's width and height (if GamePanel's width is greater than height there should be empty space on the left and right, if it's smaller there should be empty space on top and bottom). It's also important that BoardPanel should be displayed in the center of parent panel.
I wrote sth like this:
public GamePanel() {
setLayout(new BorderLayout(0, 0));
boardPanel = new BoardPanel(...);
this.add(boardPanel, BorderLayout.CENTER);
...
}
and in BoardPanel:
public void paintComponent(Graphics g) {
super.paintComponent(g);
int size = Math.min(this.getParent().getHeight(), this.getParent().getWidth());
this.setSize(size, size);
...
}
It resizes well, but chessboard is always displayed in top left corner of GamePanel (all the empty space is displayed on bot or right) and I don't know how to fix it.
Any help? Thanks in advance!
Center it using a GridBagLayout.
import java.awt.*;
import javax.swing.*;
public class CenteredPanel {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new GridBagLayout());
JPanel square = new SquarePanel();
square.setBackground(Color.RED);
gui.add(square);
JFrame f = new JFrame("SquareBoard");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(gui);
f.setMinimumSize(new Dimension(400,100));
f.pack();
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
class SquarePanel extends JPanel {
#Override
public Dimension getPreferredSize() {
Container c = this.getParent();
int size = Math.min(c.getHeight(), c.getWidth());
Dimension d = new Dimension(size,size);
return d;
}
}
No need for new BorderLayout(0,0) simply use default constructor for BorderLayout
Dont call setSize() rather override getPreferredSize() of JPanel like so:
#Override
public void getPreferredSize() {
int size = Math.min(this.getParent().getHeight(), this.getParent().getWidth());
return new Dimension(size,size);
}
also its never good to do work in your paintComponent as this should be used exclusively for painting only.
If the above does not work I'd suggest a SSCCE to illustrate specific problems you might have
I believe JViewport does work with JPanel, but when I build a new class that extends JPanel, it seem as if the JViewport is ignore by the program. I don't know if I do anything wrong, so this is the test I conduct and still get the same result:
public class panel extends JPanel
{
public panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawString("Hello World", 50, 50);
g.setColor(Color.RED);
g.fillRect(50,50,100,100);
g.setColor(Color.BLACK);
g.fillOval(100, 100, 50, 50);
}
}
public class test extends JFrame
{
private panel p;
public void init()
{
this.setSize(1000, 1000);
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
p = new panel();
p.setOpaque(false);
JViewport v = new JViewport();
v.setViewSize(new Dimension(200,200));
v.setViewPosition(new Point(2000,2000));
v.setView(p);
this.add(v,BorderLayout.CENTER);
}
public test()
{
init();
}
public static void main(String[] args)
{
test t = new test();
}
}
It suppose to show part of the painted JPanel, but the JFrame window just display the whole JPanel. Therefore, I don't know if I did any wrong or JViewport is not built for this purpose. If it is the latter, then it would be great if anyone can suggest a workaround solution.
Thanks
The BorderLayout you're using is causing the viewport, which is placed in the center, to take the entire space inside the frame, since there are no other components in that layout. That's how the BorderLayout works.
Thus the viewport is also given a bigger size than defined (the size is overwritten by the layout manager). Since the panel doesn't have a fixed size either, it will also be resized.
In order to change that, either use a different layout manager or set a minimum/maximum size for the viewport and override getPreferredSize() for the panel.
As a side note: don't use lower case class names like panel.