Adding JApplet into JFrame - java

I am trying to view a JApplet within a JFrame.
Class: Paint
public void paint(Graphics g) {
g.drawString("hi", 50, 50);
}
public static void main(String args[]) {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(methodThatReturnsJMenuBar());
JPanel panel = new JPanel(new BorderLayout());
frame.add(panel);
JApplet applet = new Paint();
panel.add(applet, BorderLayout.CENTER);
applet.init();
frame.pack();
frame.setVisible(true);
}
The applet shows up in the Window, but there is no background (it's transparent), and when I click on the Menu, the list is covered. How do I make it so that the Menu list isn't covered, and there is a background?
Edit: When I draw a white rectangle, it fixes the background problem, but the Menu list is still covered.

I would gear my GUI creation towards making a JPanel and then use the JPanel as I desire, either in an JApplet or a JFrame. For e.g.,
import java.awt.*;
import javax.swing.*;
public class MyPanel extends JPanel {
private static final Dimension PREF_SIZE = new Dimension(400, 300);
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("hi", 50, 50);
}
#Override
public Dimension getPreferredSize() {
return PREF_SIZE;
}
public JMenuBar methodThatReturnsJMenuBar() {
JMenu menu = new JMenu("Menu");
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
}
Then to use in an applet:
import javax.swing.JApplet;
public class MyApplet extends JApplet {
public void init() {
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't successfully complete");
}
}
private void createGUI() {
getContentPane().add(new MyPanel());
}
}
Or in a JFrame:
import javax.swing.JFrame;
public class MyStandAlone {
private static void createAndShowUI() {
MyPanel myPanel = new MyPanel();
JFrame frame = new JFrame("MyPanel");
frame.getContentPane().add(myPanel);
frame.setJMenuBar(myPanel.methodThatReturnsJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Related

java GUI set cardlayout frame size

So I am trying to learn how to use card layout and in this sample code I would like to change the size of the frame to a certain size but using setSize does not work.
the following also does not work in the when added to createAndShowGui() function
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setPreferredSize(new Dimension(500,200));
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MainGui2 extends JPanel {
private CardLayout cardLayout = new CardLayout();
private WelcomePanel welcomePanel = new WelcomePanel(this);
private HomePanel homePanel = new HomePanel();
public MainGui2() {
setLayout(cardLayout);
add(welcomePanel, WelcomePanel.NAME);
add(homePanel, HomePanel.NAME);
}
public void showCard(String name) {
cardLayout.show(this, name);
}
private static void createAndShowGui() {
MainGui2 mainPanel = new MainGui2();
JFrame frame = new JFrame("MainGui2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
//frame.pack();
frame.setSize(550, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class WelcomePanel extends JPanel {
public static final String NAME = "welcome panel";
private MainGui2 mainGui2;
public WelcomePanel(final MainGui2 mainGui2) {
this.mainGui2 = mainGui2;
add(new JLabel(NAME));
add(new JButton(new AbstractAction("Logon") {
#Override
public void actionPerformed(ActionEvent e) {
mainGui2.showCard(HomePanel.NAME);
}
}));
}
}
class HomePanel extends JPanel {
public static final String NAME = "home panel";
public HomePanel() {
add(new JLabel(NAME));
}
}
I would like to change the size of the frame to a certain size
Don't try to hard code frame sizes.
If you want extra space around the panels then in the constructor of your MainGui2 class you can add:
setBorder( new EmptyBorder(50, 50, 50, 50) );
This will adjust the preferred size of the panel and this size will now be taken into account when the pack() method is used.

java GUI Form open other form onclick button

I am trying to do when clicked button from form1 open form2. Its sounds very simple but i coudnt find any way to do this.I am using java intellij.
When i use netbeans and swing i was doing this with :
"Form2 form2=new Form2();
form2.setVisible(true);
dispose(); "
Form1(Main):
public class Main {
private JButton b_show;
private JButton b_Add;
private JPanel jp_main;
public Main() {
b_show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
}
});
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Main().jp_main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
form2(Show):
public class Show {
private JButton b_back;
public JPanel jpanelmain;
public Show() {
Show show=new Show();
geriButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
}
});
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Show().jpanelmain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
is any one can help me ?
when click b_show open form2(Show).
Here is an mcve demonstrating it
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
private final JButton b_show;
private final JPanel jp_main;
public Main() {
jp_main = new JPanel();
b_show = new JButton("Show");
b_show.addActionListener(actionEvent -> {
new Show();
});
jp_main.add(b_show);
}
public static void main(String[]args){
JFrame frame=new JFrame();
frame.setContentPane(new Main().jp_main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
class Show {
private JButton b_back;
public JPanel jpanelmain;
public Show() {
createAndShowGui();
}
void createAndShowGui(){
JFrame frame=new JFrame();
frame.setLocationRelativeTo(null);
jpanelmain = new JPanel();
b_back = new JButton("Back");
jpanelmain.add(b_back);
frame.setContentPane(jpanelmain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
However, please read The Use of Multiple JFrames: Good or Bad Practice?
The best way to do this would be using JDialogs. When actionPerformed() at 'Form1' is called, you would instantiate a new JDialog and set him visible. Here is an example:
public class Show extends JDialog {
private JButton b_back;
public JPanel jpanelmain;
public Show(Frame owner, boolean modal) {
super(owner, modal);
}
//method that creates the GUI
}
b_show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
Show show = new Show(JOptionPane.getFrameForComponent(this), true);
show.setVisible(true);
}
});
Finally, when you want to close the dialog, implement an actionPerformed() in it, and call the dispose() method

Initiate a JPanel from a separate class (beginner)

I try to buid JPanels in a separate class to invoke them separately and add different items on it. Please can you tell me what i am doing wrong?
MyFrame.java
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setVisible(true);
}
public MyFrame() {
setTitle("MyFrame");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
JButton testButton = new JButton("Test");
panel.add(testButton);
}
}
MyPanel.java
import javax.swing.*;
import java.awt.*;
class MyPanel extends JPanel {
public MyPanel() {
this.setOpaque(true);
this.setVisible(true);
}
}
You're not adding your panel variable to your JFrame's contentPane.
Add:
public MyFrame() {
setTitle("MyFrame");
// setSize(300, 200); // let's avoid this
setDefaultCloseOperation(EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
JButton testButton = new JButton("Test");
panel.add(testButton);
add(panel); // *** here
pack(); // this tells the layout managers to do their thing
setLocationRelativeTo(null);
setVisible(true);
}
As a side note:
public MyPanel() {
this.setOpaque(true);
this.setVisible(true);
}
JPanels are opaque and visible by default, so your method calls within the MyPanel constructor do nothing useful.
Side note 2: I rarely if ever extend JFrame or any other top level window (with the exception of JApplet if I'm forced to use one of these), since I rarely change the innate behavior of the window. Better I think to create my top level windows (i.e., my JFrames) when needed.
Side note 3: Always strive to start your Swing GUI's on the Swing event thread. So do...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame frame = new MyFrame();
frame.setVisible(true);
}
});
}
Edit
You ask:
You wrote lets avoid setting the size.. can you tell me how i can pack it but set a minimum frame size?
I like to override the JPanel's getPreferredSize() method, and have it return a Dimension that makes sense.
For example, you could do something like this to be sure that your GUI is at lest PREF_W by PREF_H in size:
import java.awt.Dimension;
import javax.swing.*;
public class ShowGetPreferredSize extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int w = Math.max(superSize.width, PREF_W);
int h = Math.max(superSize.height, PREF_H);
return new Dimension(w, h);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ShowGetPreferredSize");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new ShowGetPreferredSize());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Java how to put a button on border/surround of window or JFrame

How do I put a button on the border that surrounds the frame like this cog:
_"Is the a short example anywhere? "
Yea, here... This very basic. You need to do alot more to it. You'll notice I have to add a MouseMotionListener to the JPanel that acts as the top frame border, because when you remove the decoration from the frame, you're also taking away that functionality. So the MouseMotionListener makes the frame draggable again.
You would also have to implement resizing if you wished. I already implemented the Systemexit()` when you press the image. Test it out. You need to provide your own image.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class UndecoratedExample {
static JFrame frame = new JFrame();
static class MainPanel extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
static class BorderPanel extends JPanel {
JLabel stackLabel;
int pX, pY;
public BorderPanel() {
ImageIcon icon = new ImageIcon(getClass().getResource(
"/resources/stackoverflow1.png"));
stackLabel = new JLabel();
stackLabel.setIcon(icon);
setBackground(Color.black);
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(stackLabel);
stackLabel.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
System.exit(0);
}
});
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// Get x,y and store them
pX = me.getX();
pY = me.getY();
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent me) {
frame.setLocation(frame.getLocation().x + me.getX() - pX,
frame.getLocation().y + me.getY() - pY);
}
});
}
}
static class OutsidePanel extends JPanel {
public OutsidePanel() {
setLayout(new BorderLayout());
add(new MainPanel(), BorderLayout.CENTER);
add(new BorderPanel(), BorderLayout.PAGE_START);
setBorder(new LineBorder(Color.BLACK, 5));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setUndecorated(true);
frame.add(new OutsidePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

rectangular component disappears upon resizing the frame

I have a following code ( trying to learn swing and java). I created a ladder using rectangular components using class and placed on the main frame. Everything works okay but if I resize it even slightly, the ShapeManager object (i.e, the ladder) disappears. I don't know what is going on. Any help please.
GUIMain Class:
package mainProg;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.awt.*;
public class GUIMain {
static JPanel mainPanel;
static JButton[] newButtons;
static ShapeManager newShape;
private static class BtnEvtHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
//System.exit(0);
JOptionPane.showMessageDialog( null, "WELCOME" );
}
}
private static JButton[] createButtons() {
JButton[] buttonArray= new JButton[2];
buttonArray[0]=new JButton("OK");
buttonArray[1]=new JButton("MOVE");
BtnEvtHandler okButtonHandler= new BtnEvtHandler();
( buttonArray[0]).addActionListener(okButtonHandler);
return buttonArray;
}
private static ShapeManager createShape(int x) {
ShapeManager newContent=new ShapeManager(x);
return newContent;
}
private static JPanel mainContainer() {
JPanel mainPanel= new JPanel();
mainPanel.setSize(400, 400);
return mainPanel;
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(false);
JFrame frame = new JFrame(" DB ");
mainPanel= mainContainer();
mainPanel.setLayout(new BorderLayout(10, 10));
newButtons= createButtons();
newShape= createShape(20);
newButtons[0].setHorizontalAlignment(0);
mainPanel.add(newButtons[0],BorderLayout.PAGE_START);
newButtons[1].setHorizontalAlignment(0);
mainPanel.add(newButtons[1],BorderLayout.PAGE_END);
newShape.setPreferredSize(new Dimension(400, 400));
mainPanel.add(newShape, BorderLayout.LINE_END);
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocation(500,200);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
ShapeManager Class:
package mainProg;
import javax.swing.JPanel;
import java.awt.*;
#SuppressWarnings("serial")
class ShapeManager extends JPanel {
int rectPos;
ShapeManager(int rectPos) {
setPreferredSize(new Dimension(400,400));
this.rectPos=rectPos;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
while (rectPos<150) {
g.setColor(Color.BLUE);
g.drawRect(rectPos+10, rectPos+10, 100, 10);
g.fillRect(rectPos+10, rectPos+10, 100, 10);
rectPos=rectPos+10;
}
}
}
You never reset rectangle position, so after the first paint it remains above 150. You need to reset it after you exit your while loop.
Try this:
g.setColor(Color.BLUE);
int position = rectPos;
while (position<150) {
position += 10;
g.drawRect(position, position, 100, 10);
g.fillRect(position, position, 100, 10);
}

Categories

Resources