Could you tell me please, why components like JPanel etc. are not visible when added to a JFrame? Here is my code:
public class GUI{
static JPanel panel = new JPanel();
private void createAndShowGUI() {
final ImageIcon zielonaikona = new ImageIcon("kulazielona.png");
JFrame frame1 = new JFrame("MasterMind");
JRadioButton zielony = new JRadioButton(zielonaikona);
zielony.setSelected(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton akceptuj = new JButton("Akceptuj");
akceptuj.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JLabel label2 = new JLabel(zielonaikona);
panel.add(label2);
}
});
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.add(akceptuj);
panel.setLayout(layout);
panel.add(zielony);
JLabel label = new JLabel (zielonaikona);
panel.add(label);
frame1.getContentPane().add(panel);
frame1.getContentPane().add(akceptuj);
frame1.getContentPane().add(zielony);
frame1.setSize(200, 300);
frame1.setVisible(true);
}
public static void main(String[] args) {
GUI kk = new GUI();
kk.createAndShowGUI();
}
}
You add your controls to the JFrame as well as the JPanel panel, so they will only appear in the last container to which they were added, namely the frame. Also because you add them in the default BorderLayout.CENTER position each one displaces the last so you are only left with one component displayed (the JRadioButton zielony)
To fix, remove the lines:
frame1.getContentPane().add(akceptuj);
frame1.getContentPane().add(zielony);
Aside: When adding new components on the fly (i.e. the JLabel added in the ActionListener), don't forget to call:
panel.revalidate();
panel.repaint();
The button and the radio button are added twice, to the panel and to the frame. You didn't set the layout on the frame but I think it has a default one. I just don't remember what kind.
Here is your code that is wrong.
panel.add(akceptuj);
panel.add(zielony);
and
frame1.getContentPane().add(akceptuj);
frame1.getContentPane().add(zielony);
Related
I have read many subjects here but I can't make my window with the layout I want.
I simply want all my graphic object to be in a row style like in the first picture here : http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
I've tried GridLayout but it still make my first button giant and then, as I add textfields, it's getting smaller and smaller?!
Here is my code without all the imports:
public class TestScrollPane extends JFrame implements ActionListener{
Dimension dim = new Dimension(200 , 50);
JButton button;
JPanel panel = new JPanel();
JScrollPane scrollpane = new JScrollPane(panel);
public TestScrollPane(){
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.add(scrollpane);
//panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
this.setSize(300, 400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
button = new JButton("click me");
button.setPreferredSize(dim);
panel.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == button ){
JTextField txt = new JTextField(); // we add a new button
txt.setPreferredSize(dim);
panel.add(txt);
SwingUtilities.updateComponentTreeUI(this); // refresh jframe
}
}
public static void main(String[] args){
TestScrollPane test = new TestScrollPane();
}
}
I just want to have one button per row.
A BoxLayout will respect the minimum/maximum sizes of a component.
For some reason the maximum height of a text field is unlimited so the text field gets all the space available.
So you can do something like:
JTextField txt = new JTextField(10); // we add a new button
//txt.setPreferredSize(dim); // don't hardcode a preferrd size of a component.
txt.setMaximumSize(txt.getPreferredSize());
Also:
//SwingUtilities.updateComponentTreeUI(this); // refresh jframe
Don't use the above method. That is used for a LAF change.
Instead when you add/remove components from a visible GUI you should use:
panel.revalidate();
panel.repaint();
I am trying to implement JTabbedPane. In the following code I have presented a case very similar to what I want to implement. I have created a tab by adding a JPanel to the JTabbedPane. I have added a JButton and JScrollPane to the JPanel. On click of the JButton I want to add a new JPanel having some JRadioButtons to the JScrollPane. But these are not shown even after refreshing the JScrollPane or main JPanel. Please help. The code is given below.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Test {
static JFrame frame;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("DynamicTreeDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tp = new JTabbedPane();
final JScrollPane jsp = new JScrollPane();
JPanel jp = new JPanel();
JButton jb = new JButton("Refresh");
jb.setActionCommand("Show");
jb.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equalsIgnoreCase("Show")){
JRadioButton jrb1 = new JRadioButton("First Option");
JRadioButton jrb2 = new JRadioButton("Second Option");
JRadioButton jrb3 = new JRadioButton("Third Option");
ButtonGroup bg = new ButtonGroup();
bg.add(jrb1);
bg.add(jrb2);
bg.add(jrb3);
JPanel p = new JPanel(new GridLayout(0,1));
p.add(jrb1);
p.add(jrb2);
p.add(jrb3);
jsp.add(p);
jsp.revalidate();
jsp.repaint();
}
}
});
jp.setLayout(new GridLayout(0,1));
jp.add(jb);
jp.add(jsp);
tp.add("First Tab", jp);
frame.getContentPane().add(tp);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
To add something to JScrollPane use its JViewport rather than directly calling add(). In your example replace:
jsp.add(p);
with:
jsp.getViewport().add(p);
Alternatively, initialize JScrollPane with a JPanel that holds other components. Based on your example:
final JPanel panel = new JPanel();
final JScrollPane jsp = new JScrollPane(panel);
panel.add(new JRadioButton("First Option"));
panel.add(new JRadioButton("Second Option"));
panel.add(new JRadioButton("Third Option"));
See How to Use Scroll Panes for more details.
The components should be added to the JPanel called jp rather than directly to the scroll pane.
JScrollPane only works with a single "View". You cannot add components to the scrollPane. If you want, you can change the "View" using setViewPortView(). To achieve the behaviour you are looking for, do the following:
JPanel centralView = new JPanel();
// possibly configure that central view with appropriate layout and other stuffs
JScrollPane jsp = new JScrollPane(centralView);
...
// Now you can add your components to centralView instead of your jsp.add(...) calls.
You should add the JPanel to the JScollPanes viewport using getViewport(), then repack the JFrame to get the sizing issue sorted using pack();:
jsp.getViewport().add(p);
frame.pack();
instead of:
jsp.add(p);
jsp.revalidate();
jsp.repaint();
I have a JFrame and a Jpanel over that in which various buttons are placed.so on click of a button I have called a new class which is also having containers placed in a Jpanel.so I want to show that new class panel over the main Jframe panel.How can I do that?
And if we use card layout in it then how can i use that as on click button i have called an object of a new class.
as
Card layout consider each component in a container as card and i want whole Jpanel as a card so is it possible to do that???
Can We do nesting of Jpanels in it?
Please suggest me a right way to do that?
here is SSCCE:
// this is the main class on which i want to use panel of other class
public class mymain
{
JFrame jframe = new JFrame();
JPanel panel = new JPanel();
BorderLayout borderlayout = new BorderLayout();
public mymain()
{
jframe.setLayout(borderlayout);
JMenuBar menubar = new JMenuBar();
jframe.setJMenuBar(menubar);
JButton home_button = new JButton("HOME");
menubar.add(home_button);
jframe.getContentPane().add(panel,BorderLayout.CENTER);
panel.setLayout(new GridBagLayout());
//here used containers over that frame
and call it from main()
}
here is another class to manage category is
public class manageCategory
{
JPanel panel = new JPanel();
GridBagLayout gridbglayout = new GridBagLayout();
GridBagConstraints gridbgconstraint = new GridBagConstraints();
public manageCategory()
{
panel.setLayout(new BorderLayout());
// i have again here used containers placed with grid bag layout
}
}
So now i want that as i click on home button used in mymain class then the panel that is used in manageCategory() should be displayed on the same panel.and when i again click on home button then the mymain panel get displayed.how can i do that???
I would advise you to use a CardLayout for this task.
Updated example with JPanel and "classes":
static class MainPanel extends JPanel {
public MainPanel(final Container frame) {
add(new JButton(new AbstractAction("Click to view next") {
#Override
public void actionPerformed(ActionEvent e) {
frame.add(new NextPanel(), "NextPanel");
((CardLayout) frame.getLayout()).show(frame, "NextPanel");
}
}));
}
}
static class NextPanel extends JPanel {
public NextPanel() {
add(new JLabel("Next page in the card layout"));
}
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Test");
frame.setLayout(new CardLayout());
frame.add(new MainPanel(frame.getContentPane()), "MainPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
CardLayout is one of possible ways, but there are another options valid or required by most completed GUI
1) BorderLayout, because there only one JComponent can occupate decision area
someContainer.add(myPanel, BorderLayout.CENTER)
revalidate();
repaint();
2) GridBagLayout
before anything you have to get declared GridBagConstraints from myOldComponent layed by GridBagLayout
myContainer.setVisible(myOldComponent);
//or
myContainer.remove(myOldComponent);
myContainer.add(myNewComponent, gbc);
revalidate();
repaint();
You can
JFrame myFrame = new JFrame();
JPanel panel1 = new JPanel();
Panel1.setVisible(true);
myFrame.add(panel1);
JPanel panel2 = new JPanel();
Panel2.setVisible(false);
myFrame.add(panel2);
//Here you setup your panels and your actionlisteners etc and when
//you wish for your second panel to show up just run the code below.
panel1.setVisible(false);
panel2.setVisible(true);
Obviously you first have to add both panels to your Jframe. Panel1 will be at first visible, as it is the one shown by default. Panel2 must be set to be invisible in the beginning.
Right, I have a JTabbedPane that has a JPanel that contains a JLabel and a JTextField.
my code
JTabbed Pane declaration :
this.tabPane = new JTabbedPane();
this.tabPane.setSize(750, 50);
this.tabPane.setLocation(10, 10);
tabPane.setSize(750,450);
tabPane.add("ControlPanel",controlPanel);
textfield declaration :
this.channelTxtFld = new JTextField("");
this.channelTxtFld.setFont(this.indentedFont);
this.channelTxtFld.setSize(200, 30);
this.channelTxtFld.setLocation(200, 10);
JLabel :
this.channelLabel = new JLabel("Channel name : ");
this.channelLabel.setSize(150, 30);
this.channelLabel.setLocation(10,10);
private void createPanels() {
controlPanel = new JPanel();
controlPanel.setSize(650,500);
}
private void fillPanels() {
controlPanel.add(channelLabel);
controlPanel.add(channelTxtFld);
}
So what my plan is, was to have a tabbed pane that has a JPanel where I have some Labels, textfields and buttons on fixed positions, but after doing this this is my result:
http://i.stack.imgur.com/vXa68.png
What I wanted was that I had the JLabel and next to it a full grown JTextfield on the left side not in the middle.
Anyone any idea what my mistake is ?
thank you :)
What kind of Layout Manager are you using for your controlPanel, you probably want BorderLayout, putting the Label in the West, and the TextField in the center.
BTW, setting the size and position of various components doesn't make sense unless you are using a Null Layout, which isn't a good idea. So i'd remove all that stuff and let the Layout Manager do it for you.
Use a LayoutManager and consider also the methods setPreferredSize, setMinimumSize, setMaximumSize to adjust components bounds according on which is your desired effect.
Assuming the default JPanel layout, FlowLayout, give the JTextField a non-zero number of columns, and give the JLabel a JLabel.LEFT constraint.
Addendum:
a full grown JTextField
Something like this?
import java.awt.*;
import javax.swing.*;
/**
* #see http://stackoverflow.com/questions/5773874
*/
public class JTabbedText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
private final JTabbedPane jtp = new JTabbedPane();
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtp.setPreferredSize(new Dimension(400, 200));
jtp.addTab("Control", new MyPanel("Channel"));
f.add(jtp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
private static class MyPanel extends JPanel {
private final JLabel label = new JLabel("", JLabel.LEFT);
private final JTextField text = new JTextField();
public MyPanel(String name) {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
label.setText(name);
label.setAlignmentY(JLabel.TOP_ALIGNMENT);
text.setAlignmentY(JTextField.TOP_ALIGNMENT);
this.add(label);
this.add(text);
}
}
}
I have a class that extends a JPanel called Row. I have a bunch of Row added to a JLabel, the code is the following:
JFrame f=new JFrame();
JPanel rowPanel = new JPanel();
//southReviewPanel.setPreferredSize(new Dimension(400,130));
rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.Y_AXIS));
rowPanel.add(test1);
rowPanel.add(test1);
rowPanel.add(test2);
rowPanel.add(test3);
rowPanel.add(test4);
rowPanel.setPreferredSize(new Dimension(600, 400));
rowPanel.setMaximumSize(rowPanel.getPreferredSize());
rowPanel.setMinimumSize(rowPanel.getPreferredSize());
f.setSize(new Dimension(300,600));
JScrollPane sp = new JScrollPane(rowPanel);
sp.setSize(new Dimension(300,600));
f.add(sp);
f.setVisible(true);
where test1...etc is a Row. However when I resize the window the layout of the Row somehow becomes messy (it resizes as well)... how can I prevent this from happening?
Read the Swing tutorial on Using Layout Managers. Each layout manager has its own rules about what happens when the container is resized. Experiment and play.
In the case of a BoxLayout it should respect the maximum size of the components added to the panel so you can do:
childPanel.setMaximumSize( childPanel.getPreferredSize() );
If you need more help post your SSCCE demonstrating the problem.
I took the code in http://download.oracle.com/javase/tutorial/uiswing/examples/layout/BoxLayoutDemoProject/src/layout/BoxLayoutDemo.java and adapted it with what you are trying to do, only using buttons instead of custom JPanels:
public class BoxLayoutDemo {
public static void addComponentsToPane(Container pane) {
JPanel rowPanel = new JPanel();
pane.add(rowPanel);
rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.Y_AXIS));
rowPanel.add(addAButton("Button 1"));
rowPanel.add(addAButton("Button 2"));
rowPanel.add(addAButton("Button 3"));
rowPanel.add(addAButton("Button 4"));
rowPanel.add(addAButton("5"));
rowPanel.setPreferredSize(new Dimension(600, 400));
rowPanel.setMaximumSize(rowPanel.getPreferredSize());
rowPanel.setMinimumSize(rowPanel.getPreferredSize());
}
private static JButton addAButton(String text) {
JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
return button;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("BoxLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The end result is this:
As you can see, the button row is perfectly aligned. If you resize the JFrame, they stay aligned. Is that what you are looking for?