How to retrieve a swing form values - java

I have two swing Frames. Frame one will contain a button.when we click the button we will get another frame which will have the five lables(which are the varibles of a class.) with the textfields beside, and a submit button. user will enter the values and clicks submit butoon.
My question is how can retrieve the values from that Frame two when user clicks submit button .i have the code like blelow.
public class Form extends JFrame implements ActionListener {
JPanel panel = new JPanel();
JFrame frame = new JFrame("New frame");
JPanel panel2 = new JPanel();
JButton button = new JButton("add");
JButton button2 = new JButton("Submit");
JLabel label;
JTextField textfield;
public Form() {
setLayout(new BorderLayout());
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setPreferredSize(new Dimension(300, 200));
button.addActionListener(this);
add(panel, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
}
public static void main(String[] a) {
Form s = new Form();
s.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
s.pack();
s.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
dispose();
panel2.setLayout(new FlowLayout());
panel2.setPreferredSize(new Dimension(1000, 1000));
final Field[] fields = Employee.class.getFields();
for (Field temp : fields) {
label = new JLabel(temp.getName());
label.setBounds(20, 50, 100, 20);
textfield = new JTextField(20);
textfield.setBounds(140, 50, 100, 20);
panel2.add(label);
panel2.add(textfield);
}
frame.add(panel2);
frame.setSize(290, 300);
frame.setVisible(true);
button2.setSize(20, 30);
frame.add(button2, BorderLayout.SOUTH);
repaint();
revalidate();
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
}
}

Start by taking a look at The Use of Multiple JFrames, Good/Bad Practice?
Instead of using a second frame, you should use a modal dialog, which, when made visible, will halt your programs execution at that point until it's disposed, at which time it will return and you can extract the values you want from it.
See How to Make Dialogs for more details

Related

Java GUI switching between panels on button click

I am learning Java and I have to develop an application using a GUI. I have the application working in command line already, but the GUI is driving me insane and costing me in lost hours of head banging and research which is leading nowhere. Can you please help me get the basics working so that i can develop further from there. I want to have a single frame application that can switch between frames on a button click. I created a frame and added three panels P1-P3. These are set as Card Layout (from what i read from forums). Then I added additional panels to these to which i have set colour and buttons.
'''
public class MyMainForm extends JFrame{
private JPanel P1;
private JPanel P2;
private JPanel P3;
private JButton btnFrame1;
private JButton btnFrame2;
private JButton button1;
private JTextField thisIsPanel3TextField;
private JButton btn2Frame1;
private final JFrame frame = new JFrame("MyMain Frame");
public MyMainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(P1);
pack();
setSize(1000,800);
//setLocation(null);
btnFrame1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P1.setVisible(false);
setContentPane(new MyMainForm().P2);
}
});
btnFrame2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P2.setVisible(false);
setContentPane(new MyMainForm().P3);
}
});
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P3.setVisible(false);
setContentPane(new MyMainForm().P2);
}
});
btn2Frame1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P1.setVisible(false);
setContentPane(new MyMainForm().P3);
}
});
}
public static void main(String[] args) {
MyMainForm MyMainForm = new MyMainForm();
MyMainForm.setVisible(true);
}
}
'''
I can display P2 or P3 with this new code example above. When i try to go from P2 or P3 back to P1 the content pane doesn't show? Do i need to revalidate the content pane for this to work? I really need to be able to go from P1 to P2
The easiest way to do this is to use a CardLayout. Just follow this example:
JFrame frame = new JFrame();
JPanel p1 = new JPanel();
p1.setBackground(Color.RED);
JPanel p2 = new JPanel();
p2.setBackground(Color.WHITE);
JPanel p3 = new JPanel();
p3.setBackground(Color.BLUE);
//Create the panel that contains the "cards".
JPanel cards = new JPanel(new CardLayout());
cards.add(p1, "Panel 1");
cards.add(p2, "Panel 2");
cards.add(p3, "Panel 3");
// Add your card container to the frame
Container pane = frame.getContentPane();
pane.add(cards, BorderLayout.CENTER);
JButton btn = new JButton("Click me!");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.next(cards);
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(btn);
pane.add(btnPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
Alternatively, you can switch to a specific panel by calling cl.show(cards, "Panel X") where X is the number of the panel. This is because the swing argument is the name I assigned to each "card" and the show method recalls panels added to CardLayout by name. For your example, each button should have a listener that uses this method to "show" its assigned panel.

How to create multiple frames or windows in GUI?

I am new to creating GUI. I want to know how to create multiple windows. I want to show another frame if a button is to be clicked. I have searched how and i saw that some people are making another GUI form and just calling the other form i a button was clicked, but i dont understand how.
There are numerous ways to do this. One of the main ways is to create a new Java Class with its own properties. Here is a nexample:
JButton button = new JButton("Button_Leads_To_This_Window");
button.addActionListener( new ActionActionListener()
{
public void actionPerformed(ActionEvent e)
{
NewFrame();
}
});
This will allow the button to call a new window, similar as the way you called the "My Empire" window. For example NewFrame() class will look like this:
public static void newFrame()
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(true);
JTextArea textArea = new JTextArea(15, 50);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setFont(Font.getFont(Font.SANS_SERIF));
JScrollPane scroller = new JScrollPane(textArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new FlowLayout());
JTextField input = new JTextField(20);
JButton button = new JButton("Enter");
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
panel.add(scroller);
inputpanel.add(input);
inputpanel.add(button);
panel.add(inputpanel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setResizable(false);
input.requestFocus();
}
});
}
Here is more information to the matter:
https://www.thoughtco.com/create-a-simple-window-using-jframe-2034069
https://www.youtube.com/watch?v=RMz9LYY2g4A
Good luck.

How do I add actions to buttons?

I want my buttons to print to the console when I click them. Here's my code. Im looking to make a basic app using this code, and I was wondering how to make the buttons have actions. For the first time, I just want to start with the console for the first time, but later possibly display images?
public static void main(String[] args) {
JFrame frame = new JFrame("GUI");
frame.setSize(320, 300);
frame.setBackground(Color.WHITE);
frame.setVisible(true);
JPanel panel = new JPanel();
panel.setSize(50,50);
JLabel label = new JLabel();
frame.add(panel);
panel.add(label);
label.setText("Welcome to Team 1389!");
Container contentPane = getContentPane();
contentPane.setBackground(Color.blue);
contentPane.setLayout(new FlowLayout());
JButton button = new JButton("MATCHES");
button.setSize(100, 30);
button.setLocation(95, 45);
button.addActionListener(null);
button.setVisible(true);
frame.add(button);
JButton button2 = new JButton("PIT TEAM");
button2.setSize(100, 30);
button2.setLocation(95, 100);
button2.setVisible(true);
frame.add(button2);
JButton button3 = new JButton("SCOUTING");
button3.setSize(100, 30);
button3.setLocation(95, 150);
button3.setVisible(true);
frame.add(button3);
}
private static Container getContentPane() {
// TODO Auto-generated method stub
return null;
}
}
You can look at this tutorial on Oracle's website, it explains things well:
Use an ActionListener. They are interfaces so you will need to add unimplemented methods where the event is handled:
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
//do stuff..
}
});
You can also create the listener separately before adding it if you desire to do so:
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
//do stuff..
}
};
button.addActionListener(listener);

how to identify dynamically created jbutton actions

I create two jbuttons in one panel(can be Box).i create same panel dynamically several times in same frame.so if two panels created dynamically those button make with same variable name.But i want to identify buttons one by one for put actions.how to identify dynamically created buttons one by one?
button creating code
public class Jscrollpanetest extends JFrame {
JScrollPane scrollPane;
Box box;
private static int panelCount = 0;
public Jscrollpanetest() {
setPreferredSize(new Dimension(200, 400));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setUnitIncrement(15);
box = Box.createVerticalBox();
scrollPane.getViewport().add(box);
this.add(scrollPane);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
box.add(new TestPanel(), box.size());
scrollPane.validate();
}
});
t.setRepeats(true);
t.start();
}
public class TestPanel extends JPanel {
int myId = panelCount++;
public TestPanel() {
this.setLayout(new GridBagLayout());
this.setBorder(BorderFactory.createBevelBorder(1));
JButton up = new JButton("^");
JLabel rate = new JLabel("1");
JButton down = new JButton("^");
JLabel label = new JLabel("" + myId);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
this.setMaximumSize(new Dimension(1000, 200));
this.setPreferredSize(new Dimension(1000, 100));
this.add(label);
this.add(up);
this.add(rate);
this.add(down);
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Jscrollpanetest testScrollPane = new Jscrollpanetest();
}
});
}
}
If use and dynamic created ActionListener there will be no problem. So each button will have its own ActionListener.
If using a common ActionListener must add tags to each button as extend JButton.

Calling a JPanel inside a split panel Java

Hi I'm having trouble in my code. I can't call or display my JPanel(TruthTable) inside my splitpane in the Minimize class when I click the button and Keypressed(Enter).The problem is in the class Minimize
*UPDATE: I'have solved my problem regarding to diplaying the panel my next problem is when I call the constructor the text in the panel should be updated.I also change the setText to append 'coz they say that JPanel doesnt support setText.I've already used,validate,repaint method but no luck in updating the textArea.
Heres my code for class Minimize:
package splashdemo;
public class Minimize extends JPanel implements ClipboardOwner
{
simButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent ae)
{
LogicGates lg= new LogicGates();
lg.geth();
sim s=new sim();
s.InputExp(lg.g,lg.g1);
s.menu();
s.setSize(700,700);
s.setVisible(false);
Frame f = new Frame();
Panel panel = new Panel();
f.add(BorderLayout.SOUTH, panel);
f.add(BorderLayout.CENTER, new sim());
f.add(BorderLayout.SOUTH, panel);
f.setSize(580, 500);
panel.add(s.button);
f.show();
f.setVisible(false);
JOptionPane.showMessageDialog(null, b);
ex=b;
cAppend();
JOptionPane.showMessageDialog(null, ex1);
InToPost(ex1);
foutput= doTrans();
JOptionPane.showMessageDialog(null, foutput);
TruthTable_1 kl = new TruthTable_1(foutput);
Minimize mi = new Minimize();
s.InputExp(lg.g,lg.g1);
s.menu();
lg.gatessplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mi, lg.p1);
//here's the splitpane where I should display the TruthTable_1 panel but it doesn't diplay
lg.p1.add(lg.gatessplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, s,kl));
lg.gatessplit.setOneTouchExpandable(true);
lg.gatessplit.setDividerLocation(250);
lg.gatessplit.setPreferredSize(new Dimension(900, 500));
lg.createAndShowGUI();
}});
}
Heres my code the TruthTable_1:constructors
public TruthTable_1() {
super();
tableArea.append("This is a Test");
//setBackground(Color.black);
createg();
setVisible(true);
}
public void createg(){
setLayout(new BorderLayout());
line= 0;
truth= 'T';
fallacy= 'F';
final JPanel top= new JPanel();
input= new TextField(35);
TFCheck= new Checkbox("Select for \"1/0\" (default\"T/F\")");
check= new JButton("Check");
check.addActionListener(this);
top.add(input);
top.add(TFCheck);
top.add(check);
top.setVisible(false);
tableArea= new JTextArea(16, 40);
tableArea.setEditable(false);
tableArea.setFont(new Font("Lucida Console", Font.PLAIN, 14));
// all letters are the same width in this font
go= new JButton("Do it to it!");
go.addActionListener(this);
input.addActionListener(this);
go.setVisible(false);
add(top, BorderLayout.NORTH);
scrolls= new JScrollPane(tableArea);// add scroll buttons to the area
add(scrolls, BorderLayout.CENTER);
add(go, BorderLayout.SOUTH);
setSize(535, 500);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100, 100);
}
public TruthTable_1(String f){
createg();
tableArea.append(run(f));
}

Categories

Resources