How do i display in JTextarea or JTable - java

So I have created two buttons and I want to do a specific task when the buttons are clicked. If button 1 (b1) is clicked using the ActionListener, I want to create an object of Van and display the instance variables in a JTextarea or JTable. For example if Van button is clicked then the action would be to create an object of Van and get the instance variable values and print them in a JTextArea/JTable. Below is my code so far:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
public class TestButton extends JFrame{
JTable table;
public TestButton (){
setLayout(new FlowLayout());
}
static class ActionTwo implements ActionListener{
#Override
public void actionPerformed (ActionEvent evt){
Vehicle sport = new Sportcar (200, 1500, 220);
}
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent evt){
Vehicle aVan = new Van(100,0.9,3500,160.4);
}
}
public static void main (String [] args){
JFrame frame = new JFrame ("Type of Vehicle");
frame.setVisible(true);
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setBackground(Color.black);
JButton b1 = new JButton("Van");
JButton b2 = new JButton("Sports Car");
panel.add(b1);
panel.add(b2);
frame.add(panel);
b1.addActionListener(new Action());
b2.addActionListener(new ActionTwo());
}
}

Have a look at the Java tutorial on Action Listeners
This will do what you would like it to do, but you should read through that tutorial to get a full grasp of what's happening.
public static void main (String [] args){
JTextField text = new JTextField();
ActionListener textSetter = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
text.setText(clicked.getText());
}
};
JButton btnVan = new JButton("Van");
btnVan.addActionListener(textSetter);
JButton btnCar = new JButton("Sports Car");
btnCar.addActionListener(textSetter);
JPanel btnPanel = new JPanel();
btnPanel.add(btnVan);
btnPanel.add(btnCar);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(text, BorderLayout.NORTH);
mainPanel.add(btnPanel, BorderLayout.SOUTH);
JFrame frame = new JFrame ("Type of Vehicle");
frame.add(mainPanel);
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

Related

Data not Printing on JLabel contained in a JPanel after clicking a Jbutton

I am creating a JFrame holding a JPanel(p1) and a JButton(b1)....p1 contains another JPanel(sub1) holding a JLabel(l1)...after i Click on b1,i want a String to be printed in the JLabel...but it is not printing anything.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class panAccDel implements ActionListener {
JFrame frame = new JFrame();
JButton b1;
JLabel l1;
String intro = "Hello there";
JPanel sub1,p1;
public static void main(String[] args) {
panAccDel panAccDel = new panAccDel();
}
public panAccDel(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1 = new JPanel();
b1 = new JButton("Print Data");
sub1 = new JPanel();
p1.add(sub1);
p1.add(b1);
p1.setLayout(new GridLayout(2,1));
sub1.setBackground(Color.RED);
l1 = new JLabel();
sub1.add(l1);
frame.add(p1);
frame.setVisible(true);
frame.setSize(700,700);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == b1){
l1.setText(intro);
}
}
}
This is a trial Code.
Any Suggestions???
The listener needs added to the button. For example:
b1.addActionListener(this);

How to add JTextField whenever the button is clicked?

I am practising Java Swing and I am trying to create a GPA calculator. I am having a hard time with my code, how can I add text fields whenever the JButton "add" is clicked? I also want the text fields to align vertically when the button is clicked. Should I use a layout or something?
You can check my screenshot as well.
Here is my code:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class gwa implements ActionListener, java.awt.event.ActionListener{
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
//button
JButton buttonAdd = new JButton("Add");
buttonAdd.setBounds(30, 30, 80, 34);
buttonAdd.addActionListener(new gwa());
//textfield
JTextField gradeField = new JTextField();
gradeField.setBounds(150, 30, 100, 35);
JTextField unitsField = new JTextField();
unitsField.setBounds(300, 30, 100, 35);
//panel
panel.setLayout(null);
panel.add(buttonAdd);
panel.add(gradeField);
panel.add(unitsField);
//frame
frame.add(panel);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
}
One way – but not the only way – is to use GridBagLayout.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class GwaAdder {
private static final int COLUMNS = 10;
private GridBagConstraints gbc;
private JPanel textFieldsPanel;
private void addTextField(ActionEvent event) {
JTextField textField = new JTextField(COLUMNS);
gbc.gridy++;
textFieldsPanel.add(textField, gbc);
textFieldsPanel.revalidate();
textFieldsPanel.repaint();
}
private void createAndDisplayGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextFieldsPanel(), BorderLayout.CENTER);
frame.add(createButtons(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtons() {
JPanel panel = new JPanel();
JButton button = new JButton("Add");
button.addActionListener(this::addTextField);
panel.add(button);
return panel;
}
private JScrollPane createTextFieldsPanel() {
textFieldsPanel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridy = 0;
JTextField textField = new JTextField(COLUMNS);
textFieldsPanel.add(textField, gbc);
JScrollPane scrollPane = new JScrollPane(textFieldsPanel);
scrollPane.setPreferredSize(new Dimension(140, 200));
return scrollPane;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new GwaAdder().createAndDisplayGui());
}
}
The ActionListener is implemented using method references. When you change the GUI after it is initially displayed (as the above code does in method addTextField), you usually need to call method revalidate (in class javax.swing.JComponent) followed by method repaint (in class java.awt.Component).
How it looks when I run the above code:
You should first give your button's Action event the panel, and then do the Action
My English is not good, so I use translation software to answer, please forgive me

How to Switch between Panels in CardLayout from ActionListeners in external classes

I have a cardLayout in the main class that the Gui classes are added to layout via panels and when the Room1Button is pressed how would it switch the card in the main method to the Gui2 card
is this the best way to go about this any help would be apreatiated
Main Method
import javax.swing.*;
import java.awt.*;
class Main
{
CardLayout cl=new CardLayout();
GridBagConstraints gb=new GridBagConstraints();
JFrame frame=new JFrame("Frame");
JPanel panel =new JPanel();
Gui1 g1= Gui1();
Gui2 g2= Gui2();
public Main()
{
panel.setLayout(cl);
panel.add(g1, "1");
panel.add(g2, "2");
frame.add(panel);
frame.pack();
frame.setVisible(true);
cl.show(panel,"1");
//how would the actionlistner in the Gui1 class switch the layout to "2"
cl.show(panel, "2");
}
public static void main(String[]param)
{
new Main();
}
}
The gui1 class
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class Gui1 extends JPanel implements ActionListener{
private JButton room1Button;
JPanel panel=new JPanel();
{
setSize(1000,1000);
panel.setVisible(true);
room1Button=new JButton("Go the next Panel");
this.setVisible(true);
room1Button.addActionListener(this);
add(room1Button);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==room1Button){
Window w = SwingUtilities.getWindowAncestor(R0.this);
w.setVisible(false);
}
}
}
The Gui2 class
public class Gui2 extends JPanel implements Actionlistener
{
// some code
}
The ActionEvent will contain the source object that generated the event. In this case the JButton. So generic code for the ActionListener in your GUI1 class would be something like:
JButton button = (JButton)e.getSource();
JPanel buttonPanel = (JPanel)button.getParent();
JPanel cardLayoutPanel = (JPanel)buttonPanel.getParent();
CardLayout layout = (CardLayout)cardLayoutPanel.getLayout();
layout.show(cardLayoutPanel, "2");
Hope this helps.
package cardlayoutsample;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CardLayoutSample {
JFrame frame = new JFrame("CardLayout Demo");
JPanel panelCont = new JPanel();
JPanel panelFirst = new JPanel();
JPanel panelSecond = new JPanel();
JButton btnOne = new JButton("Switch");
JButton btnTwo = new JButton("Back");
CardLayout cl = new CardLayout();
public CardLayoutSample(){
panelCont.setLayout(cl);
panelFirst.add(btnOne);
panelSecond.add(btnTwo);
panelFirst.setBackground(Color.red);
panelSecond.setBackground(Color.blue);
panelCont.add(panelFirst,"1");
panelCont.add(panelSecond,"2");
cl.show(panelCont, "1");
btnOne.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
cl.show(panelCont, "2");
}
});
btnTwo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
cl.show(panelCont, "1");
}
});
frame.add(panelCont);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args) {
CardLayoutSample a = new CardLayoutSample();
}
}
Try to play this button you can see it's switching the panels when you clicked the buttons.
Syntax for ActionListener
Component.addActionListener(new ActionListener (){
#Override
public void actionPerformed(ActionEvent e){
//do this
}
});
Example
LogoutButton.addActionListener(new ActionListener (){
#Override
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});

How to change image without double instantiating the JFrame?

So I want to change the image showing every time i press the Roll button but whenever I try to do it I double instantiate the JFrame. I would like to use the ActionListener this way if it is posible.
Here is my code:
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class DiceFrame extends JFrame{
ImageIcon[] dice_images = new ImageIcon[7];
String score = "This is a test";
JPanel mainPanel;
JPanel scorePanel;
JPanel buttonPanel;
JLabel picLabel;
JTextArea scoreField;
JButton roll;
JButton save;
ActionListener action;
ActionListener output;
public DiceFrame(){
super();
mainPanel = new JPanel();
scorePanel = new JPanel();
buttonPanel = new JPanel();
roll = new JButton("Roll");
save = new JButton("Save");
picLabel = new JLabel();
scoreField = new JTextArea();
setSize(400,300);
setTitle("Dice Program");
loadImage();
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(scorePanel, BorderLayout.EAST);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(picLabel);
picLabel.setIcon(dice_images[0]);
buttonPanel.add(roll);
buttonPanel.add(save);
scorePanel.add(scoreField);
scoreField.setText(score);
roll.addActionListener(action);
save.addActionListener(output);
}
private void loadImage()
{
dice_images [0] = new ImageIcon("res/dice_img/die_01_sm.gif");
dice_images [1] = new ImageIcon("res/dice_img/die_02_sm.gif");
dice_images [2] = new ImageIcon("res/dice_img/die_03_sm.gif");
dice_images [3] = new ImageIcon("res/dice_img/die_04_sm.gif");
dice_images [4] = new ImageIcon("res/dice_img/die_05_sm.gif");
dice_images [5] = new ImageIcon("res/dice_img/die_06_sm.gif");
dice_images [6] = new ImageIcon("res/dice_img/die_01_sm.gif");
}
public static void main(String [] args){
DiceFrame frame = new DiceFrame();
frame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class DiceActionListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){}
}
class SaveActionListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){}
}
I dont know what to put inside the actionPerformed method in order to not create another instance of the JFrame.
Do something like below code. Create a method that can change your image icon. Then call it from as part of your button click. Have a look at the comments.
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class DiceFrame extends JFrame {
ImageIcon[] dice_images = new ImageIcon[7];
String score = "This is a test";
JPanel mainPanel, scorePanel, buttonPanel;
JLabel picLabel;
JTextArea scoreField;
JButton roll, save;
public DiceFrame(){
super();
mainPanel = new JPanel();
scorePanel = new JPanel();
buttonPanel = new JPanel();
roll = new JButton("Roll");
save = new JButton("Save");
picLabel = new JLabel();
scoreField = new JTextArea();
setSize(400,300);
setTitle("Dice Program");
loadImage();
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(scorePanel, BorderLayout.EAST);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(picLabel);
picLabel.setIcon(dice_images[0]);
buttonPanel.add(roll);
buttonPanel.add(save);
scorePanel.add(scoreField);
scoreField.setText(score);
save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
System.out.println("You clicked save");
}
});
roll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
//call your icon change method with the index you want to change it to
changeIcon(3);
}
});
}
private void loadImage() {
//use a loop insted of repeting the add, but becareful if i < 10 because your file names need to match :)
for(int i = 0; i < 7; i++) {
dice_images [i] = new ImageIcon("res/dice_img/die_0" + i + "_sm.gif");
}
}
public static void main(String [] args) {
DiceFrame frame = new DiceFrame();
frame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//create a method to change your icon
public void changeIcon(int imageIndex) {
picLabel.setIcon(this.dice_images[imageIndex]);
}
}

Java: Jswing: Jlist

When i input a name to the Jlist, the name gets outputted to the lower section of the list, how do i make it to where the name is set to the top of the window
package Gui;
//import java.awt.BorderLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GUI implements ActionListener {
JButton button;
JTextField field;
JList list;
JTextField name1;
DefaultListModel listModel;
String name;
public GUI(){
listModel = new DefaultListModel();
listModel.addElement(null);
listModel.setSize(1);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
field = new JTextField("Enter Name", 10);
button = new JButton("Click");
list = new JList(listModel);
list.setBorder(BorderFactory.createEmptyBorder(120, 20, 20, 120));
JScrollPane listScrollPane = new JScrollPane(list);
panel.add(listScrollPane);
listScrollPane.setWheelScrollingEnabled(true);
panel.add(button);
panel.add(field);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == button)
name = field.getText();
listModel.addElement(name);
}
}
You can simply use the add(0, object) method.
Instead of listModel.addElement(name), listModel.add(0, name) will add the name at the top of the List.
For the size of the JList you shouldn't use this border but instead select a preferredSize for your JSCrollPane :
package Gui;
...
import java.awt.Dimension;
public class GUI implements ActionListener {
...
public GUI(){
...
list = new JList(listModel);
JScrollPane listScrollPane = new JScrollPane(list);
listScrollPane.setPreferredSize(new Dimension(100, 240));
panel.add(listScrollPane);
...
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == button)
name = field.getText();
listModel.add(0, name);
}
}
Resources :
JavaDoc - DefaultListModel.add(int, Object)

Categories