I have a simple GUI with 3 radio buttons and a button. I want the user to select a radio option, then upon clicking the button the user will be directed to a different Java UI depending upon which radio button they selected. Here is my method:
private void btnContinueActionPerformed(java.awt.event.ActionEvent evt)
{
if(rbCSV.isSelected())
{
}
else if(rbExcel.isSelected())
{
}
else if(rbDatabase.isSelected())
{
}
else
{
}
}
I am new to Java Swing, and not sure of the syntax that will allow me to direct the user to the next page. Sort of like a Wizard, I guess. Any help would be awesome! Thanks!
Recommendations:
Read the How to Use Radio Buttons tutorial
Read the How to Use CardLayout tutorial
Learn how to use a ButtonGroup, since you'll only want one button to be selected at a time
public final class RadioButtonDemo {
private static CardPanel cards;
private static Card cardOne;
private static Card cardTwo;
private static Card cardThree;
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("RB Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
cards = new CardPanel();
frame.getContentPane().add(cards);
frame.getContentPane().add(new ControlPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createCards(){
cardOne = new Card(
"Card 1",
new JLabel("This is card one"),
Color.PINK);
cardTwo = new Card(
"Card 2",
new JLabel("This is card two"),
Color.YELLOW);
cardThree = new Card(
"Card 3",
new JLabel("This is card three"),
Color.CYAN);
}
private static final class Card extends JPanel{
private final String name;
public Card(
final String name,
final JComponent component,
final Color c){
super();
this.name = name;
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setBackground(c);
add(component);
}
public final String getName(){
return name;
}
}
private static final class CardPanel extends JPanel{
public CardPanel(){
super(new CardLayout());
createCards();
add(cardOne, cardOne.getName());
add(cardTwo, cardTwo.getName());
add(cardThree, cardThree.getName());
}
}
private static final class ControlPanel extends JPanel{
private static JRadioButton showCardOneButton;
private static JRadioButton showCardTwoButton;
private static JRadioButton showCardThreeButton;
private static JButton showButton;
public ControlPanel(){
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(createJRadioButtonPanel());
add(createJButtonPanel());
}
private final JPanel createJRadioButtonPanel(){
final JPanel panel = new JPanel();
showCardOneButton = new JRadioButton(cardOne.getName());
showCardOneButton.setSelected(true);
showCardTwoButton = new JRadioButton(cardTwo.getName());
showCardThreeButton = new JRadioButton(cardThree.getName());
ButtonGroup group = new ButtonGroup();
group.add(showCardOneButton);
group.add(showCardTwoButton);
group.add(showCardThreeButton);
panel.add(showCardOneButton);
panel.add(showCardTwoButton);
panel.add(showCardThreeButton);
return panel;
}
private final JPanel createJButtonPanel(){
final JPanel panel = new JPanel();
showButton = new JButton("Show");
showButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
CardLayout cl = (CardLayout) cards.getLayout();
if(showCardOneButton.isSelected()){
cl.show(cards, showCardOneButton.getText());
}
else if(showCardTwoButton.isSelected()){
cl.show(cards, showCardTwoButton.getText());
}
else if(showCardThreeButton.isSelected()){
cl.show(cards, showCardThreeButton.getText());
}
}
});
panel.add(showButton);
return panel;
}
}
}
JPanel panelCSV, panelExcel, panelDatabase;
CardLayout cardLayout = new CardLayout();
JPanel pagePanel = new JPanel(cardLayout);
pagePanel.add(panelCSV, "CSV");
pagePanel.add(panelExcel, "Excel");
pagePanel.add(panelDatabase, "Database");
public void btnContinueActionPerformed(ActionEvent e) {
if ( rbCSV.isSelected() ) {
cardLayout.show(pagePanel, "CSV");
} else if ( rbExcel.isSelected() ) {
cardLayout.show(pagePanel, "Excel");
} else if ( rbDatabase.isSelected() ) {
cardLayout.show(pagePanel, "Database");
} else {
// ....
}
}
Related
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 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.
I need a little help on java temperature conversion GUI
so here is my code for result
public class ResultsPanel extends JPanel
{
private JLabel result;
private JPanel panel;
final int WIDTH_CONST=120;
final int HEIGHT_CONST=60;
public ResultsPanel()
{
setPreferredSize(new Dimension(WIDTH_CONST, HEIGHT_CONST));
setBorder(BorderFactory.createTitledBorder("Result"));
result = new JLabel();
add(result);
}
public void setResultLabel(String str)
{
result.setText(str);
}
public void setResultLabel()
{
result.setText("");
}
}
so what I'm trying to do is, that when i click on the convert button i want to label the result
and here is my button handler class:
private class ConvertButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//calculate and convert temperatures
//convert the temperature into String
ResultsPanel result = new ResultsPanel();
String temp; // temperature in string
result.setResultLabel(temp);
}
}
but it doesn't seem like it's printing out the result,
any help appreciated, thanks
update :
here is my tempGUI class:
public class TempGUI extends JFrame
{
private BannerPanel banner;
private TypePanel type;
private TemperaturePanel temperature;
private ResultsPanel results;
private JPanel buttonPanel;
private JButton convert;
private JButton clear;
private JButton exit;
public TempGUI()
{
setTitle("Temperature Concverter GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
banner = new BannerPanel();
type = new TypePanel();
temperature = new TemperaturePanel();
results = new ResultsPanel();
buildButtonPanel();
add(banner, BorderLayout.NORTH);
add(type, BorderLayout.WEST);
add(temperature, BorderLayout.CENTER);
add(results, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void buildButtonPanel()
{
buttonPanel = new JPanel();
convert = new JButton("Convert");
clear = new JButton("Clear");
exit = new JButton("Exit");
convert.addActionListener(new ConvertButtonHandler());
clear.addActionListener(new ClearButtonHandler());
exit.addActionListener(new ExitButtonHandler());
buttonPanel.add(convert);
buttonPanel.add(clear);
buttonPanel.add(exit);
}
private class ConvertButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
double celsius = 0, fahrenheit = 0;
DecimalFormat decimalFormatter = new DecimalFormat("0,00");
TypePanel type = new TypePanel();
TemperaturePanel temp = new TemperaturePanel();
ResultsPanel result = new ResultsPanel();
String temp1 = "Test";
result.setResultLabel(temp1);
add(result);
}
}
private class ClearButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
ResultsPanel results = new ResultsPanel();
results.setResultLabel();
TemperaturePanel temp = new TemperaturePanel();
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
You're creating the ResultsPanel but you're not adding it to any frame. Thus, the ResultsPanel is not displayed. You will have to create a frame for the ResultsPanel or add it to an existing frame like this yourFrame.add(result).
I know it's something to do with how I've set it up and the actionlistener not being correctly set to the frame or something but I just can't get my hear around it. If someone could point me in the right direction I'd be much obliged. Sorry for noob question.
Here's what I have:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main implements ActionListener {
JPanel cardHolder;
public static final String HOME_CARD = "Home";
public static final String BLUE_PANEL = "Blue Panel";
public static final String RED_PANEL = "Red Panel";
public static final String ORANGE_PANEL = "Orange Panel";
public static JButton home = new JButton("Home");
public static JButton bluePanel = new JButton("Blue Card");
public static JButton redPanel = new JButton("Red Panel");
public static JButton orangePanel = new JButton("Orange Panel");
public static JPanel createCardHolderPanel() {
JPanel cardHolder = new JPanel(new CardLayout());
cardHolder.setBorder(BorderFactory.createTitledBorder("Card Holder Panel"));
cardHolder.add(createHomeCard(), HOME_CARD);
cardHolder.add(createBluePanel(), BLUE_PANEL);
cardHolder.add(createRedPanel(), RED_PANEL);
cardHolder.add(createOrangePanel(), ORANGE_PANEL);
return cardHolder;
}
private static JPanel createOrangePanel() {
JPanel orangePanel = new JPanel();
orangePanel.setBackground(Color.orange);
return orangePanel;
}
private static Component createRedPanel() {
JPanel redPanel = new JPanel();
redPanel.setBackground(Color.red);
return redPanel;
}
private static Component createBluePanel() {
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.blue);
return bluePanel;
}
private static Component createHomeCard() {
JPanel homePanel = new JPanel();
homePanel.setBackground(Color.GRAY);
return homePanel;
}
public static JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(4, 0, 5, 5));
buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
buttonPanel.add(home);
buttonPanel.add(bluePanel);
buttonPanel.add(redPanel);
buttonPanel.add(orangePanel);
return buttonPanel;
}
public static JPanel createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(BorderFactory.createTitledBorder("Main Content Pane"));
contentPane.setBackground(Color.WHITE);
contentPane.setPreferredSize(new Dimension(499, 288));
contentPane.add(createButtonPanel(), BorderLayout.WEST);
contentPane.add(createCardHolderPanel(),BorderLayout.CENTER);
return contentPane;
}
public static JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu users = new JMenu("Users");
JMenu options = new JMenu("Options");
JMenu help = new JMenu("Help");
menuBar.add(file);
menuBar.add(users);
menuBar.add(options);
menuBar.add(help);
return menuBar;
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("Simple CardLayout Program");
frame.setContentPane(createContentPane());
frame.setJMenuBar(createMenuBar());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == home) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
cardLayout.show(cardHolder, HOME_CARD);
}
if (e.getSource() == bluePanel) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
cardLayout.show(cardHolder, BLUE_PANEL);
}
if (e.getSource() == redPanel) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
cardLayout.show(cardHolder, RED_PANEL);
}
if (e.getSource() == orangePanel) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
cardLayout.show(cardHolder, ORANGE_PANEL);
}
}
}
Others have suggested listening to the buttons; in addition:
Prefer the lowest accessibility consistent with use, e.g. private rather than public.
Don't make everything static.
Use static for immutable constants used throughout the class.
Use class variables rather than static members for content.
Don't repeat your self, e.g. initialize cardLayout just once in your actionPerformed)().
Use parameters rather than separate methods for each color, e.g.
private JPanel createColorPanel(Color color) {...}
Revised code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main implements ActionListener {
private static final String HOME_CARD = "Home";
private static final String BLUE_PANEL = "Blue Panel";
private static final String RED_PANEL = "Red Panel";
private static final String ORANGE_PANEL = "Orange Panel";
private JPanel cardHolder;
private JButton homeButton = new JButton("Home");
private JButton blueButton = new JButton("Blue Card");
private JButton redButton = new JButton("Red Panel");
private JButton orangeButton = new JButton("Orange Panel");
public JPanel createCardHolderPanel() {
cardHolder = new JPanel(new CardLayout());
cardHolder.setBorder(BorderFactory.createTitledBorder("Card Holder Panel"));
cardHolder.add(createColorPanel(Color.gray), HOME_CARD);
cardHolder.add(createColorPanel(Color.blue), BLUE_PANEL);
cardHolder.add(createColorPanel(Color.red), RED_PANEL);
cardHolder.add(createColorPanel(Color.orange), ORANGE_PANEL);
return cardHolder;
}
private JPanel createColorPanel(Color color) {
JPanel panel = new JPanel();
panel.setBackground(color);
return panel;
}
public JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(4, 0, 5, 5));
buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
buttonPanel.add(homeButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);
buttonPanel.add(orangeButton);
homeButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
orangeButton.addActionListener(this);
return buttonPanel;
}
public JPanel createContentPane() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createTitledBorder("Main Content Pane"));
panel.setBackground(Color.WHITE);
panel.setPreferredSize(new Dimension(499, 288));
panel.add(createButtonPanel(), BorderLayout.WEST);
panel.add(createCardHolderPanel(), BorderLayout.CENTER);
return panel;
}
public JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu users = new JMenu("Users");
JMenu options = new JMenu("Options");
JMenu help = new JMenu("Help");
menuBar.add(file);
menuBar.add(users);
menuBar.add(options);
menuBar.add(help);
return menuBar;
}
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
if (e.getSource() == homeButton) {
cardLayout.show(cardHolder, HOME_CARD);
}
if (e.getSource() == blueButton) {
cardLayout.show(cardHolder, BLUE_PANEL);
}
if (e.getSource() == redButton) {
cardLayout.show(cardHolder, RED_PANEL);
}
if (e.getSource() == orangeButton) {
cardLayout.show(cardHolder, ORANGE_PANEL);
}
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("Simple CardLayout Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main main = new Main();
frame.setJMenuBar(main.createMenuBar());
frame.add(main.createContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You have not set an action listener for any of the buttons. Implementing the actionPerformed method of the interface does not automatically set an action listener for the buttons. You have to call the addActionListener method which in your case would look like the following since your class implements the ActionListener Interface.
public static JButton home = new JButton("Home").addActionListener(this);
public static JButton bluePanel = new JButton("Blue Card").addActionListener(this);
public static JButton redPanel = new JButton("Red Panel").addActionListener(this);
public static JButton orangePanel = new JButton("Orange Panel").addActionListener(this);
I'm working on a downloader which looks like this at the moment:
The JFrame uses a BorderLayout.
In the NORTH, I have a JPanel(FlowLayout). In the SOUTH there is also a JPanel(FlowLayout), in the WEST I just have a JTextArea (in a JScrollPane). This is all shown correctly. However, in the EAST I currently have a JPanel(GridLayout(10, 1)).
I want to show up to 10 JProgressBars in the EAST section which are added and removed from the panel dynamically. The problem is, I can not get them to look like I want to them to look: I want the JProgressBars' width to fill up the entire EAST section because 1) This gives the app a more symmetrical look and 2) The ProgressBars may contain long strings that don't fit at the moment. I've tried putting the JPanel that contains the GridLayout(10, 1) in a flowlayout and then put that flowlayout in the EAST section, but that didn't work either.
My code (SSCCE) is currently as follows:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
new DownloadFrame();
}
private static class DownloadFrame extends JFrame {
private JButton downloadButton;
private JTextField threadIdTextField;
private JTextArea downloadStatusTextArea;
private JScrollPane scrollPane;
private JTextField downloadLocationTextField;
private JButton downloadLocationButton;
private JPanel North;
private JPanel South;
private JPanel ProgressBarPanel;
private Map<String, JProgressBar> progressBarMap;
public DownloadFrame() {
InitComponents();
InitLayout();
AddComponents();
AddActionListeners();
setVisible(true);
setSize(700, 300);
}
private void InitComponents() {
downloadButton = new JButton("Dowload");
threadIdTextField = new JTextField(6);
downloadStatusTextArea = new JTextArea(10, 30);
scrollPane = new JScrollPane(downloadStatusTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
downloadLocationTextField = new JTextField(40);
downloadLocationButton = new JButton("...");
North = new JPanel();
South = new JPanel();
ProgressBarPanel = new JPanel();
progressBarMap = new HashMap<String, JProgressBar>();
}
private void InitLayout() {
North.setLayout(new FlowLayout());
South.setLayout(new FlowLayout());
ProgressBarPanel.setLayout(new GridLayout(10, 1));
}
private void AddComponents() {
North.add(threadIdTextField);
North.add(downloadButton);
add(North, BorderLayout.NORTH);
add(ProgressBarPanel, BorderLayout.EAST);
South.add(downloadLocationTextField);
South.add(downloadLocationButton);
add(South, BorderLayout.SOUTH);
add(scrollPane, BorderLayout.WEST);
}
private void AddActionListeners() {
downloadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addNewProgessBar(threadIdTextField.getText());
}
});
}
public void addNewProgessBar(String threadId) {
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBarMap.put(threadId, progressBar);
drawProgessBars();
}
void drawProgessBars() {
ProgressBarPanel.removeAll();
for (JProgressBar progressBar : progressBarMap.values()) {
ProgressBarPanel.add(progressBar);
}
validate();
repaint();
}
}
}
Thanks in advance.
EDIT
Easiest solution: change
add(ProgressBarPanel, BorderLayout.EAST);
to
add(ProgressBarPanel, BorderLayout.CENTER);
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
new DownloadFrame();
}
private static class DownloadFrame extends JFrame {
private JButton downloadButton;
private JTextField threadIdTextField;
private JTextArea downloadStatusTextArea;
private JScrollPane scrollPane;
private JTextField downloadLocationTextField;
private JButton downloadLocationButton;
private JPanel North;
private JPanel South;
private JPanel ProgressBarPanel;
private Map<String, JProgressBar> progressBarMap;
public DownloadFrame() {
InitComponents();
AddComponents();
AddActionListeners();
pack();
setVisible(true);
//setSize(700, 300);
}
private void InitComponents() {
setLayout(new BorderLayout());
downloadButton = new JButton("Dowload");
threadIdTextField = new JTextField(6);
downloadStatusTextArea = new JTextArea(10, 30);
scrollPane = new JScrollPane(downloadStatusTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
downloadLocationTextField = new JTextField(40);
downloadLocationButton = new JButton("...");
North = new JPanel(new FlowLayout());
South = new JPanel(new FlowLayout());
ProgressBarPanel = new JPanel(new GridLayout(0, 1));
ProgressBarPanel.setBorder(new LineBorder(Color.black));
ProgressBarPanel.setPreferredSize(new Dimension(300,20));
progressBarMap = new HashMap<String, JProgressBar>();
}
private void AddComponents() {
North.add(threadIdTextField);
North.add(downloadButton);
add(North, BorderLayout.NORTH);
add(ProgressBarPanel, BorderLayout.EAST);
South.add(downloadLocationTextField);
South.add(downloadLocationButton);
add(South, BorderLayout.SOUTH);
add(scrollPane, BorderLayout.WEST);
}
private void AddActionListeners() {
downloadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addNewProgessBar(threadIdTextField.getText());
}
});
}
public void addNewProgessBar(String threadId) {
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBarMap.put(threadId, progressBar);
drawProgessBars();
}
void drawProgessBars() {
ProgressBarPanel.removeAll();
for (JProgressBar progressBar : progressBarMap.values()) {
ProgressBarPanel.add(progressBar);
}
validate();
repaint();
}
}
}
well. that possible, but in your example CENTER area occupated some Rectangle, its hard to reduce/remove CENTER area to the zero Size
to the North JPanel (BorderLayout) place another JPanel and put it to the EAST (with LayoutManager would be GridLayout(1,2,10,10)) and put here two JComponents JTextField - threadIdTextField and JButton - downloadButton, there you are needed setPreferredSize 1) for JComponents (correct way) or 2) for whole JPanel (possible way too)
JScrollPane with JTextArea must be placed to the CENTER area
JPanel with JProgressBars place to EAST, but again set same PreferredSize as for JPanel with JTextField and JButton from the NORTH
SOUTH JPanel remains without changes
Please post a compilable runnable small program for the quickest best help, an SSCCE.
Suggestions include using GridLayout(0, 1) (variable number of rows, one column), or display the JProgressBars in a JList that uses a custom renderer that extends JProgressBar.
Edit 1:
I know that Andrew has already posted the accepted answer (and 1+ for an excellent answer), but I just wanted to demonstrate that this can be done readily with a JList, something like so:
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.Random;
import javax.swing.*;
public class EastProgressList extends JPanel {
private DefaultListModel myListModel = new DefaultListModel();
private JList myList = new JList(myListModel);
private JTextField downloadUrlField = new JTextField(10);
public EastProgressList() {
JButton downLoadBtn = new JButton("Download");
downLoadBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
downloadAction();
}
});
JPanel northPanel = new JPanel();
northPanel.add(new JLabel("File to Download:"));
northPanel.add(downloadUrlField);
northPanel.add(Box.createHorizontalStrut(15));
northPanel.add(downLoadBtn);
myList.setCellRenderer(new ProgressBarCellRenderer());
JScrollPane eastSPane = new JScrollPane(myList);
eastSPane.setPreferredSize(new Dimension(200, 100));
setLayout(new BorderLayout());
add(new JScrollPane(new JTextArea(20, 30)), BorderLayout.CENTER);
add(northPanel, BorderLayout.NORTH);
add(eastSPane, BorderLayout.EAST);
}
private void downloadAction() {
String downloadUrl = downloadUrlField.getText();
final MyData myData = new MyData(downloadUrl);
myListModel.addElement(myData);
myData.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(MyData.VALUE)) {
myList.repaint();
if (myData.getValue() >= 100) {
myListModel.removeElement(myData);
}
}
}
});
}
private class ProgressBarCellRenderer extends JProgressBar implements ListCellRenderer {
protected ProgressBarCellRenderer() {
setBorder(BorderFactory.createLineBorder(Color.blue));
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
//setText(value.toString());
MyData myData = (MyData)value;
setValue(myData.getValue());
setString(myData.getText());
setStringPainted(true);
return this;
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("EastProgressList");
frame.getContentPane().add(new EastProgressList());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyData {
public static final int TIMER_DELAY = 300;
public static final String VALUE = "value";
protected static final int MAX_DELTA_VALUE = 5;
private String text;
private int value = 0;
private Random random = new Random();
private PropertyChangeSupport pcSupport = new PropertyChangeSupport(this);
public MyData(String text) {
this.text = text;
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int deltaValue = random.nextInt(MAX_DELTA_VALUE);
int newValue = value + deltaValue;
if (newValue >= 100) {
newValue = 100;
((Timer)e.getSource()).stop();
}
setValue(newValue);
}
}).start();
}
public String getText() {
return text;
}
public int getValue() {
return value;
}
public void setValue(int value) {
int oldValue = this.value;
this.value = value;
PropertyChangeEvent pcEvent = new PropertyChangeEvent(this, VALUE, oldValue, value);
pcSupport.firePropertyChange(pcEvent);
}
public void addPropertyChangeListener(PropertyChangeListener pcListener) {
pcSupport.addPropertyChangeListener(pcListener);
}
}
This results in a GUI looking like so: