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

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();
}
} );

Related

JFrame : cannot display two panels in jframe

I have problem to display two panel in Jframe. Please help me to fix the code below
public class quotingtable extends javax.swing.JFrame {
DefaultTableModel model;
JTable table;
JButton SetButton = new JButton("Set Symbol");
JButton VNStock = new JButton("VNStockChart");
JButton Global = new JButton("GlobalChart");
JPanel quotingpanel = new JPanel(new BorderLayout());
JPanel functionpanel = new JPanel(new BorderLayout());
public void run(){
model = new DefaultTableModel(col,row);
quotingpanel.add(table);
functionpanel.add(BorderLayout.CENTER,SetButton);
functionpanel.add(BorderLayout.WEST,VNStock);
functionpanel.add(BorderLayout.EAST,Global);
table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
quotingpanel.add(pane);
getContentPane().add(BorderLayout.CENTER,functionpanel);
getContentPane().add(BorderLayout.SOUTH,quotingpanel);
setSize(800,800);
setLayout( new FlowLayout());
setLayout ( new BorderLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Any help is appreciated.
Remove:
setLayout( new FlowLayout());
setLayout ( new BorderLayout());
Using BorderLayout this way won't pick up the pre-existing components, so will ignore them and won't lay them out
And consider replacing setSize(800,800); with pack();
You may also want to change
getContentPane().add(BorderLayout.CENTER,functionpanel);
getContentPane().add(BorderLayout.SOUTH,quotingpanel);
to
getContentPane().add(functionpanel, BorderLayout.CENTER);
getContentPane().add(quotingpanel, BorderLayout.SOUTH);
it's simply a more consistent and preferred mechanism

How do I create the following GUI in Java Swing?

I want to create the following GUI with Java Swing.
Since I'm not experienced enough with Java Swing, I'm not sure how to exactly recreate that GUI.
I've tried using GridLayout which looks like this:
I've tried other LayoutManagers but due to my inexperience, I couldn't get anything even remotely resembling the GUI I want to achieve.
I probably have to use GridBagLayout but I've tried it and simply wasn't able to get anything done.
I'm not sure how to exactly use GridBagLayout, especially since there is a variance of the amount of colums needed (2, 2 and then 3).
Here is the code used for creating the second GUI:
import java.awt.*;
import javax.swing.*;
public class GUITest extends JFrame {
public GUITest() {
super("Testing Title");
Container pane = getContentPane();
pane.setLayout(new GridLayout(3,1));
pane.add(getHeader());
pane.add(getTextArea());
pane.add(getButtonPanel());
}
public JComponent getHeader() {
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new GridLayout(1,2));
labelPanel.setSize(getPreferredSize());
JLabel labelLocal = new JLabel("Left value: ", JLabel.CENTER);
JLabel labelDB = new JLabel("Right value: ", JLabel.CENTER);
labelPanel.add(labelLocal);
labelPanel.add(labelDB);
return labelPanel;
}
public JComponent getTextArea() {
JPanel textPanel = new JPanel();
textPanel.setLayout(new GridLayout(1,2,5,0));
JTextArea testTextArea = new JTextArea();
testTextArea.setEditable(false);
JScrollPane sp1 = new JScrollPane(testTextArea);
JTextArea testTextArea2 = new JTextArea();
JScrollPane sp2 = new JScrollPane(testTextArea2);
testTextArea2.setEditable(false);
testTextArea.setText("Hello Hello Hello\nTesting!\ntesterino\ntesteroni");
testTextArea2.setText("Hello Hello Hello\nTesting!\ntest\nABC123\ncdef123\nhijk123");
textPanel.add(sp1);
textPanel.add(sp2);
return textPanel;
}
public JComponent getButtonPanel() {
JPanel inner = new JPanel();
inner.setLayout(new FlowLayout((FlowLayout.CENTER),0,100));
inner.add(new JButton("Do something"));
inner.add(new JButton("Do something different"));
inner.add(new JButton("Do something even more different"));
return inner;
}
public static void main(String[] args) {
GUITest e = new GUITest();
e.setSize(700, 500);
e.setVisible(true);
e.setResizable(false);
e.setDefaultCloseOperation(EXIT_ON_CLOSE);
e.setLocationRelativeTo(null);
}
}
I'm thankful for any kind of support!
You could try something like this:
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
public class Example {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setTitle("Testing Title");
jFrame.setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel listPanel = new JPanel(new GridLayout(0, 2, 10, 0));
JPanel leftListPanel = new JPanel(new BorderLayout(0, 10));
JLabel leftLabel = new JLabel("Left value:");
JTextArea leftTextArea = new JTextArea("Hello Hello Hello\nTesting!\ntest");
JScrollPane leftScrollPane = new JScrollPane(leftTextArea);
leftListPanel.add(leftLabel, BorderLayout.NORTH);
leftListPanel.add(leftScrollPane, BorderLayout.CENTER);
JPanel rightListPanel = new JPanel(new BorderLayout(0, 10));
JLabel rightLabel = new JLabel("Right value:");
JTextArea rightTextArea = new JTextArea("Hello Hello Hello\nTesting!\ntest");
JScrollPane rightScrollPane = new JScrollPane(rightTextArea);
rightListPanel.add(rightLabel, BorderLayout.NORTH);
rightListPanel.add(rightScrollPane, BorderLayout.CENTER);
listPanel.add(leftListPanel);
listPanel.add(rightListPanel);
mainPanel.add(listPanel, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel(new BorderLayout());
buttonsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
buttonsPanel.add(new JButton("Do something"), BorderLayout.WEST);
buttonsPanel.add(new JButton("Do something different"), BorderLayout.CENTER);
buttonsPanel.add(new JButton("Do something even more different"), BorderLayout.EAST);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
jFrame.setContentPane(mainPanel);
jFrame.pack();
jFrame.setVisible(true);
}
}
Explanation:
Firstly I created a main JPanel with a BorderLayout. This JPanel will be split horizontally, the CENTRE component will be another JPanel containing the text areas and labels, and the SOUTH component will be a JPanel containing the buttons.
The JPanel that contains the text areas is given a GridLayout so that it can be easily split vertically, and is also given a hgap of 10 to add some spacing.
The left and right JPanels that are put into that are both the same. They have a BorderLayout with a vgap to add spacing. The NORTH component is a JLabel and the CENTRE component is a JScrollPane containing a JTextArea.
Finally, the SOUTH component of the main JPanel is another JPanel which is given a BorderLayout again. Three JButtons are added with WEST, CENTRE and EAST attributes allocated accordingly.
The overall result looks like:
Here is your code with just some little changes :)
import java.awt.*;
import javax.swing.*;
public class GUITest extends JFrame {
public GUITest() {
super("Testing Title");
Container pane = getContentPane();
pane.setLayout(new BorderLayout());//Modified Layout to BorderLayout
pane.add(getHeader(),BorderLayout.NORTH); //BorderLayout.NORTH
pane.add(getTextArea(),BorderLayout.CENTER);//BorderLayout.CENTER
pane.add(getButtonPanel(),BorderLayout.SOUTH);//BorderLayout.SOUTH
}
public JComponent getHeader() {
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new GridLayout(1,2));
labelPanel.setSize(getPreferredSize());
JLabel labelLocal = new JLabel("Left value: ", JLabel.CENTER);
JLabel labelDB = new JLabel("Right value: ", JLabel.CENTER);
labelPanel.add(labelLocal);
labelPanel.add(labelDB);
return labelPanel;
}
public JComponent getTextArea() {
JPanel textPanel = new JPanel();
textPanel.setLayout(new GridLayout(1,2,5,0));
JTextArea testTextArea = new JTextArea();
testTextArea.setEditable(false);
JScrollPane sp1 = new JScrollPane(testTextArea);
JTextArea testTextArea2 = new JTextArea();
JScrollPane sp2 = new JScrollPane(testTextArea2);
testTextArea2.setEditable(false);
testTextArea.setText("Hello Hello Hello\nTesting!\ntesterino\ntesteroni");
testTextArea2.setText("Hello Hello Hello\nTesting!\ntest\nABC123\ncdef123\nhijk123");
textPanel.add(sp1);
textPanel.add(sp2);
return textPanel;
}
public JComponent getButtonPanel() {
JPanel inner = new JPanel();
inner.setLayout(new FlowLayout());//Modified to standard FlowLayout
inner.add(new JButton("Do something"));
inner.add(new JButton("Do something different"));
inner.add(new JButton("Do something even more different"));
return inner;
}
public static void main(String[] args) {
GUITest e = new GUITest();
e.pack(); //Modified setSize(700,500) to pack()
e.setVisible(true);
e.setResizable(false);
e.setDefaultCloseOperation(EXIT_ON_CLOSE);
e.setLocationRelativeTo(null);
}
}
GridLayout sizes all cells the same, i.e. your outer layout with 3 rows and 1 column makes 3 cells of all the same size.
Instead, use BorderLayout for your outer container and add the top, mid and lower panels with constraints BorderLayout.NORTH, BorderLayout.CENTER and BorderLayout.SOUTH respectively

How can I fix blank screen on jframe and set values of vgap and hgap from textfield

How can I fix blank screen on jframe and set values of vgap and hgap from textfield. i am using borderlayout for this.
import java.awt.*;
import javax.swing.*;
public class d1{
public static void main(String[] args) {
JFrame f1 = new JFrame ("Border Layout") ;
f1.setLayout(new BorderLayout());
f1.setVisible(true);
f1.setSize(400,400);
f1.setLocationRelativeTo(null);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField t1 = new JTextField();
t1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JTextField t2 = new JTextField();
t2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JPanel p1 = new JPanel ();
p1.setLayout(new BorderLayout());
p1.add(new JButton("East"), BorderLayout.EAST);
p1.add(new JButton("South"), BorderLayout.SOUTH);
p1.add(new JButton("West"), BorderLayout.WEST);
p1.add(new JButton("North"), BorderLayout.NORTH);
p1.add(new JButton("Center"), BorderLayout.CENTER);
JPanel p2 = new JPanel ();
p2.setLayout(new BorderLayout());
JPanel p3 = new JPanel ();
p3.setLayout(new BorderLayout());
p3.add(new JLabel("Vgap"), BorderLayout.WEST);
p3.add(t1, BorderLayout.CENTER);
JPanel p4 = new JPanel ();
p4.setLayout(new BorderLayout());
p4.add(new JLabel("Hgap"), BorderLayout.WEST);
p4.add(t2, BorderLayout.CENTER);
JPanel p5 = new JPanel();
p5.setLayout(new BorderLayout());
p5.add(new JLabel("Container of BorderLayout"));
JPanel p6 = new JPanel();
p6.setLayout(new BorderLayout());
p6.add(new JLabel("BorderLayout Properties"));
JPanel p7 = new JPanel ();
p7.setLayout(new BorderLayout());
p7.add(p6, BorderLayout.NORTH);
p7.add(p2, BorderLayout.SOUTH);
p2.add(p3, BorderLayout.NORTH);
p2.add(p4, BorderLayout.SOUTH);
f1.add(p1, BorderLayout.CENTER);
f1.add(p7, BorderLayout.SOUTH);
f1.add(p5, BorderLayout.NORTH);
}
}
after this code.
There should be space between north-south and center, north, south and center.
I can not fix blank screen problem when frame is opened.
Add your panels before f1.setVisible(True) on frame and f1.pack() the frame after it.
You don't need to set a fixed size for your frame. Your added components should take care of it.
To set your components, look at MigLayout. It's easy to use and set components the way you need it.
please check this link you can find it here but first you should add ActionListener into your textField objects so that they can take numbers from inside of themselves. Providing white space in a Swing GUI
something like that
t1 = new JTextField();
t1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String v = t1.getText();
int numberhGap = Integer.parseInt(v);
}
});
t1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
t2 = new JTextField();
t2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String h = t2.getText();
int numberhGap = Integer.parseInt(h);
}
});
and declare t1 and t2 outside main method.
like this
public class d1{
static JTextField t1;
static JTextField t2;

UPDATE THE EVENTS ARE NOT WORKING....

UPDATE UPDATE UPDATE
thank you :))) I did What u told me
I put frame.add(FirstScreen) first
they appeared .....
but now the events are not working , why???????
Can u help me again???
I'm sorry ........
..................
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class InterFace extends JFrame implements ActionListener,ItemListener
{
JFrame frame = new JFrame("Al-murshed Dictionary");
JPanel FirstScreen = new JPanel();
JPanel SecondScreen = new JPanel();
JPanel ThirdScreen = new JPanel();
JPanel ForthScreen = new JPanel();
JButton Translate = new JButton ("Translate");
JButton About = new JButton ("About");
JButton Help= new JButton ("Help");
JButton Quit= new JButton ("Quit");
JButton Quit1= new JButton ("Quit");
JButton Quit2= new JButton ("Quit");
JButton Back= new JButton ("Back");
JButton Back1= new JButton ("Back");
JTextField WordField = new JTextField("Write Your Word Here",50);
JTextArea ArbField = new JTextArea(40,40);
JTextArea EngField = new JTextArea(40,40);
CardLayout c1 = new CardLayout ();
public InterFace()
{
FirstScreen.setLayout(c1);
SecondScreen.add(WordField);
SecondScreen.add(Translate);
ThirdScreen.add(Back);
ForthScreen.add(Back1);
ThirdScreen.add(Quit1);
ForthScreen.add(Quit2);
FirstScreen.add(SecondScreen,"1");
FirstScreen.add(ThirdScreen,"2");
FirstScreen.add(ForthScreen,"3");
JPanel controlButtons = new JPanel();
controlButtons.add(Help);
controlButtons.add(About);
controlButtons.add(Quit);
JPanel wordTranslate = new JPanel();
wordTranslate.add(WordField);
wordTranslate.add(Translate);
JPanel controlTextArea = new JPanel();
controlTextArea.add(EngField);
controlTextArea.add(ArbField);
c1.show(FirstScreen,"1");
About.addActionListener(this);
Back.addActionListener(this);
Help.addActionListener(this);
Back1.addActionListener(this);
Quit.addActionListener(this);
Quit1.addActionListener(this);
Quit2.addActionListener(this);
frame.add(FirstScreen);
Container pane = frame.getContentPane();
pane.add(wordTranslate, BorderLayout.NORTH);
pane.add(controlTextArea, BorderLayout.CENTER);
pane.add(controlButtons, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
//EventHandler
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==About)
c1.show(FirstScreen,"2");
if(e.getSource()==Help)
c1.show(FirstScreen,"3");
if(e.getSource()==Quit)
System.exit(0);
if(e.getSource()==Quit1)
System.exit(0);
if(e.getSource()==Quit2)
System.exit(0);
if(e.getSource()==Back)
c1.show(FirstScreen,"1");
if(e.getSource()==Back1)
c1.show(FirstScreen,"1");
}
public static void main (String args[])
{
InterFace d = new InterFace ();
}
}
pane.add(controlTextArea, BorderLayout.CENTER);
...
frame.add(FirstScreen);
First you add the text area panel to the content pane.
Then you add the "FirstScreen" to the frame.
The problem is that when you add the "FirstScreen" to the frame you are really adding it to the content pane of the frame. So basically you are replacing the text area panel with the first screen.
Also, follow Java naming conventions. Variable names should NOT start with an upper case character.

How to align JPanel in java

I have a JPanel which is in a box layout but I am unsure how to align the JPanel to center of the window (and stay centered even if window is resized) I've tried looking for a solution but all questions seem over complicated compared to what it is that I'm looking for.
import java.awt.*;
import javax.swing.*;
public class Stacker extends JFrame {
public Stacker() {
super("Stacker");
setSize(430, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create top panel
JPanel commandPane = new JPanel();
BoxLayout vertical = new BoxLayout(commandPane,
BoxLayout.Y_AXIS);
commandPane.setLayout(vertical);
JButton subscribe = new JButton("Subscribe");
JButton unsubscribe = new JButton("Unsubscribe");
JButton refresh = new JButton("Refresh");
JButton save = new JButton("Save");
commandPane.add(subscribe);
commandPane.add(unsubscribe);
commandPane.add(refresh);
commandPane.add(save);
JMenuItem j1 = new JMenuItem("File");
JMenuItem j2 = new JMenuItem("Open");
JMenuItem j3 = new JMenuItem("Close");
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Feeds");
menu.add(j1);
menu.add(j2);
menu.add(j3);
menubar.add(menu);
setJMenuBar(menubar);
// create bottom panel
/*JPanel textPane = new JPanel();
JTextArea text = new JTextArea(4, 70);
JScrollPane scrollPane = new JScrollPane(text);
// put them together
FlowLayout flow = new FlowLayout();
setLayout(flow);
add(commandPane);
add(scrollPane); */
setJMenuBar(menubar);
add(commandPane);
setVisible(true);
}
public static void main(String[] arguments) {
Stacker st = new Stacker();
}
}
You say you're using a BoxLayout, but is the JPanel with the BoxLayout the JPanel you want to center, or does it contain the JPanel you want to center?
If it contains the JPanel you want to center, then you can add a glue on either side of the JPanel to be centered. If it is the JPanel you want to center, then you can use GridBagLayout or BoxLayout to achieve the effect you're talking about.
Googling something like "Java center component" will give you a ton of results.
for this idea (still not clear from your description) use GridBagLayout without set for GridBagConstraints
.
.
.
import java.awt.*;
import javax.swing.*;
public class CenteredJPanel {
private JFrame frame = new JFrame("Test");
private JPanel panel = new JPanel();
private JButton subscribe = new JButton("Subscribe");
private JButton unsubscribe = new JButton("Unsubscribe");
private JButton refresh = new JButton("Refresh");
private JButton save = new JButton("Save");
public CenteredJPanel() {
panel.setLayout(new GridBagLayout());
panel.add(subscribe);
panel.add(unsubscribe);
panel.add(refresh);
panel.add(save);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CenteredJPanel centeredJLabel = new CenteredJPanel();
}
});
}
}

Categories