adding users to JList in chatroom GUI - java

I'm trying to write a simple chatroom GUI using java, including a Jlist to show the online users. first a user chooses a display name so that the name will be displayed in the JList.
here is the code:
(the problem is only inside the createServer() method which sends Name as an argument to the handler constructor, in order to display it in the JList!)
public class GUI{
private JFrame frame;
private JButton btnSend, btnConnect;
private JTextArea txtChat;
private JTextField fldText, fldName;
private JList clientList;
private DefaultListModel listModel;
private JScrollPane sc, scClients;
private JPanel jpS2All, jpS2Client, jpS2Text;
private String Name;
class handler implements ActionListener, MouseListener{
private String Name = null;
void handler(String Name) {
this.Name = Name;
}
#Override
public void actionPerformed(ActionEvent e) {
chatroom();
}
#Override
public void mouseClicked(MouseEvent e) {
fldName.setText("");
listModel.addElement(Name);
}
}
public void creatServer() {
frame = new JFrame("login");
frame.setBounds(50, 50, 300, 200);
btnConnect = new JButton("connect");
frame.add(btnConnect, BorderLayout.EAST);
fldName = new JTextField("enter your name");
fldName.addMouseListener(new handler());
Name = fldName.getText();
btnConnect.addActionListener(new handler(Name));
frame.add(fldName, BorderLayout.CENTER);
frame.setVisible(true);
}
public void chatroom() {
frame = new JFrame("online friends");
frame.setBounds(100, 100, 400, 400);
jpS2All = new JPanel();
txtChat = new JTextArea();
txtChat.setRows(25);
txtChat.setColumns(25);
txtChat.setEditable(false);
sc = new JScrollPane(txtChat);
jpS2All.add(sc);
frame.add(jpS2All, BorderLayout.WEST);
////////////////////////
jpS2Text = new JPanel();
fldText = new JTextField();
fldText.setColumns(34);
fldText.setHorizontalAlignment(JTextField.RIGHT);
jpS2Text.add(fldText);
frame.add(jpS2Text, BorderLayout.SOUTH);
/////////
jpS2Client = new JPanel();
listModel = new DefaultListModel();
clientList = new JList(listModel);
clientList.setFixedCellHeight(14);
clientList.setFixedCellWidth(100);
scClients = new JScrollPane(clientList);
frame.add(jpS2Client.add(scClients), BorderLayout.EAST);
/////////
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
and finally in the main method:
public class Chat {
public static void main(String[] args) {
GUI gui = new GUI();
gui.creatServer();
}
}

This:
void handler(String Name) {
...
Should be
handler(String Name) {
...
To be a constructor, instead of a method. Also, you create a handler with two different parameter lists: empty, and the string. You need a constructor for both.
By the way, the code would be a lot easier to follow if it used the usual java naming conventions. Now they are inverted in a couple of places. Also, MouseListener has more methods that need to be implemented - consider extending MouseAdapter. Finally, you should create and access swing components only in the event dispatch thread.

Related

Get text field information from one class and show it on a JTextArea on another class

I have a class BasicInfoWindow that gets the user information such as name, address, etc. I then have another class ReviewandSubmit where it show the the texts the user entered from BasicInfoWindow in the JTextArea. I am using card layout to switch between each panel. I am not sure how to send the info from BasicInfoWindow and receive it from ReviewandSubmit. Here is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JPanel
{
private static void createAndShowGUI()
{
final Main test = new Main();
JPanel buttonPanel = new JPanel(new BorderLayout());
JPanel southPanel = new JPanel();
buttonPanel.add(southPanel, BorderLayout.SOUTH);
final JButton btnNext = new JButton("NEXT");
final JButton btnPrev = new JButton("PREVIOUS");
buttonPanel.add(btnNext, BorderLayout.EAST);
buttonPanel.add(btnPrev, BorderLayout.WEST);
btnNext.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
test.nextCard();
}
});
btnPrev.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
test.prevCard();
}
});
JFrame frame = new JFrame("Employment Application");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(test);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
//frame.setSize(750,500);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String [] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private CardLayout cardLayout = new CardLayout();
private JPanel cardShowingPanel = new JPanel(cardLayout);
public Main()
{
BasicInfoWindow window1 = new BasicInfoWindow();
cardShowingPanel.add(window1, "1");
EmploymentHistoryWindow window2 = new EmploymentHistoryWindow();
cardShowingPanel.add(window2, "2");
EducationAndAvailbleWindow window3 = new EducationAndAvailbleWindow();
cardShowingPanel.add(window3, "3");
ReviewAndSubmitWindow window4 = new ReviewAndSubmitWindow();
cardShowingPanel.add(window4, "4");
setLayout(new BorderLayout());
add(cardShowingPanel, BorderLayout.CENTER);
}
public void nextCard()
{
cardLayout.next(cardShowingPanel);
}
public void prevCard()
{
cardLayout.previous(cardShowingPanel);
}
public void showCard(String key)
{
cardLayout.show(cardShowingPanel, key);
}
}
BasicInfo Class
ommitted some methods
public class BasicInfoWindow extends JPanel
{
private JTextField txtName, txtAddress, txtCity, txtState, txtZipCode, txtPhoneNumber, txtEmail;
private JComboBox cbDate, cbYear, cbMonth;
private JLabel labelName, labelAddress, labelCity, labelState, labelZipCode, labelPhoneNumber, labelEmail, labelDOB;
private JButton btnClear;
public BasicInfoWindow()
{
createView();
}
private void createView()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
northPanel(panel);
centerPanel(panel);
southPanel(panel);
}
public ArrayList<HiringPersonInfo> sendInfo()
{
String name = txtName.getText();
String address = txtAddress.getText();
String city = txtCity.getText();
String state = txtState.getText();
String zip = txtZipCode.getText();
String phone = txtPhoneNumber.getText();
String email = txtEmail.getText();
String DOB = cbMonth.getSelectedItem() + " " + cbDate.getSelectedItem() + " " + cbYear.getSelectedItem();
HiringPersonInfo addNewInfo = new HiringPersonInfo(name, address, city, state, zip, phone, email, DOB);
ArrayList<HiringPersonInfo> personInfo = new ArrayList();
personInfo.add(addNewInfo);
return personInfo;
}
ReviewAndSubmit class
public class ReviewAndSubmitWindow extends JPanel
{
private JButton btnSubmit;
public ReviewAndSubmitWindow()
{
createView();
}
private void createView()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
northPanel(panel);
centerPanel(panel);
southPanel(panel);
}
private void northPanel(JPanel panel)
{
JPanel northPanel = new JPanel();
panel.add(northPanel, BorderLayout.NORTH);
JLabel labelMessage = new JLabel("Review and Submit");
labelMessage.setFont(new Font("Serif", Font.BOLD, 25));
northPanel.add(labelMessage, BorderLayout.CENTER);
}
private void centerPanel(JPanel panel)
{
JPanel centerPanel = new JPanel();
JTextArea showReview = new JTextArea();
showReview.setLineWrap(true);
showReview.setWrapStyleWord(true);
showReview.setEditable(false);
JScrollPane scrollPane = new JScrollPane(showReview);
scrollPane.setPreferredSize(new Dimension(600, 385));
centerPanel.add(scrollPane, BorderLayout.CENTER);
BasicInfoWindow getInfo = new BasicInfoWindow();
showReview.append(getInfo.sendInfo().toString());
panel.add(centerPanel);
}
private void southPanel(JPanel panel)
{
JPanel southPanel = new JPanel();
panel.add(southPanel, BorderLayout.SOUTH);
btnSubmit = new JButton("SUBMIT");
// creates a new file
southPanel.add(btnSubmit);
}
}
You could use a Singleton Pattern in the HiringPersonInfo class to instantiate one instance of the class and then during the submit you could add that instance of that class to an ArrayList.
Singleton Patterns can be used to create one instance of the object that can be shared by all the classes in that package. You can think of it like a "global" variable in a way for OOP.

I've created a basic GUI but buttons won't interact with textfield

I've been working on creating a simple GUI through the use of JPanels. I've managed to what I believe fluke a reasonably looking layout and now I would like the user to be able to input values into the Mass textbox and the Acceleration textbox so when they hit calculate they are given a message telling them the Force.
The issue I am having is within the public void that is added to the buttons, I can't seem to figure out how to refer to values within the text field. I've tried to just refer to it generally by:
String mass = txts[1].getText();
However this doesn't recognise txts as existing?
Any help on this would be much appreciated.
Below is the full code in case it helps.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
import java.awt.*;
public class InitScreen {
public static void createHomeScreen() {
/*Creates a Java Frame with the Window Name = HomeScreen*/
JFrame frame = new JFrame("HomeScreen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.getContentPane().setPreferredSize(new Dimension(400,300));
frame.pack();
/*Creates the main JPanel in form of GridLayout*/
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(new EmptyBorder(new Insets(20,20,20,20)));
/*Creates the first sub panel*/
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(1,2,75,100));
firstPanel.setMaximumSize(new Dimension(300,100));
/*Creates the buttons in the first sub panel*/
JButton[] btns = new JButton[2];
String bText[] = {"Calculate", "Clear"};
for (int i=0; i<2; i++) {
btns[i] = new JButton(bText[i]);
btns[i].setPreferredSize(new Dimension(100, 50));
btns[i].setActionCommand(bText[i]);
btns[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
/*JOptionPane.showMessageDialog(null, "Clicked "+choice);*/
JOptionPane.showMessageDialog(null, "Force = ");
}
});
firstPanel.add(btns[i]);
}
/*Creates the second sub panel*/
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new BorderLayout());
/*Creates the labels for the second sub panel*/
JLabel label = new JLabel("Calculate the Force of an Object", SwingConstants.CENTER);
secondPanel.add(label,BorderLayout.NORTH);
/*Creates the third sub Panel for entering values*/
JPanel thirdPanel = new JPanel();
thirdPanel.setLayout(new GridLayout(3,1,10,10));
thirdPanel.setMaximumSize(new Dimension(400,100));
/*Create labels and text fields for third sub panel*/
String lText[] = {"Mass of Body", "Acceleration of Body", "Force"};
JLabel[] lbls = new JLabel[3];
JTextField[] txts = new JTextField[3];
for (int i=0; i<3; i++) {
txts[i] = new JTextField();
lbls[i] = new JLabel(lText[i], SwingConstants.LEFT);
lbls[i].setPreferredSize(new Dimension(50, 50));
thirdPanel.add(lbls[i]);
thirdPanel.add(txts[i]);
}
mainPanel.add(secondPanel);
mainPanel.add(thirdPanel);
mainPanel.add(firstPanel);
frame.setContentPane(mainPanel);
frame.setVisible(true);
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createHomeScreen();
}
});
}
}
First drop the reliance on static, and instead, create an instance of InitScreen and call it's createHomeScreen method
public class InitScreen {
public void createHomeScreen() {
//...
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
InitScreen screen = new InitScreen();
screen.createHomeScreen();
}
});
}
Now, make txts and instance field of InitScreen and use it within your methods
public class InitScreen {
private JTextField[] txts;
public void createHomeScreen() {
//...
txts = new JTextField[3];
//...
}
This takes txts from a local context to a class instance context, meaning you can now access it from any method within InitScreen

Calling method from one class in other

I know that this kind of issue has been discussed here many times, but I'm confused. I'm totally beginner in Java and I honestly don't know what to do and I admit that I don't have that much time to read whole documentation provided by Oracle. Here's my problem:
I'm trying to program a GUI for my program that will be show interference of acoustic waves. Mathematical functionality doesn't matter in here. I've got two classes called Window and Sliders. Window is intended to be a 'main GUI class' and Sliders is supposed to inherit (?) from it.
This comes from another issue that I need to implement ActionListener in class Window and ChangeListener in Sliders class. I heard that one class can't implement several classes that's why I made two.
Now, I wrote a little bit chaotic those two classes, but I don't know how to combine them. It's really silly, but after C++ I'm pretty confused how to tell the program that it is supposed to show in one frame either buttons defined in Window class and sliders defined in Sliders class. Currently it shows only buttons I want to make it showing sliders too.
I'm very sorry for chaotic pseudo code, please help. Please, try to explain as simply as you can/possible. Please feel free to ignore overrided methods, they're not finished yet.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class Window extends JFrame implements ActionListener
{
private JButton showChord, playSound, getSample, getPlot;
private JLabel chordInfo;
private JPanel basicFunctions;
public Window()
{
init();
}
private void init()
{
setVisible(true);
setSize(new Dimension(1000,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
basicFunctions = new JPanel();
FlowLayout basicLayout = new FlowLayout();
basicFunctions.setLayout(basicLayout);
showChord = new JButton("Akord");
playSound = new JButton("Odtwórz");
getSample = new JButton("Pobierz dźwięk");
getPlot = new JButton("Pobierz wykres");
showChord.addActionListener(this);
playSound.addActionListener(this);
getSample.addActionListener(this);
getPlot.addActionListener(this);
basicFunctions.add(showChord);
basicFunctions.add(playSound);
basicFunctions.add(getSample);
basicFunctions.add(getPlot);
add(basicFunctions);
Sliders param = new Sliders();
}
public static void main(String[] args)
{
Window frame = new Window();
}
//Action Listener
#Override
public void actionPerformed(ActionEvent a)
{
Object event = a.getSource();
if(event == showChord)
{
}
else if(event == playSound)
{
}
else if(event == getSample)
{
}
else if(event == getPlot)
{
}
}
}
import java.awt.*;
import javax.swing.event.ChangeEvent;
import javax.swing.*;
import javax.swing.event.ChangeListener;
public class Sliders extends Window implements ChangeListener
{
private JPanel sliders, sliderSub;
private JTextField accAmplitude, accFrequency, accPhase;
private JSlider amplitude, frequency, phase;
private double amplitudeValue, frequencyValue, phaseValue;
public Sliders()
{
sliders = new JPanel();
sliders.setLayout(new FlowLayout());
amplitude = new JSlider(0,100,0);
amplitude.setMajorTickSpacing(10);
amplitude.setMinorTickSpacing(5);
amplitude.setPaintTicks(true);
amplitude.setPaintLabels(true);
frequency = new JSlider(0,10,0);
frequency.setMajorTickSpacing(1);
frequency.setMinorTickSpacing(1/10);
frequency.setPaintTicks(true);
frequency.setPaintLabels(true);
phase = new JSlider(0,1,0);
phase.setMinorTickSpacing(2/10);
phase.setPaintTicks(true);
phase.setPaintLabels(true);
accAmplitude = new JTextField();
accFrequency = new JTextField();
accPhase = new JTextField();
sliders.add(amplitude, BorderLayout.NORTH);
sliders.add(frequency, BorderLayout.CENTER);
sliders.add(phase, BorderLayout.SOUTH);
add(sliders);
}
#Override
public void stateChanged(ChangeEvent arg0)
{
}
}
I've done this so far, but those text fields just stopped showing sliders values and I don't know why. They are defined in the Parameters class and Window class. Can someone help? Additionally in the future I'd like to make those text fields editable so that you can set slider value by typing it in the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.event.*;
public class Window extends JPanel
{
private JMenuBar mainMenu = new JMenuBar();
private Plot plot = new Plot();
private Parameters param = new Parameters();
private JComboBox chooseChord = new JComboBox();
private JButton playSound = new JButton("Odtwórz");
private JButton getSample = new JButton("Pobierz dźwięk");
private JButton getPlot = new JButton("Pobierz wykres");
private JPanel mainPanel = new JPanel();
private JPanel subPanel = new JPanel();
private JPanel buttonsPanel = new JPanel();
private JPanel slidersPanel = new JPanel();
private JLabel chord = new JLabel("Akord:");
private JTextField aValue = new JTextField();
private JTextField fValue = new JTextField();
private JTextField pValue = new JTextField();
public Window()
{
mainPanel.setLayout(new FlowLayout());
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS));
slidersPanel.setLayout(new BorderLayout());
subPanel.setLayout(new BorderLayout());
chooseChord.addItem("A");
chooseChord.addItem("A#");
chooseChord.addItem("Ab");
chooseChord.addItem("B");
chooseChord.addItem("Bb");
chooseChord.addItem("C");
chooseChord.addItem("C#");
chooseChord.addItem("Cb");
chooseChord.addItem("D");
chooseChord.addItem("D#");
chooseChord.addItem("E");
chooseChord.addItem("F");
chooseChord.addItem("F#");
buttonsPanel.add(chord);
buttonsPanel.add(chooseChord);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(playSound);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(getSample);
buttonsPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonsPanel.add(getPlot);
buttonsPanel.setBorder(BorderFactory.createTitledBorder("Menu"));
slidersPanel.add(param);
JMenu langMenu = new JMenu("Język");
mainMenu.add(langMenu);
subPanel.add(buttonsPanel, BorderLayout.NORTH);
subPanel.add(slidersPanel, BorderLayout.SOUTH);
mainPanel.add(subPanel);
mainPanel.add(plot);
add(mainPanel);
param.addAmplitudeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent a)
{
double ampValue = param.getAmplitudeValue();
aValue.setText(String.valueOf(ampValue));
}
}
);
param.addFrequencyListener(new ChangeListener()
{
public void stateChanged(ChangeEvent f)
{
double frValue = param.getFrequencyValue();
fValue.setText(String.valueOf(frValue));
}
}
);
param.addPhaseListener(new ChangeListener()
{
public void stateChanged(ChangeEvent p)
{
double phValue = param.getPhaseValue();
pValue.setText(String.valueOf(phValue));
}
}
);
}
public JMenuBar getmainMenu()
{
return mainMenu;
}
private static void GUI()
{
Window mainPanel = new Window();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setJMenuBar(mainPanel.getmainMenu());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
GUI();
}
}
);
}
}
class Parameters extends JPanel
{
private JPanel pane = new JPanel();
private JPanel ampPanel = new JPanel();
private JPanel frPanel = new JPanel();
private JPanel phPanel = new JPanel();
private JSlider amplitude = new JSlider(0,100,0);
private JSlider frequency = new JSlider(0,10000,0);
private JSlider phase = new JSlider(0,180,0);
private JLabel pLabel = new JLabel("Faza");
private JLabel aLabel = new JLabel("Amplituda (dB)");
private JLabel fLabel = new JLabel("Częstotliwość (Hz)");
private JTextField preciseAmplitude = new JTextField(3);
private JTextField preciseFrequency = new JTextField(4);
private JTextField precisePhase = new JTextField(3);
public Parameters()
{
preciseAmplitude.setEditable(true);
preciseFrequency.setEditable(true);
precisePhase.setEditable(true);
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
ampPanel.setLayout(new FlowLayout());
frPanel.setLayout(new FlowLayout());
phPanel.setLayout(new FlowLayout());
amplitude.setMajorTickSpacing(10);
amplitude.setMinorTickSpacing(5);
amplitude.setPaintTicks(true);
amplitude.setPaintLabels(true);
frequency.setMajorTickSpacing(2000);
frequency.setMinorTickSpacing(100);
frequency.setPaintTicks(true);
frequency.setPaintLabels(true);
phase.setMajorTickSpacing(2/10);
phase.setPaintTicks(true);
phase.setPaintLabels(true);
setBorder(BorderFactory.createTitledBorder("Parametry fali"));
ampPanel.add(aLabel);
ampPanel.add(preciseAmplitude);
pane.add(ampPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(amplitude);
pane.add(Box.createRigidArea(new Dimension(0,10)));
frPanel.add(fLabel);
frPanel.add(preciseFrequency);
pane.add(frPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(frequency);
pane.add(Box.createRigidArea(new Dimension(0,10)));
phPanel.add(pLabel);
phPanel.add(precisePhase);
pane.add(phPanel);
pane.add(Box.createRigidArea(new Dimension(0,5)));
pane.add(phase);
pane.add(Box.createRigidArea(new Dimension(0,10)));
add(pane);
}
public int getAmplitudeValue()
{
return amplitude.getValue();
}
public int getFrequencyValue()
{
return frequency.getValue();
}
public int getPhaseValue()
{
return phase.getValue();
}
public void addAmplitudeListener(ChangeListener ampListener)
{
amplitude.addChangeListener(ampListener);
}
public void addFrequencyListener(ChangeListener frListener)
{
frequency.addChangeListener(frListener);
}
public void addPhaseListener(ChangeListener phListener)
{
phase.addChangeListener(phListener);
}
}
class Plot extends JPanel
{
private JPanel componentWave = new JPanel();
private JPanel netWave = new JPanel();
private JLabel componentLabel = new JLabel("Fale składowe");
private JLabel netLabel = new JLabel("Fala wypadkowa");
private JLabel wave = new JLabel("Wybierz falę składową");
private JPanel labels = new JPanel();
private JComboBox chooseWave = new JComboBox();
public Plot()
{
labels.setLayout(new BoxLayout(labels, BoxLayout.PAGE_AXIS));
componentWave.setBackground(new Color(255,255,255));
netWave.setBackground(new Color(255,255,255));
componentWave.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
netWave.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
componentWave.setPreferredSize(new Dimension(400,200));
netWave.setPreferredSize(new Dimension(400,200));
labels.add(wave);
labels.add(Box.createRigidArea(new Dimension(0,10)));
labels.add(chooseWave);
labels.add(componentLabel);
labels.add(componentWave);
labels.add(Box.createRigidArea(new Dimension(0,20)));
labels.add(netLabel);
labels.add(netWave);
add(labels);
}
}
Window is intended to be a 'main GUI class' and Sliders is supposed to inherit (?) from it.
Nope: this is a misuse of inheritance and will only lead to problems since the Windows instance that Sliders inherently is, is completely distinct from the displayed Windows instance. What you need to do is to pass references.
For example, the following code uses outside classes for the JButton and JMenuItem Actions (Actions are like ActionListeners on steroids), and uses a class that holds a JSlider that allows itside classes to attach listeners to the slider.
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Foo extends JPanel {
private static final long serialVersionUID = 1L;
private Action helloAction = new HelloAction("Hello", KeyEvent.VK_H);
private Action exitAction = new ExitAction("Exit", KeyEvent.VK_X);
private JMenuBar menuBar = new JMenuBar();
private JTextField sliderValueField = new JTextField(10);
private Bar bar = new Bar();
public Foo() {
sliderValueField.setEditable(false);
sliderValueField.setFocusable(false);
add(new JButton(helloAction));
add(new JButton(exitAction));
add(new JLabel("Slider Value: "));
add(sliderValueField);
add(bar);
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(new JMenuItem(exitAction));
fileMenu.add(new JMenuItem(helloAction));
menuBar.add(fileMenu);
bar.addSliderListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
int sliderValue = bar.getSliderValue();
sliderValueField.setText(String.valueOf(sliderValue));
}
});
}
public JMenuBar getJMenuBar() {
return menuBar;
}
private static void createAndShowGui() {
Foo mainPanel = new Foo();
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setJMenuBar(mainPanel.getJMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class HelloAction extends AbstractAction {
public HelloAction(String name, int mnemonic) {
super(name); // sets name property and gives button its title
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello!");
}
}
class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
if (win == null) {
// if no window, then a JMenuItem held in a JPopupMenu
JPopupMenu popup = (JPopupMenu) component.getParent();
component = popup.getInvoker();
win = SwingUtilities.getWindowAncestor(component);
}
win.dispose();
}
}
class Bar extends JPanel {
private JSlider slider = new JSlider(0, 100, 50);
public Bar() {
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setSnapToTicks(true);
setBorder(BorderFactory.createTitledBorder("Slider Panel"));
add(slider);
}
public int getSliderValue() {
return slider.getValue();
}
// one way to let outside classes listen for changes
public void addSliderListener(ChangeListener listener) {
slider.addChangeListener(listener);
}
}
You ask about decimal labels, and yes this can be done but requires use of a label table. For example,
JSlider slider = new JSlider(0, 100, 50);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(2);
Dictionary<Integer, JLabel> labels = new Hashtable<>();
for (int i = 0; i <= 100; i += 20) {
labels.put(i, new JLabel(String.format("%.1f", i / 200.0)));
}
slider.setLabelTable(labels);
Which displays as:
You would also have to translate the value back from int to its corresponding floating point number.

jframes array that contains objects- java

I am trying to make a program that I enter first name and last name and so on and then being about to view that information again.
I am using Java and Jframes
i have setup my interface with JTextfileds and Jlabels and a button
i am trying to make an array of objects so each array number will contain (firstname, lastname , and so on) and then i am going to print it out into a Jlist. i want to make it so when i prees my button it will input everything in my Jtextinputs in the first array
but i don't know how to do the array with objects i have started one but i need help thanks
i know that i need to use
ArrayList<> mylist = new ArrayList<Data>();
Data myTask = new Data("imput", "input");
myList.add(myTask);
But I don't understand how I use it
Thanks
that is my data.java file
package components;
Import Java.Io.Serializable;
public class Data implements Serializable {
static final long serialVersionUID = 1;
String name;
String description;
public Task(String Fname, String Lname) {
this.name = Fname;
this.description = Lname;
}
public String getName() {
return this.name;
}
public String getDescription() {
Return this.description;
}
interface file
public class DataDemo extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
//Name Label and TextField
protected static JLabel LbName;
protected static JTextField txtInputName;
//Description Label and TextField
protected static JLabel LbDescription;
protected static JTextField txtInputDescription;
//Submit Button
static JButton btnSubmit;
#SuppressWarnings("unchecked")
public DataDemo() {
//Name Label and TextField
LbName = new JLabel("Name:");
txtInputName = new JTextField(200);
//Description Label and TextField
LbDescription = new JLabel("Description:");
txtInputDescription = new JTextField(20);
//Submit Button
btnSubmit = new JButton("Done");
btnSubmit.addActionListener(this);
//Add Components to this container, using the default FlowLayout.
setLayout(null);
//Name
add(LbName);
add(txtInputName);
//Description
add(LbDescription);
add(txtInputDescription);
//button Submit
add(btnSubmit);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == btnSubmit)
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("DataDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
DataDemo newContentPane = new DataDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
//(x,y,with,height)
//Name interface position
LbName.setBounds(50, 70, 200, 25);
txtInputName.setBounds(200, 70, 200, 25);
//Description interface position
LbDescription.setBounds(50, 100, 200, 25);
txtInputDescription.setBounds(200, 100, 200, 25);
//button Submit
btnSubmit.setBounds(200, 150, 200, 25);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Did you try using
ArrayList<Data> mylist = new ArrayList<Data>();
That should allow you to create a proper Iterator and get your Data-Objects. Otherwise you will have to cast all Objects you retrieve from your list to Data, i.e.
ArrayList<> mylist = new ArrayList<>();
//add your Data-Objects here
for (Object o : mylist)
{
Data d = (Data) o;
//do something with d
}

A individual class for each Card in java swing CardLayout

For architecture and design purposes I would like to design my GUI with a class for each card in a Java Swing CardLayout. and then have a mainapp that builds the GUI. I am having trouble doing this right now.
I would like to example have a class for the main menu with all the button locations etc. and then just instantiate that card and add it to the layout in another class. Does anyone know how to achieve this?
Perhaps you want to give your class that uses the CardLayout a public loadCard method, something like
public void loadCard(JComponent component, String key) {
cardHolderPanel.add(component, key);
}
where cardHolderPanel is the container that holds the cards.
Since your creating classes to act as cards, consider having them all extend from a base abstract class or an interface that has a method that allows this class to hold its own key String. Either that or simply use the JComponent name property to have a component hold its own key String, one that can easily be obtained via getName().
For a more detailed answer, you may need to give us more details on your current application and its structure.
very simple example that held Swing Objects generated from different Java Classes
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OnTheFlyImageTest extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel cardPanel;
private CardLayout cardLayout;
public OnTheFlyImageTest() {
JPanel cp = new JPanel(new BorderLayout());
cp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout(5, 5);
cardPanel = new JPanel(cardLayout);
cp.add(cardPanel);
for (int i = 0; i < 100; i++) {// Create random panels for testing.
String name = "ImagePanel" + (i + 1);
String image = (i & 1) == 0 ? "foo.gif" : "bar.gif";
ImagePanel imgPanel = new ImagePanel(name, image);
cardPanel.add(imgPanel, name);
cardLayout.addLayoutComponent(imgPanel, name);
}
JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JButton prevButton = new JButton("< Previous");
prevButton.setActionCommand("Previous");
prevButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.previous(cardPanel);
}
});
buttonPanel.add(prevButton);
JButton nextButton = new JButton("Next >");
nextButton.setActionCommand("Next");
nextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(cardPanel);
}
});
buttonPanel.add(nextButton);
JPanel temp = new JPanel(new BorderLayout());
temp.add(buttonPanel, BorderLayout.LINE_END);
cp.add(temp, BorderLayout.SOUTH);
setContentPane(cp);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Test");
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new OnTheFlyImageTest().setVisible(true);
}
});
}
}
class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private String imgString;
private JLabel imgLabel;
public ImagePanel(String name, String imgString) {
setName(name);
this.imgString = imgString;
setLayout(new BorderLayout());
// Ensure size is correct even before any image is loaded.
setPreferredSize(new Dimension(640, 480));
}
#Override
public void setVisible(boolean visible) {
if (visible) {
System.err.println(getName() + ": Loading and adding image");
ImageIcon icon = new ImageIcon(imgString);
imgLabel = new JLabel(icon);
add(imgLabel);
}
super.setVisible(visible);
if (!visible) { // Do after super.setVisible() so image doesn't "disappear".
System.err.println(getName() + ": Removing image");
if (imgLabel != null) { // Before display, this will be null
remove(imgLabel);
imgLabel = null; // Hint to GC that component/image can be collected.
}
}
}
}

Categories

Resources