How to paint on a Jpanel? - java

i am trying to add 2 different panels in a Frame. one panel adds few buttons in the frame. others frame will add a chess board into the frame. i am confused, how to draw this board on a panel. my Frame will have a board on the top and buttons at the bottom. Moreover, let me know if i am somewhere wrong in the given code can anybody help me? my Code is
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame main;
private JPanel board;
private JPanel buttons;
private JButton add;
private JButton delete;
public Test()
{
main=new JFrame();
board=new JPanel();
buttons=new JPanel();
add=new JButton("Add");
delete=new JButton("Delete");
init();
addButtons();
}
public void init()
{
main.setSize(700,700);
main.setVisible(true);
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
}
public void addButtons()
{
buttons.setSize(700,40);
buttons.setLayout(new FlowLayout());
buttons.add(add);
buttons.add(delete);
main.add(buttons,BorderLayout.SOUTH);
}
public void addBoxes()
{
// what should be my code here...??
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test();
}
}

You need a component to paint on, like a JPanel.
You need to #Override its paintComponent method
You can use a loop to paint using Graphics context
Use a flag to alternate between colors.
Take a look at some Painting Graphics tutorials
In the mean time, give this a whirl
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Board extends JPanel {
private static final int DIM_WIDTH = 640;
private static final int DIM_HEIGHT = 640;
private static final int SQ_SIZE = 80;
boolean black = true;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < DIM_HEIGHT; i += SQ_SIZE) {
if (black) {
black = false;
} else {
black = true;
}
for (int j = 0; j < DIM_WIDTH; j += SQ_SIZE) {
if (black) {
g.setColor(Color.WHITE);
g.fillRect(j, i, SQ_SIZE, SQ_SIZE);
black = false;
} else {
g.setColor(Color.BLACK);
g.fillRect(j, i, SQ_SIZE, SQ_SIZE);
black = true;
}
}
}
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new Board());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(DIM_WIDTH, DIM_HEIGHT);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Related

Clicking a button within a JFrame passes an data to a JPanel

I have a Jframe with two buttons: '1' and '2'. Clicking the button '1' should display the capital letter A in the JPanel.
Code fore my JFrame:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawFrame extends JFrame{
private final int WIDTH = 500;
private final int HEIGHT = 300;
private JButton number1;
private JButton number2;
private JPanel numberPanel;
private DrawPanel graphicsPanel;
public DrawFrame()
{
createSelectionPanel();
createGraphicsPanel();
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private void createSelectionPanel()
{
numberPanel = new JPanel();
number1 = new JButton("1");
number2 = new JButton("2");
numberPanel.setLayout(new GridLayout(2,2));
numberPanel.add(number1);
numberPanel.add(number2);
this.add(numberPanel, BorderLayout.WEST);
}
private void createGraphicsPanel()
{
//instantiate drawing panel
graphicsPanel = new DrawPanel();
//add drawing panel to right
add(graphicsPanel);
}
private class Number1ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
Number number = new Number();
number.setNumber('A');
}
}
//creates a drawing frame
public static void main(String[] args)
{
DrawFrame draw = new DrawFrame();
}
}
Code for my JPanel
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class DrawPanel extends JPanel{
public Coordinates current;
public DrawPanel(){
//nothing drawn initially
current = null;
//set white background for drawing panel
setBackground(Color.WHITE);
//add mouse listeners
MouseHandler mouseHandler = new MouseHandler();
this.addMouseListener(mouseHandler);
this.addMouseMotionListener(mouseHandler);
}
public void paint(Graphics g){
super.paint(g);
if(current!=null){
I want to replace "A" with number.getNumber()
g.drawString("A", current.getX(), current.getY());
}
}
//class to handle all mouse events
private class MouseHandler extends MouseAdapter implements MouseMotionListener
{
public void mousePressed(MouseEvent event)
{
current = new Coordinates(event.getX(), event.getY());
}
public void mouseReleased(MouseEvent event)
{
repaint();
}
}
}
I'm not sure if this is possible. So sorry if I am mistaken in my logic. Please provide an alternate way for me to approach this problem. Appreciate any guidance.
Thanks!
The Coordinates and Number classes weren't included, so I had to modify the code somewhat.
Here's the GUI I created.
The first thing I did was create a model class for the GUI. By creating a model class, I could make the display string and the drawing coordinate available to the view and the controller classes. This is a simple example of the model / view / controller pattern.
package com.ggl.drawing;
import java.awt.Point;
public class GUIModel {
private String displayString;
private Point coordinate;
public GUIModel(String displayString) {
this.displayString = displayString;
}
public Point getCoordinate() {
return coordinate;
}
public void setCoordinate(int x, int y) {
this.coordinate = new Point(x, y);
}
public void setCoordinate(Point coordinate) {
this.coordinate = coordinate;
}
public void setDisplayString(String displayString) {
this.displayString = displayString;
}
public String getDisplayString() {
return displayString;
}
}
Now that we have a model, lets look at the DrawFrame class.
package com.ggl.drawing;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawFrame implements Runnable {
private final int WIDTH = 500;
private final int HEIGHT = 300;
private JFrame frame;
private GUIModel model;
public DrawFrame() {
this.model = new GUIModel("A");
}
#Override
public void run() {
frame = new JFrame("Draw Letters");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createSelectionPanel(), BorderLayout.WEST);
frame.add(new DrawPanel(WIDTH, HEIGHT, model), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private JPanel createSelectionPanel() {
JPanel numberPanel = new JPanel();
ButtonListener listener = new ButtonListener();
JButton number1 = new JButton("A");
number1.addActionListener(listener);
JButton number2 = new JButton("B");
number2.addActionListener(listener);
numberPanel.setLayout(new GridLayout(0, 2));
numberPanel.add(number1);
numberPanel.add(number2);
return numberPanel;
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
model.setDisplayString(event.getActionCommand());
}
}
// creates a drawing frame
public static void main(String[] args) {
SwingUtilities.invokeLater(new DrawFrame());
}
}
I started the Java Swing application on the Event Dispatch thread with the call to the SwingUtilities invokeLater method.
I separated the JFrame construction from the 2 JPanels construction. I used a JFrame, rather than extend a JFrame. The only time you should extend any Java class is if you want to override one or more of the class methods.
I used the same ButtonListener for both JButtons. I'm guessing what you want, but I drew either an "A" or a "B", depending on which button you left clicked.
Let's look at the DrawPanel class.
package com.ggl.drawing;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
private static final long serialVersionUID = 3443814601865936618L;
private GUIModel model;
public DrawPanel(int width, int height, GUIModel model) {
this.setPreferredSize(new Dimension(width, height));
this.model = model;
// add mouse listeners
MouseHandler mouseHandler = new MouseHandler();
this.addMouseListener(mouseHandler);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (model.getCoordinate() != null) {
Point p = model.getCoordinate();
Font font = g.getFont().deriveFont(48F);
g.setFont(font);
g.drawString(model.getDisplayString(), p.x, p.y);
}
}
// class to handle all mouse events
private class MouseHandler extends MouseAdapter {
#Override
public void mousePressed(MouseEvent event) {
model.setCoordinate(event.getPoint());
}
#Override
public void mouseReleased(MouseEvent event) {
DrawPanel.this.repaint();
}
}
}
The major change I made in this class was to use the paintComponent method, rather than the paint method. The paintComponent method is the correct method to override.
I set the size of the drawing panel in the DrawPanel constructor. It's much better to let Swing figure out the size of the JFrame. That's what the pack method in the DrawFrame run method does.
I increased the font size so you can see the drawn letter better.
I removed the mouse motion listener code, as it wasn't needed.
I hope this was helpful to you.
OK, all I know so far is that you want the text displayed in a JPanel to change if a button is pressed. If so, then your code looks to be way too complex for the job. Suggestions include:
Give the DrawingPanel a setter method, say, setText(String text), that allows outside classes to change the text that it displays.
Within that method, set a field of DrawingPanel, say called text, and call repaint().
Override DrawingPanel's paintComponent not its paint method, and call the super's method within your override.
Within the paintComponent method, call drawString to draw the String held by the text field, if the field is not null.
Give your buttons ActionListeners or AbstractActions that call the DrawingPanel's setText(...) method, setting the text to be displayed.
For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class DrawAorB extends JPanel {
private DrawingPanel drawingPanel = new DrawingPanel();
public DrawAorB() {
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
btnPanel.add(new JButton(new ButtonAction("A")));
btnPanel.add(new JButton(new ButtonAction("B")));
setLayout(new BorderLayout());
add(drawingPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
String text = e.getActionCommand();
drawingPanel.setText(text);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawAorB");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawAorB());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class DrawingPanel extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private String text = null;
public void setText(String text) {
this.text = text; // set the JPanel's text
repaint(); // and draw it
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (text != null) {
int x = getWidth() / 2;
int y = getHeight() / 2;
// use FontMetrics if you want to center text better
g.drawString(text, x, y);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
Even simpler, easier, and probably better would be to display the text within a JLabel as it's much easier to center this text.

can you help me with this java program?

I just started using swing and events
what I wanted was a basic program where there is a button in a window and when you click on the button an oval moves around the screen for time,like wanted to be like animated.
This is what I did for it
package testmode;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Ainmationtester implements ActionListener {
JFrame frame;
JButton Button;
int x = 30, y = 30;
Ainmationtester tester = new Ainmationtester();
Ainmationtester.MyDrawPanels test = tester.new MyDrawPanels();
public static void main(String[] args) {
// TODO Auto-generated method stubc
Ainmationtester test = new Ainmationtester();
test.go();
}
public void go() {
frame = new JFrame("Aniamtor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
Button = new JButton("CLick me to Animate");
Button.addActionListener(this);
frame.getContentPane().add(BorderLayout.NORTH, Button);
frame.getContentPane().add(BorderLayout.CENTER, test);
}
public class MyDrawPanels extends JPanel {
public void paintComponent(Graphics g) {
g.fillOval(x, y, 10, 10);
}
}
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < 200; i++){
test.repaint();
x++;
y++;
}
}
}
I wrote an example based on your code.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Ainmationtester implements ActionListener {
JFrame frame;
JButton Button;
int x = 30, y = 30;
MyDrawPanels draw = new MyDrawPanels();
public static void main(String[] args) {
Ainmationtester test = new Ainmationtester();
test.go();
}
public void go() {
frame = new JFrame("Aniamtor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
Button = new JButton("CLick me to Animate");
Button.addActionListener(this);
frame.getContentPane().add(BorderLayout.NORTH, Button);
frame.getContentPane().add(BorderLayout.CENTER, draw);
frame.setVisible(true);
}
public class MyDrawPanels extends JPanel {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
g.fillOval(x, y, 50, 50);
}
}
public void actionPerformed(ActionEvent event) {
x += 5;
y += 5;
frame.repaint();
}
}
The final run screenshot is the following
Hope that helped

Drawing using Graphics in Java

I have a Graphics question. I'm trying to draw an image in a Frame and I'm having some issue. I want to know what's the best approach to successfully do what I want to do.
I will show my 3 classes. The Main class create the Menu. Once Matchmaking button is press, it create the Board object and call Main.draw to paint all it's component (only Board for now). The picture only sometime appear so it make me realise my code isn't probably setup the right way. THANKS!!!
MAIN CLASS
import java.awt.Graphics;
public class Main
{
public static Board theBoard;
public static void main(String[] args)
{
new Menu("Main Menu").setVisible(true);
}
public static void draw(Graphics painter)
{
theBoard.draw(painter);
}
}
MENU CLASS
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Menu extends JFrame implements ActionListener
{
//Jpanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnMatchmaking = new JButton("Matchmaking");
JButton btnExit = new JButton("Exit");
JButton btnProfile = new JButton("Profile");
JButton btnOption = new JButton("Options");
public Menu(String s)
{
super("Bu$ted: " + s);
btnExit.addActionListener(this);
btnMatchmaking.addActionListener(this);
//JPanel setting
pnlButton.add(btnMatchmaking);
pnlButton.add(btnProfile);
pnlButton.add(btnOption);
pnlButton.add(btnExit);
pnlButton.setVisible(true);
//The winddow options
super.setLocation(0,0); //A remplacer par des dimension variables
super.setSize(600, 500); //A remplacer par des dimension variables
super.setResizable(false);
super.setVisible(true);
super.add(pnlButton);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//Handle action events.
//#param evt
#Override
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource() == btnMatchmaking)
{
super.remove(pnlButton);
Main.theBoard = new Board("TestBoard");
super.add(Main.theBoard);
super.setSize(Main.theBoard.boardSize);
Main.draw(super.getGraphics());
}
if(evt.getSource() == btnExit)
{
System.exit(0);
}
}
}
BOARD CLASS
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Board extends JPanel
{
BufferedImage boardImage;
int width;
int height;
Dimension boardSize;
public Board (String boardName)
{
boardImage = loadBoard(boardName);
width=boardImage.getWidth();
height=boardImage.getHeight();
boardSize = new Dimension(width,height);
this.setVisible(true);
System.out.println("The board is setup.");
}
private BufferedImage loadBoard (String boardName)
{
BufferedImage img = null;
try
{
img = ImageIO.read(new File("Components/"+boardName+".png"));
}
catch (IOException e)
{
System.out.println("The board image couldn't be loaded.");
}
return img;
}
public void draw(Graphics painter)
{
painter.drawImage(boardImage, 0, 0, null);
System.out.println("The board image was painted.");
}
}
The recommended approach is to override the paintComponent of your Board class and let the paint system handel it...
See Painting in AWT and Swing and Perfoming Custom Painting for more details

No main() even if main() is there

I added this code to Netbeans and I am getting that file test1 doesn't contain main() function.
I have added main() function but still getting this error:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import net.miginfocom.swing.MigLayout;
public class test1 extends JFrame {
// Window Vars //
String title;
int width;
int height;
// Mid Level componets //
JMenuBar menuBar;
JMenu file;
JToolBar toolBar;
JPanel map;
JPanel sideBar;
// Low Level componets //
JMenuItem exit;
JButton select;
public test1(String title, int width, int height) {
this.title = title;
this.width = width;
this.height = height;
this.makeInterface();
}
public void makeInterface() {
// Setup JFrame
this.setTitle(title);
this.setSize(width, height);
this.setLocationRelativeTo(null);
this.setMinimumSize(new Dimension(700, 500));
this.setVisible(true);
this.setLayout(new MigLayout(
"debug, fillx, gap unrel rel", // Layout
"[grow, fill][fill]", // Column
"[fill][fill]")); // Row
this.makeMenu();
this.addToolBars();
this.makePanels();
this.setupActionListeners();
}
public void makeMenu() {
this.menuBar = new JMenuBar();
this.file = new JMenu("File");
this.file.setMnemonic(KeyEvent.VK_F);
this.menuBar.add(file);
this.exit = new JMenuItem("Exit", KeyEvent.VK_E);
this.exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.ALT_MASK));
this.file.add(exit);
this.setJMenuBar(this.menuBar);
}
public void addToolBars() {
this.toolBar = new JToolBar("Draggable");
this.addToolBarButtons();
this.add(toolBar, "span, height 20:35:50, wrap");
}
public void addToolBarButtons() {
this.select = new JButton("Select");
this.toolBar.add(select);
}
public void makePanels() {
this.map = new JPanel();
this.sideBar = new JPanel();
this.add(map, "width 400:600:, flowy, growy");
this.add(sideBar, "width 250:300:350, flowy, growy");
}
public void setupActionListeners() {
this.exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new test1("r",400,400).setVisible(true);
}
});
}
}
Could someone please find out what the problem is?
The correct signature of main is
public static void main(String[] args)
You main needs as argument (String[] args)
The required arguments are missing from the declaration of your main function.The correct syntax for main is :
public static void main(String args[])
If you are using some IDE like Eclipse. I recommend you to type ma and autocomplete it so that you'll never make any mistake.

Why can this code note be run as a JFrame?

I am trying to make an applet run as a JFrame. The code I have below is simple but should work. It will run as an JApplet but when I go to RUN AS --> nothing appears.
import java.awt.*;
import java.applet.Applet;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LifeCycle extends Applet
{
private static final long serialVersionUID = 1L;
String output = "test";
String event;
public void init()
{
gui(); //I am not certain if this needs to be there.
event = "\nInitializing...";
printOutput();
}
public void start()
{
event = "\nStarting...";
printOutput();
}
public void stop()
{
event = "\nStopping...";
printOutput();
}
public void destroy()
{
event = "\nDestroying...";
printOutput();
}
private void printOutput()
{
System.out.println(event);
output += event;
repaint();
}
private void gui() {
JFrame f = new JFrame("Not resizable");
JPanel d = new JPanel();
// LifeCycle a = new LifeCycle();
// a.init();//not working
d.setLayout(new BorderLayout());
d.add(new JButton("a"));
d.add(new JButton("b"));
d.setBackground(Color.RED);
//f.add(new LifeCycle());
f.add(d);
f.setSize(545,340);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setTitle("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//a.destroy();
}
public void paint(Graphics g)
{
System.out.println("Graphics Paint Method!");
g.drawString(output, 100, 100);
}
public static void main(String[] args) {
LifeCycle l = new LifeCycle();
l.gui();
}
}
I would like to see the code that should be changed, but I cannot seem to find why this will not work. I have added to buttons to the panel to be displayed.
Don't mix AWT (Applet) with Swing components. Stick with just Swing.
Gear your class towards creating JPanels. Then you can place it in a JApplet if you want an applet or a JFrame if you want a JFrame.
Read up on use of BorderLayout -- you're adding multiple components to the default BorderLayout.CENTER position, and only one component, the last one added, will show.
For example ...
LifeCycle2.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
class LifeCycle2 {
private static final int GAP = 5;
private static final int PREF_W = 545;
private static final int PREF_H = 340;
private JPanel mainPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return LifeCycle2.this.getPreferredSize();
}
};
public LifeCycle2() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
buttonPanel.add(new JButton("A"));
buttonPanel.add(new JButton("B"));
buttonPanel.setOpaque(false);
JPanel flowLayoutPanel = new JPanel();
flowLayoutPanel.setOpaque(false);
flowLayoutPanel.add(buttonPanel);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.setBackground(Color.red);
mainPanel.add(flowLayoutPanel, BorderLayout.NORTH);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public JComponent getMainPanel() {
return mainPanel;
}
}
Show as a JFrame,
LifeCycleFrame.java
import javax.swing.*;
public class LifeCycleFrame {
private static void createAndShowGui() {
LifeCycle2 lifeCycle2 = new LifeCycle2();
JFrame frame = new JFrame("LifeCycleTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(lifeCycle2.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Show as an applet,
LifeCycleApplet.java
import java.lang.reflect.InvocationTargetException;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
public class LifeCycleApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
LifeCycle2 lifeCycle2 = new LifeCycle2();
getContentPane().add(lifeCycle2.getMainPanel());
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}
Add f.setVisible(true); to the end of the gui() method. Without this call your frame won't be shown.
Please read the "How to Make Frames" Tutorial

Categories