JButtons in JPanel in another JPanel - java

Is it possible to add a JPanel with JButtons to a Split JPanel? Right now, I have the JPanel with JButtons added to a JFrame, but I want it on a JPanel with other JPanels. When I attempt to do this, I get a completely blank JPanel with dividers.
______________________________________________________________________________
public class Panel extends JPanel implements Runnable, ActionListener {
public Panel(){
JFrame frame = new JFrame();
ctsMenu = new JPanel(new GridLayout(2,2));
ctsMenu.setPreferredSize(new Dimension(500,500));
for (int iRows = 0; iRows < 2 ; iRows++){
for (int iColumns = 0; iColumns < 2; iColumns++){
sGrid[iRows][iColumns] = new JButton ("("+iRows+","+iColumns+")");
ctsMenu.add(sGrid[iRows][iColumns]);
sGrid[iRows][iColumns].addActionListener(this);
panel.add(ctsMenu);
}
}
sGrid[0][0].setText("A");
sGrid[0][1].setText("B");
sGrid[1][0].setText("C");
sGrid[1][1].setText("D");
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}}
____________________________________________________________________
public MainFrame()
{
setTitle( "Split Pane Application" );
setBackground( Color.GREEN );
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
createPanel1();
createPanel2();
createPanel3();
createPanel4();
splitPaneV = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
topPanel.add( splitPaneV, BorderLayout.CENTER );
splitPaneV.setDividerLocation(300);
splitPaneV.setLeftComponent( gamePanel);
// gamePanel.addKeyListener(new KeyListener());
gamePanel.setFocusable(true);
gamePanel.requestFocusInWindow();
splitPaneV.setRightComponent( panel3 );
}
}
public void createPanel1(){
// deleted to take up less space
}
public void createPanel2(){
// deleted to take up less space
}
public void createPanel3(){
panel3 = new Panel();
}
public void createPanel4(){
//deleted to take up less space
}
}

You ask:
Is it possible to add a JPanel with JButtons to a Split JPanel?
Yes, it is most definitely possible to do this. It's something similar to what we do all the time:
import javax.swing.*;
public class SplitPaneEg {
private static void createAndShowGui() {
JPanel panel1 = new JPanel();
panel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
panel1.add(new JButton("Button 1"));
panel1.add(new JButton("Button 2"));
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
panel2.add(new JButton("Button 1"));
panel2.add(new JButton("Button 2"));
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1,
panel2);
JFrame frame = new JFrame("Split Pane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(splitPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You state:
Right now, I have the JPanel with JButtons added to a JFrame, but I want it on a JPanel with other JPanels. When I attempt to do this, I get a completely blank JPanel with dividers.
Then you have an error in your code, but unfortunately based on code you've posted I doubt that any of us can do more than just guess. If you need more specific help, then you will want to post a small runnable example that demonstrates your problem, an sscce.

Related

Java Swing JButton must create 4 new objects and add to JPanel

Okay, so when I press the JButton menuselect1, I want it to create 4 new objecs, attack1 2 3 and 4, and then add them to the JPanel fightmenu.
This is my code so far, it's a mini pokemon game.
First I create all my objects, and then I set the sizes and adds them to the different JPanels
public class MainFrame extends JFrame {
JPanel mainwindow = new JPanel();
JPanel bottom = new JPanel();
JPanel combat = new JPanel();
JPanel selectionmenu = new JPanel();
JPanel fightmenu = new JPanel();
JButton menuselect1 = new JButton("Fight");
JButton menuselect2 = new JButton("Minimons");
JButton menuselect3 = new JButton("Bag");
JButton menuselect4 = new JButton("Run");
JButton attack1 = new JButton("Tackle");
JButton attack2 = new JButton("Lightningbolt");
JButton attack3 = new JButton("Thunder-Shock");
JButton attack4 = new JButton("Hyper-Beam");
JButton poke1 = new JButton("Ekans");
JButton poke2 = new JButton("Pikachu");
public static void main(String[] args){
new MainFrame();
}
public MainFrame(){
super("MiniMon");
setSize(640,640);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(mainwindow);
// SIZES
combat.setPreferredSize(new Dimension(640,452));
bottom.setPreferredSize(new Dimension(640,160));
selectionmenu.setPreferredSize(new Dimension(320,160));
fightmenu.setPreferredSize(new Dimension(320,160));
mainwindow.setLayout(new BorderLayout());
mainwindow.add(combat, BorderLayout.NORTH);
mainwindow.add(bottom, BorderLayout.SOUTH);
combat.setLayout(new BorderLayout());
combat.add(poke1, BorderLayout.NORTH);
combat.add(poke2, BorderLayout.SOUTH);
bottom.setLayout(new BorderLayout());
bottom.add(selectionmenu, BorderLayout.EAST);
bottom.add(fightmenu, BorderLayout.WEST);
selectionmenu.setLayout(new GridLayout(2,2));
selectionmenu.add(menuselect1);
selectionmenu.add(menuselect2);
selectionmenu.add(menuselect3);
selectionmenu.add(menuselect4);
fightmenu.setLayout(new GridLayout(2,2));
setVisible(true);
}
}
I set up my fightmenu to use a 2x2 gridlayout, so I just need to add the 4 objects whenever I press the JButton menuselect1. I'm not really sure how to go about this. I know I should add an eventlistener, but when I tried, it did nothing at all.
I tried doing this:
fightmenu.setLayout(new GridLayout(2,2));
menuselect1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fightmenupress();
}
private void fightmenupress() {
fightmenu.add(attack1);
fightmenu.add(attack2);
fightmenu.add(attack3);
fightmenu.add(attack4);
}
} );
But it just did nothing.
When you add (or remove) components to a visible GUI, the basic code is:
panel.add(...);
panel.revalidate(); // to invoke the layout manager
panel.repaint(); // to repaint all the components on the panel
I added revalidate and repaint, and it worked!
private void fightmenupress() {
fightmenu.add(attack1);
fightmenu.add(attack2);
fightmenu.add(attack3);
fightmenu.add(attack4);
fightmenu.revalidate();
fightmenu.repaint();
}
} );

Multiple JPanels - All buttons same size

I have a a main panel that contains multiple panels inside. Each 'children' panel contains one (or more) JButtons. Since I am displaying all the panels at the same time, I would like to make all the buttons the same size (to have consistency).
This code illustrates my problem:
public class Test
{
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(new Dimension(200, 200));
// 1st Panel
JPanel panel1 = new JPanel(new MigLayout());
panel1.add(new JButton("button in panel 1"));
// 2nd Panel
JPanel panel2 = new JPanel(new MigLayout());
panel2.add(new JButton("2nd button"));
JPanel parent = new JPanel(new MigLayout("wrap"));
parent.add(panel1, "pushx, growx");
parent.add(new JSeparator(), "pushx, growx");
parent.add(panel2, "pushx, growx");
f.add(parent);
f.setVisible(true);
}
}
The size of the "button in panel 1" is different from the button in the other panel. Is there an 'easy' way to set their size using the layout? (Hardcoding the size is NOT an option).
I think you didn't read the document carefully, to demonstrate the use I have written a code. You should not copy the same snippet showed in that link. They have specified that the component you have updating must be passed into updateComponentTreeUI() method. You can replace the size by replacing the "large" with "small" or "mini".
import javax.swing.*;
import java.awt.*;
public class Demo {
/**
* #param args
*/
JFrame frame ;
JButton btn;
public Demo()
{
frame = new JFrame("Example");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLayout(new FlowLayout());
btn = new JButton("Example");
btn.putClientProperty("JComponent.sizeVariant", "large");
SwingUtilities.updateComponentTreeUI(btn);
frame.add(btn);
frame.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception e)
{
e.printStackTrace();
}
Demo d = new Demo();
}
}

Java panel alignment

class CipherGUIFrame extends JFrame {
public CipherGUIFrame() {
super("Caesar Cipher GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 600);
JTextArea area1 = new JTextArea();
JTextArea area2 = new JTextArea();
JSpinner myspinner=new JSpinner();
JPanel mainframe = new JPanel();
mainframe.setLayout(new BoxLayout(mainframe, BoxLayout.Y_AXIS));
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));
p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));
p1.setBorder(BorderFactory.createTitledBorder("Cleartext"));
p2.setBorder(BorderFactory.createTitledBorder("Spinner"));
p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS));
p3.setBorder(BorderFactory.createTitledBorder("Ciphertext"));
p1.add(area1);
p2.add(myspinner);
p3.add(area2);
mainframe.add(p1);
mainframe.add(p2);
mainframe.add(p3);
this.add(mainframe);
}
}
It seems that this code produces something which looks similar to this:
I am trying to tidy this up so it looks cleaner; is there a way to shrink the middle panel or to make the others bigger to make it look nicer?
Don't set the sizes of anything, but instead set the columns and rows of your JTextAreas. Don't use BoxLayout when you don't want its behaviors. Put your JTextAreas in JScrollPanes instead. And don't forget to pack() your JFrame.
import java.awt.BorderLayout;
import javax.swing.*;
public class Cipher2 extends JPanel {
public static final int ROWS = 12;
public static final int COLS = 30;
private JTextArea textArea1 = new JTextArea(ROWS, COLS);
private JTextArea textArea2 = new JTextArea(ROWS, COLS);
public Cipher2() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // Box OK here
JScrollPane scroll1 = new JScrollPane(textArea1);
add(wrapComponentWithTitle(scroll1, "Fubar"), BorderLayout.PAGE_START);
add(wrapComponentWithTitle(new JSpinner(), "Spinner"), BorderLayout.CENTER);
scroll1 = new JScrollPane(textArea2);
add(wrapComponentWithTitle(scroll1, "Snafu"), BorderLayout.PAGE_END);
}
private JPanel wrapComponentWithTitle(JComponent component, String title) {
// BoxLayout NOT OK here. Use BorderLayout instead
JPanel wrapPanel = new JPanel(new BorderLayout());
wrapPanel.add(component);
wrapPanel.setBorder(BorderFactory.createTitledBorder(title));
return wrapPanel;
}
private static void createAndShowGui() {
Cipher2 mainPanel = new Cipher2();
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}
I figured out the answer: change Y_AXIS to X_AXIS.
<3

Switching JPanels in a JFrame without CardLayout

How can I switch Panels with ScrollPanes in a Frame? I've tried many possible ways but cannot come up with a solution to.
Actually this is one of the Java Problems my professor gave me and I needed to accomplish this by not using other layouts (such as CardLayout) and I should use the null layout only. Additional classes are allowed as long as I maintain these three classes and the scroll pane.
public class MainDriver {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
panel1 p1 = new panel1();
panel2 p2 = new panel2();
JScrollPane jsp = new JScrollPane(panel1.panel);
Container c = frame.getContentPane();
jsp.getVerticalScrollBar().setUnitIncrement(10);
c.add(jsp);
//codes for panel switching from panel1 to panel2 vice versa
frame.setDefaultCloseOperation(JFrame.exit_ON_CLOSE);
frame.setSize(1058, 600);
frame.setLocation(100, 50);
frame.setVisible(true);
}
}
---------------------------------------------
public class panel1{
public JPanel panel(){
JPanel fore = new JPanel();
fore.setLayout(null);
fore.setPreferredSize(new Dimension (1024, 600));
fore.setBackground(Color.decode("#004050"));
fore.setVisible(true);
JButton but = new JButton();
but.setLocation(425, 300);
but.setSize(100, 35);
//button action/mouse listener
fore.add(but);
return fore;
}
}
---------------------------------------------
public class panel2{
public JPanel panel(){
JPanel fore = new JPanel();
fore.setLayout(null);
fore.setPreferredSize(new Dimension (1024, 600));
fore.setBackground(Color.decode("#004050"));
fore.setVisible(true);
JButton but = new JButton();
but.setLocation(425, 300);
but.setSize(100, 35);
//button action/mouse listener
fore.add(but);
return fore;
}
}
How can I switch Panels with ScrollPanes in a Frame?
scrollPane.setViewportView( anotherPanel );

JScrollPane won't work

Hey guys I wanted to create a JScrollPane but it won't work... and I don't know why... here's my code...
public class test extends JFrame{
public test(){
setSize(1000,600);
}
private static JButton[] remove;
private static JPanel p = new JPanel();
public static void main(String[]args){
p.setLayout(null);
JFrame t=new test();
remove = new JButton[25];
for(int i=0;i<25;i++){
remove[i]=new JButton("Remove");
remove[i].setBounds(243,92+35*i,85,25);
p.add(remove[i]);
}
JScrollPane scrollPane = new JScrollPane(p);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
t.add(scrollPane);
t.setVisible(true);
}
Umm and Im pretty sure the frame isn't big enough for these 25 buttons... But if i delete that p.setLayout(null); A horizontal scroll bar will be created automatically... I don't really know what is wrong with my code... Pls help thank you very much!
You need to set p's preferredSize for this to work.
p.setPreferredSize(new Dimension(800, 2000));
Or you could have p extend JPanel and then override the getPreferredSize() method to return the proper dimension.
And I agree -- get rid of your null layouts. Learn about and use the layout managers if you want to use Swing correctly and have robust Swing GUI's.
e.g.,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Foo extends JFrame {
private static final int BUTTON_COUNT = 25;
public static void main(String[] args) {
JPanel btnPanel = new JPanel(new GridLayout(0, 1, 0, 20));
btnPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
AbstractAction removeAction = new AbstractAction("Remove") {
#Override
public void actionPerformed(ActionEvent evt) {
JButton src = (JButton) evt.getSource();
JPanel container = (JPanel) src.getParent();
container.remove(src);
container.revalidate();
container.repaint();
}
};
for (int i = 0; i < BUTTON_COUNT; i++) {
JButton removeBtn = new JButton(removeAction);
btnPanel.add(removeBtn);
}
JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.add(btnPanel, BorderLayout.NORTH);
JScrollPane scrollpane = new JScrollPane(borderPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollpane.setPreferredSize(new Dimension(400, 800));
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollpane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The issue is that a scroll pane checks the component inside it for a "preferred size" so a pane with a null layout has a preferred size of (0,0). Which it ignores.
You should do something along the lines of:
p.setPreferredSize(1000,600);
And you should see some scroll bars appear, I'm not sure how accurate they will be though.

Categories