I am making an UI in a minecraft plugin. Everything is working, except I have a JPanel and it doesn't fill the whole JFrame. So what I want is the JPanel fill the entire JFrame even if we re-scale the window.
I use Layout manager (FlowLayout) for the JPanel.
I tried using a Layout manager for the JFrame, well it didn't solved my problem because it didn't resize the JPanel.. I tried setting the size of the JPanel to the JFrame's size, but when it's resized it doesn't scale with it.
So, how can I do this?
My plugin creates a button for every player and when I click the button it kicks the player.
My code (I can't really post less because I don't know where I need to change something):
public static JFrame f;
public static JTextField jtf;
public static JPanel jp;
public static void creategui()
{
System.out.println("GUI created.");
f = new JFrame("Players");
jp = new JPanel();
jp.setLayout(new FlowLayout(FlowLayout.LEFT));
jp.setBackground(Color.GRAY);
jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setSize(new Dimension(200,200));
f.setLayout(null);
f.setSize(500,500);
f.setVisible(true);
jp.add(jtf);f.add(jp, BorderLayout.CENTER);
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
Bukkit.getPlayer(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
jp.add(b);
System.out.println("Button added.");
}
f.add(jp, BorderLayout.CENTER);
}
The question should include an mcve reproducing the problem so we can test it.
It could look like this :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Mcve {
private static List<String> players = Arrays.asList(new String[]{"Player A", "Player B"});
public static void main(String[] args) {
creategui();
}
public static void creategui()
{
JPanel jp = new JPanel();
jp.setBackground(Color.GRAY);
JTextField jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setSize(new Dimension(200,200));
jp.add(jtf);
for (final String p : players)
{
final JButton b = new JButton();
b.setText(p);
b.setBackground(Color.GREEN);
b.addActionListener(e -> {
if (!b.getBackground().equals(Color.RED))
{
b.setBackground(Color.RED);
}
});
jp.add(b);
}
JFrame f = new JFrame("Players");
f.setLayout(null);
f.setSize(500,500);
f.add(jp, BorderLayout.CENTER);
f.setVisible(true);
}
}
To make the JPanel fill the entire frame simply remove this line :
f.setLayout(null);
and let the default BorderLayout manager do its work.
Here is a modified version with some additional comments:
public class Mcve {
private static List<String> players = Arrays.asList(new String[]{"Player A", "Player B"});
public static void main(String[] args) {
creategui();
}
public static void creategui()
{
JPanel jp = new JPanel();
jp.setBackground(Color.GRAY);
JTextField jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setPreferredSize(new Dimension(250,200)); // set preferred size rather than size
jp.add(jtf);
for (final String p : players)
{
final JButton b = new JButton();
b.setText(p);
b.setBackground(Color.GREEN);
b.addActionListener(e -> {
if (!b.getBackground().equals(Color.RED))
{
b.setBackground(Color.RED);
}
});
jp.add(b);
}
JFrame f = new JFrame("Players");
//f.setLayout(null); null layouts are bad practice
//f.setSize(500,500); let layout managers set the sizes
f.add(jp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
A 1x1 grid layout does the job quite nicely.
window = new JFrame();
panel = new JPanel();
window.setLayout(new java.awt.GridLayout(1, 1));
window.add(panel);
Either set the layout manager for jp (the JPanel in the code you posted) to BorderLayout and add jtf (the JTextField in the code you posted) to the CENTER of jp, as in:
f = new JFrame();
jp = new JPanel(new BorderLayout());
jtf = new JTextField(30); // number of columns
jp.add(jtf, BorderLayout.CENTER);
f.add(jp, BorderLayout.CENTER);
or dispense with jp and add jtf directly to f (the JFrame in the code you posted), as in:
f = new JFrame();
jtf = new JTextField(30);
f.add(jtf, BorderLayout.CENTER);
The key is that the CENTER component of BorderLayout expands to fill the available space.
So I fixed it somehow, this is the code:
public static void creategui()
{
System.out.println("GUI created.");
f = new JFrame("Players");
jp = new JPanel();
jp.setBackground(Color.GRAY);
jp.setSize(200,200);
jtf = new JTextField(30);
jtf.setToolTipText("Write the reason here.");
jp.add(jtf);
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
getplr(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
jp.add(b);
System.out.println("Button added.");
}
f.setLayout(new BorderLayout());
f.add(jp, BorderLayout.CENTER);
f.setSize(500,500);
f.pack();
f.setVisible(true);
}
Related
I created two JPanels, one with a JTextField and label and one with a JTextArea. I tried to put them into a JFrame, and when I ran the code all I got was the bar on top of a window with the minimize, enlarge, and close button.
class 1:
public TextListener() {
newText = new TextSource();
jp1 = new JPanel();
stuff = new JTextArea(45, 70);
scroll = new JScrollPane(stuff);
stuff.setEditable(false);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jp1.setLayout(new FlowLayout());
jp1.add(stuff);
jp1.setBackground(Color.YELLOW);
jp1.setVisible(true);
JFrame yo = new JFrame();
yo.add(jp1);
yo.setVisible(true);
}
class 2:
public TextSource() {
jp1 = new JPanel();
tf1 = new JTextField(8);
lb1 = new JLabel("Text Source");
jp1.setLayout(new FlowLayout());
jp1.add(tf1);
jp1.add(lb1);
jp1.setBackground(Color.GREEN);
jp1.setVisible(true);
tf1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newTextFirer(tf1.getText());
}
});
JFrame yo = new JFrame();
yo.add(jp1);
yo.setVisible(true);
}
JFrame class:
public JFrameExt() {
main = new JFrame();
tl1 = new TextListener();
ts1 = new TextSource();
main.setLayout(new FlowLayout());
main.add(tl1);
main.add(ts1);
main.revalidate();
main.repaint();
main.setSize(new Dimension(1000, 900));
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setLocationRelativeTo(null);
main.setVisible(true);
}
I packed the main JFrame after adding the two JPanel's but it still shows just the top bar of a windows page.
Lets start with a little analysis first
In JFrameExt you have...
tl1 = new TextListener();
ts1 = new TextSource();
//...
main.add(tl1);
main.add(ts1)
So, lets have a look at TextListener
public TextListener() {
newText = new TextSource();
jp1 = new JPanel();
stuff = new JTextArea(45, 70);
scroll = new JScrollPane(stuff);
stuff.setEditable(false);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jp1.setLayout(new FlowLayout());
jp1.add(stuff);
jp1.setBackground(Color.YELLOW);
jp1.setVisible(true);
JFrame yo = new JFrame();
yo.add(jp1);
yo.setVisible(true);
}
Okay, assuming that code compiles, we can assume that TextListener is some kind of component, but you never actually add anything to it
Lets have a look at TextSource
public TextSource() {
jp1 = new JPanel();
tf1 = new JTextField(8);
lb1 = new JLabel("Text Source");
jp1.setLayout(new FlowLayout());
jp1.add(tf1);
jp1.add(lb1);
jp1.setBackground(Color.GREEN);
jp1.setVisible(true);
tf1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newTextFirer(tf1.getText());
}
});
JFrame yo = new JFrame();
yo.add(jp1);
yo.setVisible(true);
}
Hmmm, same problem.
So based on these out-of-context snippets of code, you should have three windows, two of which have no defined size
Lets see if we can fix the core problems, lets start with TextListener. Since we can assume TextListener is some kind of component, instead of adding stuff to a new JFrame, simply add it directly to the component itself, for example...
public TextListener() {
newText = new TextSource();
stuff = new JTextArea(45, 70);
scroll = new JScrollPane(stuff);
stuff.setEditable(false);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
setLayout(new FlowLayout());
add(stuff);
setBackground(Color.YELLOW);
}
You'll have to update TextSource in a similar way.
Now back to JFrameExt. You don't need to revalidate or repaint the frame, it's not been realised on the screen, so it's rather useless. setSize is just a bad practice and you should use pack instead, for example...
public JFrameExt() {
main = new JFrame();
tl1 = new TextListener();
ts1 = new TextSource();
main.setLayout(new FlowLayout());
main.add(tl1);
main.add(ts1);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.pack();
main.setLocationRelativeTo(null);
main.setVisible(true);
}
Now, if after you've applied these changes and it doesn't "seem to work", I recommend instead of out-of-context code snippets which require use to make guesses and assumptions, you provide an actually runnable example which demonstrates your problem
Updated with runnable example...
So, I took your code, applied the suggested changes and wrapped into a runnable example ...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextListener tl1 = new TextListener();
TextSource ts1 = new TextSource();
frame.setLayout(new FlowLayout());
frame.add(tl1);
frame.add(ts1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TextListener extends JPanel {
public TextListener() {
JTextArea stuff = new JTextArea(45, 70);
JScrollPane scroll = new JScrollPane(stuff);
stuff.setEditable(false);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
setLayout(new FlowLayout());
add(stuff);
setBackground(Color.YELLOW);
}
}
public class TextSource extends JPanel {
public TextSource() {
JTextField tf1 = new JTextField(8);
JLabel lb1 = new JLabel("Text Source");
setLayout(new FlowLayout());
add(tf1);
add(lb1);
setBackground(Color.GREEN);
}
}
}
I am trying to learn how to use CardLayout instead of multiple JFrames and I am messing around with this code I found on youtube. I tried calling setSize() on all the JPanes but it does not change the size and it remains at the minimum window size. Is the reason I can't set the size because of this line of code: "panelCont.setLayout(cl);" ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CLayout {
JFrame frame = new JFrame("CardLayout");
JPanel panelCont = new JPanel();
JPanel panelFirst = new JPanel();
JPanel panelSecond = new JPanel();
JButton buttonOne = new JButton("Switch to second panel");
JButton buttonSecond = new JButton("Switch to first panel");
CardLayout cl = new CardLayout();
public CLayout() {
panelCont.setLayout(cl);
panelFirst.add(buttonOne);
panelSecond.add(buttonSecond);
panelFirst.setBackground(Color.BLUE);
panelSecond.setBackground(Color.GREEN);
panelCont.add(panelFirst, "1");
panelCont.add(panelSecond, "2");
cl.show(panelCont, "1");
buttonOne.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(panelCont, "2");
}
});
buttonSecond.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(panelCont, "1");
}
});
frame.add(panelCont);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CLayout();
}
});
}
}
Yes, it's for CardLayout but also it's possible to do resize. You can nest your JPanels for instance. or use something like this :
Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class MultiSizedPanels {
private static void createAndShowUI() {
final CardLayout cardLayout = new CardLayout();
final JPanel cardHolder = new JPanel(cardLayout);
JLabel[] labels = {
new JLabel("Small Label", SwingConstants.CENTER),
new JLabel("Medium Label", SwingConstants.CENTER),
new JLabel("Large Label", SwingConstants.CENTER)};
for (int i = 0; i < labels.length; i++) {
int padding = 50;
Dimension size = labels[i].getPreferredSize();
size = new Dimension(size.width + 2 * (i + 1) * padding, size.height + 2 * (i + 1) * padding);
labels[i].setPreferredSize(size);
Border lineBorder = BorderFactory.createLineBorder(Color.blue);
labels[i].setBorder(lineBorder);
JPanel containerPanel = new JPanel(new GridBagLayout());
containerPanel.add(labels[i]);
cardHolder.add(containerPanel, String.valueOf(i));
}
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.next(cardHolder);
}
});
JPanel btnHolder = new JPanel();
btnHolder.add(nextButton);
JFrame frame = new JFrame("MultiSizedPanels");
frame.getContentPane().add(cardHolder, BorderLayout.CENTER);
frame.getContentPane().add(btnHolder, BorderLayout.SOUTH);
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();
}
});
}
}
Where component (here a JLabel rather than a JPanel) has it's preferredSize set, then place it in another JPanel.
I hope this helps you.
I have constructed a class for the JPanel with several JButtons.Inside this class I want to construct another JPanel with JLabels that will change depending on the actionPerformed on the JButtons of the first JPanel.Finally, I want to add these 2 panels on the same Jframe. Can all these be done within the class of the first Panel?Otherwise, which is a better approach for this problem?
Yes, you can. One way you could accomplish this is with anonymous inner classes (saves keystrokes):
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
public class Foo {
JLabel one;
JLabel two;
public static void main(String[] args) {
(new Foo()).go();
}
public void go() {
JFrame frame = new JFrame("Test");
// Panel with buttons
JPanel buttonPanel = new JPanel();
JButton changeOne = new JButton("Change One");
changeOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
one.setText("New text for one");
}
}
buttonPanel.add(changeOne);
JButton changeTwo = new JButton("Change Two");
changeTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
two.setText("New text for two");
}
}
buttonPanel.add(changeTwo);
frame.add(buttonPanel, BorderLayout.NORTH);
// Panel with labels
JPanel labelPanel = new JLabel();
one = new JLabel("One");
labelPanel.add(one);
two = new JLabel("Two");
labelPanel.add(two);
// Set up the frame
frame.add(labelPanel, BorderLayout.SOUTH);
frame.setBounds(50, 50, 500, 500);
frame.setDefaultCloseAction(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Please take a look at the following code (I've missed the imports purposely)
public class MainFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 11, 414, 240);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
panel.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent arg0) {
System.out.println("lost");
// I want to do something here, if I reach here!
}
#Override
public void focusGained(FocusEvent arg0) {
System.out.println("gained");
// I want to do something here, if I reach here!
}
});
tabbedPane.addTab("New tab", null, panel, null);
JButton button = new JButton("New button");
panel.add(button);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("New tab", null, panel_1, null);
JPanel panel_2 = new JPanel();
tabbedPane.addTab("New tab", null, panel_2, null);
}
}
I've created this class to test it and then add the onFocusListener in my main code, but it's not working the way I expect. Please tell what's wrong or is this the right EvenetListener at all?
JPanels are not focusable by default. If you ever wanted to use a FocusListener on them, you'd first have to change this property via setFocusable(true).
But even if you do this, a FocusListener is not what you want.
Instead I'd look to listen to the JTabbedPane's model for changes. It uses a SingleSelectionModel, and you can add a ChangeListener to this model, listen for changes, check the component that is currently being displayed and if your component, react.
You are using setBounds and null layouts, something that you will want to avoid doing if you are planning on creating and maintaining anything more than a toy Swing program.
Edit
For example:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.*;
#SuppressWarnings("serial")
public class MainPanel extends JPanel {
private static final int PREF_W = 450;
private static final int PREF_H = 300;
private static final int GAP = 5;
private static final int TAB_COUNT = 5;
private JTabbedPane tabbedPane = new JTabbedPane();
public MainPanel() {
for (int i = 0; i < TAB_COUNT; i++) {
JPanel panel = new JPanel();
panel.add(new JButton("Button " + (i + 1)));
panel.setName("Panel " + (i + 1));
tabbedPane.add(panel.getName(), panel);
}
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(tabbedPane, BorderLayout.CENTER);
tabbedPane.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent evt) {
Component component = tabbedPane.getSelectedComponent();
System.out.println("Component Selected: " + component.getName());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
MainPanel mainPanel = new MainPanel();
JFrame frame = new JFrame("MainPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
JPanel is a lightweight container and it is not a Actionable component so it does not get focus events. It lets you add focus listener because of swing component hierarchy. In Order to get tab selected events you need to use JTabbedPane#addChangeListener.
Hope this helps.
I have simple problem as I am not much familiar with Java GUI. I am trying to make visible the JLable on the below code as I find it hard to understand the concept. But still label is not visible but the frame do open on run time.
public class Sample extends JPanel {
public void Sample() {
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Sample());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
You are forgot to add panel p to sample. Either use add(p) at the end or just remove panel p cause your sample class is extending JPanel.
Option 1:
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
add(p);
option 2:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
setLayout(new FlowLayout());
add(lab1 = new JLabel("add JLabel"));
Also why are you overriding initialization of JLabel? In your code JLable will always hold value "add JLabel". If you want to see "User Name" then use this add(lab1); instead of add(lab1 = new JLabel("add JLabel"));.
May be you just require this:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
setLayout(new FlowLayout());
add(lab1);
Also constructor can not have return type so remove void from your constructor.
The constructor that you are using is not a proper constructor .. A java constructor does not have a return type and the void is extra. When in the main method you are calling new Sample() it is not actually calling your method but the default constructor that exists by default.
Try like this ..
public Sample() {
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
}
also you need to do what #Harry Joy suggested to add the add(p); statement otherwise the panel is still not added.
Note the comments.
import java.awt.*;
import javax.swing.*;
public class Sample extends JPanel {
public Sample() {
// set the layout in the constructor
super(new FlowLayout(FlowLayout.LEADING));
// best not to set size OR preferred size!
setPreferredSize( new Dimension(200,200) );
JLabel lab1 = new JLabel("User Name");
add(lab1);
}
public static void main(String[] args) {
// construct the GUI on the EDT
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame("User Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Sample());
// important!
frame.pack();
frame.setVisible(true);
}
});
}
}
Note also, that it is generally not considered a good idea to extend a component unless adding custom functionality. That would mean (for example) defining new methods for the Sample panel (Which might better be labelled a UserDetails or UserDetailsContainer if I guess correctly where you are going with that code..). Or it might be a Login component..
Sample is the Jpanel.
Sample extends JPanel means you inherit from JPanel.
just drop JPanel p and all your "p."s
#SuppressWarnings("serial")
public class MyGui extends JFrame{
private MyContentPane myContentPane = new MyContentPane();
public MyGui(){
super("title");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(myContentPane);
this.createMenu();
this.pack();
this.setVisible(true);
}
private void createMenu(){
JMenuBar myMenuBar = new JMenuBar();
JMenu xMenu = new JMenu("x");
JMenu x = new JMenu("x");
JMenuItem xItem = new JMenuItem("letter");
JMenuItem exitItem = new JMenuItem("exit");
xItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
myContentPane.xPanel();
}
});
xItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
myContentPane.setxPanel();
}
});
exitItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
displayMenu.add(letterItem);
displayMenu.add(colorItem);
fileMenu.add(exitItem);
myMenuBar.add(displayMenu);
myMenuBar.add(fileMenu);
this.setJMenuBar(myMenuBar);
}
}