Switch in between JList in the JScrollPane - java

I'm recently working on a project- Bus Ticket Machine. This is a program which helps the user to print their tickets.
I have one screen (destPanel) where I display a list of cities to be chosen (JList departures).
Once the user choses a city the addListSelectionListener of the first JList will save and return a timetable (JList timetable) for the user to choose again and this time save the chosen departure for printing on the ticket later on.
I cannot get the addListSelectionListener to stop when the timetable is displayed. This in order to be able to select a departure to be saved for printing the ticket.
I've added my three classes showing what I've been working on.
Class one:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Arrays;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TicketGUI extends JFrame
{
public static void main(String[] args)
{
new TicketGUI();
}
private JPanel destPanel = new JPanel();
private JPanel departPanel = new JPanel();
private JPanel payPanel = new JPanel();
private JButton[] buttons;
// Display size
private final int WIDTH = 310;
private final int HEIGHT = 150;
JList departJList;
JList defltList;
Vector<Enum> listContent = new Vector<Enum>();
//Following line used for adding info to display JList.
//Vector<Object> listContent = new Vector<Object>();
JList timeTable; //Not being used.
private DefaultListModel listModel; //Not being used.
Vector<String> newListContent = new Vector<String>(); //Not being used.
JTextArea textArea = new JTextArea();
JTextField payField = new JTextField(15);
public TicketGUI()
{
this.setTitle("Bus Ticket Machine");
setLayout(new BorderLayout());
JPanel agePanel = new JPanel();
JRadioButton adultButton = new JRadioButton("Adult");
adultButton.setSelected(true);
JRadioButton studentButton = new JRadioButton("Student");
JRadioButton childButton = new JRadioButton("Children");
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(adultButton);
group.add(studentButton);
group.add(childButton);
JPanel bPanel = new JPanel();
bPanel.setMaximumSize(new Dimension(100, 100));
bPanel.setLayout(new GridLayout(4, 3));
buttons= new JButton[12];
for (int i=0; i<12; i++)
{
buttons[i]=new JButton();
//buttons[i].addActionListener(this);
}
for (int i=1; i<10; i++)
{
buttons[i-1].setText(""+i);
bPanel.add(buttons[i-1]);
}
buttons[9].setText("X");
bPanel.add(buttons[9]);
buttons[10].setText("0");
bPanel.add(buttons[10]);
buttons[11].setText("OK");
bPanel.add(buttons[11]);
payField.setText("Card Number");
payField.setEditable(false);
payPanel.setLayout(new BorderLayout());
payPanel.add(payField, BorderLayout.NORTH);
// Display
// listContent.add("London");
// listContent.add("Bristol");
// listContent.add("Sheffield");
// listContent.add("Birmingham");
// listContent.add("...");
// listContent.add("Here under list to be displayed after choosing a city");
// listContent.add("1. London -> Bristol Depart: 11:45 Arrives: 13:15");
// listContent.add("2. London -> Bristol Depart: 12:30 Arrives: 15:00");
// listContent.add("3. London -> Bristol Depart: 13:45 Arrives: 16:15");
// listContent.add("4. London -> Bristol Depart: 14:30 Arrives: 17:00");
// listContent.add("...");
// listContent.add("Your Journey");
// listContent.add("Ticket: Adult");
// listContent.add("From: London ");
// listContent.add("Going to: Bristol");
// listContent.add("Leaving: 11:45");
// listContent.add("Fare: £ 18.00");
listContent = new Vector<Enum>(Arrays.asList(EnumCity.values()));
System.out.print(listContent + "one");
// defltList = new JList(listContent);
//
// System.out.print(defltList);
departJList = new JList(listContent);
// departJList.add(listContent);
System.out.print("\n\n");
System.out.print(departJList + "two");
timeTable = new JList();
departJList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
TimeTable selected = new TimeTable();
selected.setTimeTable();
newListContent.addAll(selected.getTimeTable());
// timeTable.setListData(newListContent.toArray());
// departJList.setListData(newListContent);
}
System.out.println(newListContent);
// timeTable.setListData(newListContent.toArray());
departJList.setListData(newListContent);
// departJList.setListData(newListContent);
}
});
JScrollPane m_clScrollpane = new JScrollPane(departJList);
m_clScrollpane.setPreferredSize(new Dimension(WIDTH, HEIGHT));
JPanel farePanel = new JPanel(new GridLayout(4, 1));
farePanel.add(adultButton);
farePanel.add(studentButton);
farePanel.add(childButton);
JTextField tf = new JTextField("£ 0.00");
tf.setEditable(false);
farePanel.add(tf);
destPanel.add(farePanel);
destPanel.add(m_clScrollpane);
payPanel.add(bPanel);
add(destPanel);
add(payPanel, BorderLayout.EAST);
setVisible(true);
pack();
addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent evt) {
dispose();
System.exit(0);
}
});
}
}
Class two:
public enum EnumCity {
London,
Bristol,
Sheffield,
Birmingham
}
Class three:
import java.util.Vector;
public class TimeTable {
private String timeTable;
public TimeTable()
{
}
public String setTimeTable()
{
return this.timeTable;
}
public Vector<String> getTimeTable()
{
Vector<String> timeList = new Vector<String>();
timeList.addElement("1. London -> Bristol Depart: 11:45 Arrives: 13:15");
timeList.addElement("2. London -> Bristol Depart: 12:30 Arrives: 15:00");
timeList.addElement("3. London -> Bristol Depart: 13:45 Arrives: 16:15");
timeList.addElement("4. London -> Bristol Depart: 14:30 Arrives: 17:00");
return timeList;
}
}

Instead of replacing the data in the list (which is a good idea generally), you could establish two different lists, one that manages list of cities and one that managers the list of time tables.
Then using a CardLayout, you could switch between them.
This means that you don't need to worry about switching selection listeners each time you switch the data.

One way to stop a listener from working is to remove it. If you are set on swapping the data in your list, you could do:
departJList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
// ******* added **********
((JList)e.getSource()).removeListSelectionListener(this);
TimeTable selected = new TimeTable();
selected.setTimeTable();
newListContent.addAll(selected.getTimeTable());
}
System.out.println(newListContent);
departJList.setListData(newListContent);
}
});

Related

Multiple Selection with JList and Pairing Pngs

I'm quite new to Java Programming and I found this code on the internet. It works fine there is no problem. I downloaded the png's of every fruit and I want to see them when I click on them instead of seeing their names. For example, if I click only apple, I want to see the png of apple. But if I use shift and multiple select grape and banana, I want to see their pngs at the right. (If it is possible of course)
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Ğ extends JFrame
{
//Sample 02: Create a Label
JLabel label = new JLabel();
public Ğ(String title) throws HeadlessException
{
super(title);
//Sample 01: Set Size and Position
setBounds(100, 100, 200, 200);
Container ControlHost = getContentPane();
ControlHost.setLayout(new GridLayout(1,1));
//Sample 03: Create List of Fruit Items
String[] Fruits = new String[10];
Fruits[0] = "Apple";
Fruits[1] = "Mango";
Fruits[2] = "Banana";
Fruits[3] = "Grapes";
Fruits[4] = "Cherry";
Fruits[5] = "Lemon";
Fruits[6] = "Orange";
Fruits[7] = "Strawberry";
Fruits[8] = "Watermelon";
Fruits[9] = "Ananas";
//Sample 04: Create JList to Show Fruit Name
JList ListFruits = new JList(Fruits);
ListFruits.setVisibleRowCount(10);
//Sample 05: Hand-Over the JList to ScrollPane & Display
JScrollPane jcp = new JScrollPane(ListFruits);
ControlHost.add(jcp);
ControlHost.add(label);
ListFruits.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//Sample 06: Handle the JList Event
ListFruits.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
String strFruits = "";
List<String> SelectedFruits = ListFruits.getSelectedValuesList();
for(String Fruit: SelectedFruits)
strFruits = strFruits + Fruit + ",";
strFruits = strFruits.substring(0, strFruits.length()-1);
label.setText(strFruits);
}
});
}
}
And this is the main class of course
import javax.swing.JFrame;
public class Fruits {
public static void main(String[] args) {
// TODO Auto-generated method stub
Ğ frame = new Ğ ("Fruits");
frame.setVisible(true);
}
}

How to make the "proximo"(next) button work and move the rocket(foguete)

I need to make my rocket move accordingly to the correct asnwer, if he(she) get it right, it will move(from the planet (left) to the (right) planet, else, it will do nothing, i have a counter for the right question, but i don't know what to do next.
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.HashMap;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Jogo0 extends JFrame implements ActionListener{
my variables
JPanel QUIZ;
JRadioButton opcao1;//choice1
JRadioButton opcao2;//choice2
JRadioButton opcao3;//choice3
ButtonGroup escolha;//buttongroup
JLabel questao; //question
JButton proximo; //next button
String [] [] alternativa; //alternatives
String [] [] correta; //correct answer
int acerto; //my counter
int posifogx = 0;
int posifogy = 300;
the images to the code, rocket, background, planets
ImageIcon imagfogut = new v ImageIcon(getClass().getResource("Foguetao2.gif"));
ImageIcon imagespac = new ImageIcon(getClass().getResource("Background.jpg"));
ImageIcon imageplantale = new ImageIcon(getClass().getResource("giphy.gif"));
ImageIcon imageterra = new ImageIcon(getClass().getResource("terra.gif"));
JLabel fog = new JLabel (imagfogut);
JLabel background = new JLabel (imagespac);
JLabel planetale = new JLabel (imageplantale);
JLabel terra = new JLabel (imageterra);
my method jogo, that will run the whole game
public Jogo0 (){
Janela(); //window
Imagens(); //img
QuizMetodo(); //my quizmethod
}
public void Imagens (){ //imgs
background.setBounds(0, 0, 1920, 1080);
fog.setBounds(posifogx, posifogy, 300, 200);
planetale.setBounds(-150, 300, 259, 259);
terra.setBounds(1000, 0, 379, 379);
}
public void Janela()//window {
setTitle("Game");
setLocation(0,0);
setVisible(true);
setSize(1920,1080);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(fog);
add(planetale);
add(terra);
add(background);
}
public void foguetex(int moverfoguetex) { //position of the rocket
this.posifogx = moverfoguetex;
moverfoguetex = moverfoguetex + 100;
}
public void foguetey(int moverfoguetey) {
this.posifogy = moverfoguetey;
moverfoguetey = moverfoguetey + 100;
}
public synchronized void QuizMetodo(){
questoes();
Container cont=getContentPane();
cont.setLayout(null);
cont.setBackground(Color.GRAY);
escolha=new ButtonGroup();
opcao1=new JRadioButton("Opção1",true);
opcao2=new JRadioButton("Opção2",false);
opcao3=new JRadioButton("Opção3",false);
escolha.add(opcao1);
escolha.add(opcao2);
escolha.add(opcao3);
questao= new JLabel("Salve seu planeta!");
questao.setForeground(Color.WHITE);
questao.setFont(new Font("tahoma", Font.BOLD, 14));
proximo=new JButton("Proximo");
proximo.setForeground(Color.BLACK);
proximo.addActionListener(aa);
opcao1.addActionListener(aa);
opcao2.addActionListener(aa);
opcao3.addActionListener(aa);
QUIZ=new JPanel();
QUIZ.setBackground(Color.DARK_GRAY);
QUIZ.setLocation(250,530);
QUIZ.setSize(800,150);
QUIZ.setLayout(new GridLayout(6,2));
QUIZ.add(questao);
QUIZ.add(opcao1);
QUIZ.add(opcao2);
QUIZ.add(opcao3);
QUIZ.add(proximo);
cont.add(QUIZ);
setVisible(true);
acerto = 0;
i = acerto;
lerqr(acerto);
}
public String getSelection(){
String selectedChoice=null;
Enumeration<AbstractButton> buttons=escolha.getElements();
while(buttons.hasMoreElements())
{
JRadioButton temp=(JRadioButton)buttons.nextElement();
if(temp.isSelected())
{
selectedChoice=temp.getText();
}
}
return(selectedChoice);
}
ActionListener aa = new ActionListener(){ //**I DONT KNOW WHAT TO DO HERE**
public void actionPerformed(ActionEvent e) {
}
};
public void questoes() { //questions
alternativa = new String [10][4];
alternativa[0][0] ="Qual é o composição química da água?";
alternativa[0][1] = "(2) Hidrogênio e (1) Carbono";
alternativa[0][2] = "(1) Hidroênio e (2) Oxigênio";
alternativa[0][3] = "(2) Hidrogênio e (1) Oxigênio";
alternativa[1][0] = "Pra que serve o Protocolo de Kyoto?";
alternativa[1][1] = "Defesa dos animais";
alternativa[1][2] = "Proteção contra emissão de gases";
alternativa[1][3] = "Codigo da reciclagem";
correta = new String [10] [2];
correta[0][0] = "Qual é o composição química da água?";
correta[0][1] = "(2) Hidrogênio e (1) Oxigênio";
correta [1][0] = "Pra que serve o Protocolo de Kyoto?";
correta [1][1] = "Proteção contra emissão de gases";
}
public void lerqr(int id){
questao.setText(" "+alternativa[id][0]);
opcao1.setText(alternativa[id][1]);
opcao2.setText(alternativa[id][2]);
opcao3.setText(alternativa[id][3]);
opcao1.setSelected(true);
}
public static void main(String[] args) { //my main method
new Jogo0();
}
I don't exactly know if you need the methods foguetex(); and foguetey(); in the way you implemented them but the last line in both methods doesn't seem to affect the program in any way.
To make the rocket move and calculate the movement you could simply modify the foguetex(); method like this (or write a method with a different name if you also need foguetex(); for something else in the code):
public void foguetex(int moverfoguetex) { // position of the rocket
this.posifogx = moverfoguetex + 100;
}
This will cause the value posifogx to get updated to the new x-value where the rocket should be (you can also modify foguetey(); if needed). After doing this you want to update the position of your JLabel displaying the rocket.
Therefore you reassign the bounds of the JLabel in the ActionListener similar to this (you possibly want to adapt it to the ActionListener you wrote yourself):
proximo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
foguetex(posifogx); //calculating new x-position
fog.setBounds(posifogx, posifogy, 300, 200); //updating the label's position
}
});
Hope this helps you.

Radio button event handlers

I'm having some trouble with a java project. I've made an empty GUI interface, and now I need to add some functionality to it. I'm stuck, however, on how to go about that. The basic layout has 4 radio buttons, Rectangle, Box, Circle, and Cylinder. I have a group panel that has 4 separate panels that each have text boxes with labels for entering height, length, width, and radius. Here's how it looks: GUI layout. Depending on the radio button that is selected, certain boxes that aren't needed should be hidden. For example, if Rectangle is selected, only the boxes for length and width should be visible.
The main frame that will display everything is here:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import java.awt.Font;
public class GUIFrame extends JFrame
{
//private final BorderLayout layout;
private final FlowLayout layout;
private final JLabel lblTitle;
private final JButton btnProc;
public GUIFrame()
{
super("GUI Layout");
Font titleFont = new Font("Verdana", Font.BOLD, 26);
btnProc = new JButton("Click to Process");
lblTitle = new JLabel("Figure Center");
lblTitle.setFont(titleFont);
widthPanel myWidth = new widthPanel();
myWidth.setLocation(0, 400);
lengthPanel myLength = new lengthPanel();
heightPanel myHeight = new heightPanel();
radiusPanel myRadius = new radiusPanel();
radioButtonPanel myButtons = new radioButtonPanel();
//layout = new BorderLayout(3, 2);
layout = new FlowLayout();
JPanel txtGroup = new JPanel();
txtGroup.setLayout(new GridLayout(2, 2));
txtGroup.add(myWidth);
txtGroup.add(myLength);
txtGroup.add(myRadius);
txtGroup.add(myHeight);
setLayout(layout);
add(lblTitle);
add(myButtons);
add(txtGroup);
add(btnProc);
if(myButtons.btnRectangle.isSelected())
{
myHeight.setVisible(false);
myRadius.setVisible(false);
}
}
private class RadioButtonHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent event)
{
}
}
}
I can get this working using if statements, but I'm supposed to be using event handlers and I'm lost on how to code that to get it to work properly.
if it helps, here's the code for the button panel:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import java.awt.GridLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class radioButtonPanel extends JPanel
{
private final JRadioButton btnRectangle;
private final JRadioButton btnBox;
private final JRadioButton btnCircle;
private final JRadioButton btnCylinder;
private final ButtonGroup radioButtonGroup;
private final JLabel label;
private final JPanel radioPanel;
public radioButtonPanel()
{
radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(5,1));
btnRectangle = new JRadioButton("Rectangle", true);
btnBox = new JRadioButton("Box", false);
btnCircle = new JRadioButton("Circle", false);
btnCylinder = new JRadioButton("Cylinder", false);
label = new JLabel("Select A Figure:");
radioPanel.add(label);
radioPanel.add(btnRectangle);
radioPanel.add(btnBox);
radioPanel.add(btnCircle);
radioPanel.add(btnCylinder);
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(btnRectangle);
radioButtonGroup.add(btnBox);
radioButtonGroup.add(btnCircle);
radioButtonGroup.add(btnCylinder);
add(radioPanel);
}
}
And a sample of one of the panels. They all follow the same setup, just different variable names.
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.GridLayout;
public class heightPanel extends JPanel
{
private final JLabel lblHeight;
private final JTextField txtHeight;
private final JPanel myHeight;
public heightPanel()
{
myHeight = new JPanel();
myHeight.setLayout(new GridLayout(2,1));
lblHeight = new JLabel("Enter Height:");
txtHeight = new JTextField(10);
myHeight.add(lblHeight);
myHeight.add(txtHeight);
add(myHeight);
}
}
The below code should give you a quick introduction of how to use event listener/handler for your button group (JRadioButtons).
but I'm supposed to be using event handlers and I'm lost on how to
code that to get it to work properly.
//add listener to the rectangle button and should be the same for the other `JRadioButtons` but with different `identifiers`.
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRectangle){
//TODO
}
}
});
Depending on the radio button that is selected, certain boxes that
aren't needed should be hidden. For example, if Rectangle is selected,
only the boxes for length and width should be visible.
//To hide JTextFields use
void setVisible(boolean visible) method. You should pass false as the argument to the method if you want to hide the JTextField.
Example:
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRectangle){
TextFieldName.setVisible(false); // set the textfields that you want to be hidden once the Rectangle button is chosen.
}
}
});

How to hide a Text Field when a radio button is selected/not selected?

I'm writting a program to encript data. It has a JTextArea to edit text, but I want to choose if I save it encripted or in plain text. For this I created a JDialog that appears when the save button is clicked. It contains two radio buttons: one to save the data encripted and the other to save in plain text. In the middle of them there is a JPasswordField requesting the key of the encription.
My question is if there is a simple way of making the TextField not useable and half transparent, when the option to save encripted is not selected. Or, if there isn't a simple way of doing it, a way to hide the TextArea. I tryed using a ChangeListener on the radio button but it isn't working. Here is my code:
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class StackOverflowVersion extends JFrame {
public static JFrame frame;
public StackOverflowVersion() {
dialogoCriptografar();
System.exit(EXIT_ON_CLOSE);
}
public void dialogoCriptografar(){
final ButtonGroup bGroup = new ButtonGroup();
JRadioButton[] buttons = new JRadioButton[2];
final JPasswordField passwordField = new JPasswordField(20);
// create the raio bunttons
buttons[0] = new JRadioButton("Encript document before saving");
buttons[1] = new JRadioButton("Just save it");
//ad them to the ButtonGroup
bGroup.add(buttons[0]);
bGroup.add(buttons[1]);
// select the option to encript
buttons[0].setSelected(true);
//creates a panel with the radio buttons and a JPasswordField
final JPanel box = new JPanel();
JLabel descricao = new JLabel("Choose an option to save:");
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
box.add(descricao);
box.add(buttons[0]);
box.add(passwordField);
box.add(buttons[1]);
// creates the dialog
final JDialog dialogo = new JDialog(frame, "Storage options", true);
dialogo.setSize(275,125);
dialogo.setLocationRelativeTo(frame);
dialogo.setResizable(false);
dialogo.add(box);
dialogo.setVisible(true);
/* Doesn't work:
buttons[0].addChangeListener(new ChangeListener(){
boolean visivel = true;//ele começa visivel
public void stateChanged(ChangeEvent event){
if(visivel){
box.remove(password);
SwingUtilities.updateComponentTreeUI(dialogo);
dialogo.revalidate();
dialogo.repaint();
visivel = false;
}
else{
box.add(password);
SwingUtilities.updateComponentTreeUI(dialogo);
dialogo.revalidate();
dialogo.repaint();
SwingUtilities.updateComponentTreeUI(dialogo);
visivel = true;
}
}
});
*/
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new StackOverflowVersion();
frame.setVisible(true);
}
});
}
}
My question is if there is a simple way of making the TextField not useable and half transparent,
Have you tried a simple
textField.setEditable(false);
Or
textField.setEnabled(false);
Observation in your code.
1) Add setVisible at the end after all the UI components' properties, events etc are set.
2) In your case you need a listener for each of the RadioButton.
3) Also I prefer using an ItemListener to a ChangeListener(fires even when mouse is moved over it).
Please check the code below.
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main extends JFrame {
public static JFrame frame;
public Main() {
dialogoCriptografar();
System.exit(EXIT_ON_CLOSE);
}
public void dialogoCriptografar(){
final ButtonGroup bGroup = new ButtonGroup();
final JRadioButton[] buttons = new JRadioButton[2];
final JPasswordField passwordField = new JPasswordField(20);
// create the raio bunttons
buttons[0] = new JRadioButton("Encript document before saving");
buttons[1] = new JRadioButton("Just save it");
//ad them to the ButtonGroup
bGroup.add(buttons[0]);
bGroup.add(buttons[1]);
// select the option to encript
buttons[0].setSelected(true);
//creates a panel with the radio buttons and a JPasswordField
final JPanel box = new JPanel();
JLabel descricao = new JLabel("Choose an option to save:");
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
box.add(descricao);
box.add(buttons[0]);
box.add(passwordField);
box.add(buttons[1]);
// creates the dialog
final JDialog dialogo = new JDialog(frame, "Storage options", true);
dialogo.setSize(275,125);
dialogo.setLocationRelativeTo(frame);
dialogo.setResizable(false);
dialogo.add(box);
// Doesn't work:
buttons[0].addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
if(buttons[0].isSelected()) {
passwordField.setVisible(true);;
//SwingUtilities.updateComponentTreeUI(dialogo);
// System.out.println("asdasd");
box.revalidate();
box.repaint();
}
}
});
buttons[1].addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("a");
if(buttons[1].isSelected()) {
passwordField.setVisible(false);;
//System.out.println("asdasd");
//SwingUtilities.updateComponentTreeUI(dialogo);
box.revalidate();
box.repaint();
}
}
}); //
dialogo.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new Main();
frame.setVisible(true);
}
});
}

MVC View Error Java

I'm trying to create an Onscreen telepad where people can press the keypad buttons and itll come up in the text box I haven't made the ActionListner for the keypad yet but I want it to show up in the view... Here's the code for the Keypad Panel and the View there is also a duration timer which I've managed to get working but can't put them into one view
Here's the Keypad Panel
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class KeypadPanel extends JPanel {
private JButton noStar;
private JButton noHash;
private JButton[] buttons;
private JButton C;
private JButton add;
private JPanel keypadPanel;
public KeypadPanel(TelepadController controller) {
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("" + i);
// buttons[i].addActionListener(controller.new NumberButtonListener());
}
//noStar.addActionListener(controller.new noStarActionListener);
//noHash.addActionListener(controller.new noHashActionListener);
//C.addActionListener(controller.new CActionListener);
//add.addActionListener(controller.new addActionListener);
noStar = new JButton("*");
noHash = new JButton("#");
C = new JButton("C");
add = new JButton("+");
JPanel keypadPanel = new JPanel();
keypadPanel.setLayout(new GridLayout(4, 3));
for (int i = 1; i <= 9; i++) {
keypadPanel.add(buttons[i]);
add(noStar);
add(noHash);
add(C);
add(add);
}
}
}
And here's the code for the main View
package londontelepad2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import org.apache.commons.beanutils.BeanUtils;
public class TelepadView implements Observer {
private StopwatchPanel stopwatchPanel;
private KeypadPanel keypadPanel;
private JFrame frame;
/**
*
* #param controller
*/
public TelepadView(TelepadController controller) {
super();
this.setResources();
frame = new JFrame("London Telepad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stopwatchPanel = new StopwatchPanel(controller);
//stopwatchPanel = new StopwatchPanel2(controller);
keypadPanel = new KeypadPanel(controller);
frame.getContentPane().add(stopwatchPanel);
frame.getContentPane().add(keypadPanel);
frame.pack();
}
public void show() {
frame.setVisible(true);
}
#Override
public void update(Observable observable, Object arg) {
if (arg.equals(Properties.TIME)) {
try {
stopwatchPanel.setTime(BeanUtils.getProperty(observable,
Properties.TIME));
} catch (Exception e) {
System.out.println(e);
}
}
}
public void setResetState() {
stopwatchPanel.setButtons(true, false, false);
}
public void setStoppedState() {
stopwatchPanel.setButtons(false, false, true);
}
public void setRunningState() {
stopwatchPanel.setButtons(false, true, false);
}
private void setResources() {
ColorUIResource defaultBackground = new ColorUIResource(Color.white);
ColorUIResource defaultForeground = new ColorUIResource(Color.black);
ColorUIResource disabledColor = new ColorUIResource(Color.lightGray);
FontUIResource smallFont = new FontUIResource(
new Font("Dialog", Font.BOLD, 12));
FontUIResource bigFont = new FontUIResource(
new Font("Dialog", Font.BOLD, 14));
UIManager.put("Button.background",
defaultBackground);
UIManager.put("Button.foreground",
defaultForeground);
UIManager.put("Button.disabledText",
disabledColor);
UIManager.put("Button.font", smallFont);
UIManager.put("Label.background",
defaultBackground);
UIManager.put("Label.foreground",
defaultForeground);
UIManager.put("Label.font", bigFont);
UIManager.put("Panel.background",
defaultBackground);
UIManager.put("Panel.foreground",
defaultForeground);
}
}
If I do the .add seperately I get an error to do with (actual and formal argument lists differ in length)
and if i do it together I get java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null)
And I can't find what it is im doing wrong!!
All the help in the world would be very appreciated seeing as I'm an Uber noob at java!
Thank you
Bilal
UPDATE
Here's a log of the error I reciveve when I put them in the same .add field
Exception in thread "main" java.lang.NullPointerException
at londontelepad2.KeypadPanel.<init>(KeypadPanel.java:48)
at londontelepad2.TelepadView.<init>(TelepadView.java:46)
at londontelepad2.TelepadController.<init>(TelepadController.java:33)
at londontelepad2.LondonTelepad2.main(LondonTelepad2.java:19)
Java Result: 1
Wait, KeypadPanel is just a plain object. Why doesn't it extend JPanel?
you are calling the add()-method of a JFrame to add your components to the frame? You need to call
frame.getContentPane().add(comp);

Categories

Resources