public main() {
initComponents();
JPanel panel=new JPanel();
panel.setBounds(0, 0, 100, 100);
panel.setBackground(Jtrue);
this.add(panel);
}
I am able to add Jframe object using this command
However, when I write this in a separate method, I cannot add because the 'this' method is inside that object.
public void created(){
int degisken=1;
JPanel panel=new JPanel();
panel.setBounds(0, 0, 100, 100);
panel.setBackground(Jtrue);
this.add(panel);
}
How can I select that jframe instead of 'this'
I don't want to create a new jframe because there is already one
You should create you JFrame instance in a way that it will be visible in your whole class.
You can achieve this by declaring a JFrame as a private member of your class. Then you will be able to access it in all class methods:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JFrameDemo {
private JFrame frame;
public JFrameDemo() {
this.frame=new JFrame("Demo #1");
initComponents();
created();
}
private void initComponents() {
// Do your stuff here
}
public void created() {
int degisken = 1;
JPanel panel = new JPanel();
panel.setBounds(0, 0, 100, 100);
panel.setPreferredSize(new Dimension(640, 480));
panel.setBackground(new Color(255, 128, 112));
this.frame.getContentPane().add(panel);
this.frame.pack();
this.frame.setVisible(true);
}
public static void main(String[] args) {
JFrameDemo frameDemo = new JFrameDemo();
}
}
Another solution is that your class extends JFrame. This way, you will access the JFrame instance using the this keyword because this is your class and thus your JFrame:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JFrameDemo2 extends JFrame {
public JFrameDemo2() {
super("Demo #2");
initComponents();
created();
}
private void initComponents() {
// Do your stuff here
}
public void created() {
int degisken = 1;
JPanel panel = new JPanel();
panel.setBounds(0, 0, 100, 100);
panel.setPreferredSize(new Dimension(640, 480));
panel.setBackground(new Color(255, 128, 112));
this.getContentPane().add(panel);
}
public static void main(String[] args) {
JFrameDemo2 frameDemo = new JFrameDemo2();
frameDemo.pack();
frameDemo.setVisible(true);
}
}
Another remark: don't add your component directly on your JFrame but on the underlying container:
yourFrameInstance.getContentPane().add(yourComponentInstance)
Related
I need to calculate window decorations somehow. So I override JDialog's constructor. But when I call get_decoration_size() it sometimes returns wrong values. And my thought was: window creates later than get_decoration_size() executes(strange, because both in same thread and in same constructor). So I decided to sleep for a second, and it worked, and now decorations always valid.
My question is: is there a way to "join" to the creating process(wait until window is shown by setVisible(true))? If so, it must be something to replace unsafe_sleep(1000).
package swing.window;
import db.db;
import javax.swing.*;
import java.awt.*;
import static swing.util.*;
import static util.util.unsafe_sleep;
public class calc_decor extends JDialog {
{
//some initializations
setLayout(null);
setResizable(false);
JLabel label = new JLabel("Loading...");
add(label);
setxy(label, 3, 3);
fit(label);
setsize(this, label.getWidth() + 100, label.getHeight() + 100);
window_to_center(this);
setVisible(true);//trying to draw
unsafe_sleep(1000);//without that it looks like get_decoratoin_size()
//is called before setVisible(true)
db.sysdecor = get_decoration_size();//trying to get decorations
dispose();
}
private Dimension get_decoration_size() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
I had to assume a lot to create a runnable example.
Here's the result of your getDecorationSize method. The line didn't print until I closed the JDialog.
java.awt.Dimension[width=16,height=39]
And here's the code I used.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JDialogTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTest());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
150, 100, 150, 100));
panel.setPreferredSize(new Dimension(400, 400));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new CalculateDecor(frame, "Spash Screen");
}
}
public class CalculateDecor extends JDialog {
private static final long serialVersionUID = 1L;
public CalculateDecor(JFrame frame, String title) {
super(frame, true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 200));
JLabel label = new JLabel("Loading...");
label.setHorizontalAlignment(JLabel.CENTER);
panel.add(label);
add(panel);
pack();
setLocationRelativeTo(frame);
setVisible(true);
System.out.println(getDecorationSize());
}
private Dimension getDecorationSize() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
}
This is my code and when I execute, all I get is a blank window. First when I tried to do main.setContentPane() I got this error:
"Cannot make a static reference to the non-static field panel"
So i put it in the constructor, but nothing would show.
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 MainFrame extends JFrame{
private JPanel panel;
private JButton performance;
private JButton concordance;
private JButton discordance;
private JButton resultat;
public void MainFrame() {
panel = new JPanel(new GridLayout(4, 1, 10, 10));
performance = new JButton("performance");
concordance = new JButton("concordance");
discordance = new JButton("discordance");
resultat = new JButton("resultat");
performance.setSize(50, 30);
concordance.setSize(50, 30);
discordance.setSize(50, 30);
resultat.setSize(50, 30);
panel.add(performance);
panel.add(concordance);
panel.add(discordance);
panel.add(resultat);
getContentPane().add(panel);
}
public static void main(String[] args) {
MainFrame main = new MainFrame();
main.setSize(300, 200);
main.setDefaultCloseOperation(EXIT_ON_CLOSE);
main.setVisible(true);
}
}
You have a method (returning void) called MainFrame that is never being called.
You should either make that the constructor, or create a constructor that calls that method like so:
public class MainFrame extends JFrame {
private JPanel panel;
private JButton performance;
private JButton concordance;
private JButton discordance;
private JButton resultat;
public MainFrame() {
super();
MainFrame();
}
public void MainFrame() {
panel = new JPanel(new GridLayout(4, 1, 10, 10));
performance = new JButton("performance");
concordance = new JButton("concordance");
discordance = new JButton("discordance");
resultat = new JButton("resultat");
performance.setSize(50, 30);
concordance.setSize(50, 30);
discordance.setSize(50, 30);
resultat.setSize(50, 30);
panel.add(performance);
panel.add(concordance);
panel.add(discordance);
panel.add(resultat);
this.getContentPane().add(panel);
}
public static void main(String[] args) {
MainFrame main = new MainFrame();
main.setSize(300, 200);
main.setDefaultCloseOperation(EXIT_ON_CLOSE);
main.setVisible(true);
main.MainFrame();
}
}
I have written a code that has a label and a button in a frame. I have also changed the background but it never changes.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class Frames
{
JFrame Main_Menu=new JFrame("MAIN MENU");JFrame CIRCUMFERENCE=new JFrame("CIRCUMFERENCE");
JFrame AREA=new JFrame("AREA");JFrame PERIMETER=new JFrame("PERIMETER");JFrame SETS=new JFrame("SETS");
JFrame FUNDAMENTAL_OPRATIONS=new JFrame("FUNDAMENTAL OPRATIONS");JFrame POWER_AND_ROOTS=new JFrame("POWER_AND_ROOTS");
void Main_Menu()
{
JPanel contentPane = (JPanel) Main_Menu.getContentPane();
contentPane.setLayout(new BorderLayout(10,10));
contentPane.setBorder(new EmptyBorder(300, 150, 300, 150));
contentPane.setLayout(new GridLayout(4, 4));
JPanel buttonPanel = new JPanel(new GridLayout(8,8));
contentPane.add(Labels.Main_MENU,BorderLayout.NORTH);
contentPane.add(Buttons.SETS,BorderLayout.SOUTH);
Main_Menu.setBackground(Color.YELLOW);
Main_Menu.pack();
Main_Menu.setVisible(true);
}
}
You should actually be setting the background color of the content pane via getContentPane().setBackground(Color.YELLOW):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Frames extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new Frames();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Frames() {
setSize(new Dimension(100, 100));
setTitle("MAIN MENU");
getContentPane().setBackground(Color.YELLOW);
setVisible(true);
}
}
Also, consider using variable naming conventions; for instance, Main_Menu should be named as mainMenu.
I am new to java, and learning new things everyday.
Today i stumbled upon an error i just can not get fixed.
So i've got a JFrame with a JPanel inside, now I want to remove the Jpanel when i click on my Start game JLabel, and make it transition into my game JPanel ( for now i use a test JPanel)
JFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainMenu extends JFrame {
JPanel panel;
JFrame frame;
JButton playlabel;
public void mainmenu() {
frame = new JFrame();
panel = new JPanel();
playlabel = new JButton ("Nieuw Spel");
//frame
frame.setSize(new Dimension(800, 600));
frame.getContentPane().setBackground(new Color(14,36,69));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(frame.getMinimumSize());
frame.setVisible(true);
//panel
Dimension expectedDimension = new Dimension(690, 540);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setPreferredSize(expectedDimension);
panel.setMaximumSize(expectedDimension);
panel.setMinimumSize(expectedDimension);
panel.setBackground(new Color(14, 36, 69));
panel.add(playlabel);
playlabel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
//playlabel
playlabel.setFont(new Font("Old English Text MT", Font.BOLD, 40));
playlabel.setBounds(250, 350, 50, 20);
playlabel.setForeground(new Color(217,144,39));
playlabel.setBackground(new Color(14,36,69));
playlabel.setBorderPainted(false);
playlabel.setFocusPainted(false);
playlabel.addActionListener(new PlayListener());
}
private class PlayListener extends JFrame implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel panelgame = Game.Game();
this.remove(panel);
this.add(panelgame);
this.revalidate();
}
}
}
Game class:
package labyrinthproject.View;
import java.awt.Color;
import javax.swing.JPanel;
public class Game {
public static JPanel Game(){
JPanel panel = new JPanel();
panel.setSize(690, 540);
panel.setBackground(new Color(255,36,69));
return panel;
}
}
if anyone could explain this to me why this doesn't work, it would be greatly appreciated!
Thank you very much!
Sincerely,
A beginner java student.
There are quite some issues in your code
Create the GUI on the event dispatch thread
Don't extend JFrame (you have three (three!) JFrames floating around there!)
Follow the naming conventions
Don't overuse static methods
Only store the instance variables that you really need to represent your class state
Don't use manual setSize or setBounds calls. Use a LayoutManager instead
The call to frame.setVisible(true) should be the last call, after the frame has been completely assembled
Consider a CardLayout for switching between panels ( http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html )
Slightly cleaned up, but the exact structure depends on what you actually want to achieve at the end:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainMenu extends JPanel
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainMenu = new MainMenu();
mainFrame.getContentPane().add(mainMenu);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
MainMenu()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Dimension expectedDimension = new Dimension(690, 540);
setPreferredSize(expectedDimension);
setBackground(new Color(14, 36, 69));
JButton newGameButton = new JButton ("Nieuw Spel");
newGameButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
newGameButton.setFont(new Font("Old English Text MT", Font.BOLD, 40));
newGameButton.setForeground(new Color(217,144,39));
newGameButton.setBackground(new Color(14,36,69));
newGameButton.setBorderPainted(false);
newGameButton.setFocusPainted(false);
newGameButton.addActionListener(new PlayListener());
add(newGameButton);
}
private class PlayListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
removeAll();
GamePanel gamePanel = new GamePanel();
add(gamePanel);
revalidate();
}
}
}
class GamePanel extends JPanel
{
GamePanel()
{
setBackground(new Color(255,36,69));
}
}
You should use a JButton and not a JLabel. Then:
you add to your JButton : Your_JB.addActionListener(this); (don't forget to implement ActionListener to your class).
Now, we are gonna add the detector:
#Override
public void actionPerformed(ActionEvent e){
Object src = e.getSource();
if(src == Your_JB){
panel.setVisible(false);
}
}
When you click the button, it will make your panel disapear.
Try this:
this.remove(panel);
this.validate();
this.repaint(); //if you use paintComponent
this.add(panelgame);
this.revalidate();
Swing is hard to making nice UI. You just need to use validate() after remove().
I hope it's helpfull.
public class FaceMain extends JFrame {
CreateFace p1 = new CreateFace();
private ControlPanel panel;
public FaceMain(ControlPanel value) {
panel = value;
JFrame main = new JFrame();
main.setTitle("Face Frame");
main.setSize(new Dimension(600, 600));
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
Container c = main.getContentPane();
main.add(p1);
panel.eyesSetE(true);
JFrame control = new JFrame();
control.setTitle("Control Panel");
control.setSize(new Dimension(300, 300));
control.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
control.setLocationRelativeTo(main);
control.setVisible(true);
ControlPanel p2 = new ControlPanel(p1);
control.add(p2);
}
}
public class ControlPanel extends JPanel {
boolean eyesSetEdit = false, faceSetEdit = false, mouthSetEdit = false,
editEyes;
private Color purple = new Color(133, 22, 145);
private CreateFace face;
private CreateFace p1;
public ControlPanel(CreateFace value) {
face = value;
p1 = value;
setLayout(new GridLayout(4, 0));
JButton change = new JButton("Click");
add(change);
JLabel info = new JLabel("Click Above To Change Features",
JLabel.CENTER);
add(info);
JLabel info1 = new JLabel("Slide Below To Change Size", JLabel.CENTER);
add(info1);
JScrollBar slider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 100, 0, 300);
add(slider);
public void eyesSetE(boolean x) {
eyesSetEdit = x;
}
public boolean getEyesSet() {
return eyesSetEdit;
}
I have expanded my class to try and change a boolean value which will be used exstensivly in the ControlPanel class to make decisions however everytime I start the program I get a nullpointerexception at the line "panel.eyesSetE(true);" Even if I try and call getEyesSet() I still recieve a nullpointer
You never change the instance of circle within the CreateCircle class, so it never changes size.
Don't use static for what should be an instance variable, instead make use of the instance of the class you created and provide a setter method to change the variable...
Basically, this example passes the instance of p1 to the ControlPanel pane so that it has some context by which to manipulate what you have previously created.
import datetest.CircleShort.ControlPanel;
import datetest.CircleShort.CreateCircle;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Scrollbar;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
public class CircleShort extends JFrame {
CreateCircle p1 = new CreateCircle();
public CircleShort() {
CreateCircle p1 = new CreateCircle();
JFrame main = new JFrame();
main.setSize(new Dimension(600, 600));
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
Container c = main.getContentPane();
main.add(p1);
JFrame control = new JFrame();
control.setTitle("Control Panel");
control.setSize(new Dimension(300, 300));
control.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
control.setLocationRelativeTo(main);
control.setVisible(true);
ControlPanel p2 = new ControlPanel(p1);
control.add(p2);
}
static class CreateCircle extends JComponent {
int circleX = 100;
Ellipse2D.Double circle;
public CreateCircle() {
circle = new Ellipse2D.Double(circleX, 50, 400, 350);
}
public void setCircleX(int x) {
circleX = x;
circle = new Ellipse2D.Double(circleX, 50, 400, 350);
repaint();
}
public int getCircleX() {
return circleX;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fill(circle);
}
}
class ControlPanel extends JComponent {
private CreateCircle circle;
public ControlPanel(CreateCircle value) {
circle = value;
setLayout(new GridLayout(4, 0));
JButton change = new JButton("Click");
add(change);
JLabel info = new JLabel("Click Above To Change Color",
JLabel.CENTER);
add(info);
JLabel info1 = new JLabel("Slide Below To Change Size",
JLabel.CENTER);
add(info1);
JScrollBar slider = new JScrollBar(Scrollbar.HORIZONTAL, 0, 100, 0,
300);
add(slider);
slider.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println(e.getValue());
circle.setCircleX((circle.getCircleX() + (e.getValue() % 5)));
}
});
}
}
static class CircleRun {
public static void main(String[] args) {
new CircleShort();
}
}
}
static is evil until you truly understand how to use it. If you find yourself making some field or method static just because you can't seem to figure out how to access it, then you are likely doing something wrong, be careful with it...
The next question this actually raises is, "why?"
A JSlider would be a more appropriate control to use and would be conceptually easier for a user to understand