So if a user do not press any button,the action listener is not triggered and i end up with an exception. So i thought to put a default String in my FrameClass and change that String whenever a button is clicked,than in my main class i do a loop that keeps on looping until the default String is changed,so i think it is an infinite loop. Is it okay to do that ?
package gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
/**
*
* #author E-TECH
*/
public class ButtonsFrame extends JFrame {
private JButton ScPerF, weekSc, both,cancel;
private SchedulePerWeek week;
private CoursesPerWeek course;
private JPanel panel;
private String choice;
private File file;
public ButtonsFrame() {
ScPerF = new JButton("Generate schedule/faculty");
weekSc = new JButton("Generate weekly class schedule");
both = new JButton("Generate Both");
cancel = new JButton("Cancel");
choice="nothing";
ScPerF.addActionListener(new ButtonListener());
weekSc.addActionListener(new ButtonListener());
both.addActionListener(new ButtonListener());
cancel.addActionListener(new ButtonListener());
setResizable(false);
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
panel = new JPanel();
panel.add(ScPerF);
panel.add(weekSc);
panel.add(both);
panel.add(cancel);
getContentPane().add(panel);
setVisible(true);
pack();
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == ScPerF) {
dispose();
choice = "faculty";
}
if (event.getSource() == weekSc) {
dispose();
choice = "course";
}
if (event.getSource() == both) {
dispose();
choice = "both";
}
if (event.getSource()==cancel){
dispose();
choice="cancel";
}
}
}
public boolean Activated() {
return ScPerF.isSelected() || weekSc.isSelected();
}
public String getChoice() {
return choice;
}
public File getFile() {
return file;
}
}
public class SchedulePerWeek {
HSSFSheet weekSh,courseSh;
int instructor_count;
HSSFWorkbook wb;
public SchedulePerWeek() {
ExcelReader reader = new ExcelReader();
HSSFSheet sh = reader.getSortedSheet();
String choice=reader.getChoice();
if(choice.equals("cancel")||choice.equals("nothing")){///i fixed the exception with this condition by closing the program instead of continuing,but i want to wait for the user instead of just exiting the program
System.exit(1);
}
wb = new HSSFWorkbook();
/////
///more code
I ran your code from a couple of edits ago, and it works fine on my Windows 8 workstation, Java 7.
Before you go much further in your GUI design, read this answer to The Use of Multiple JFrames, Good/Bad Practice?
I modified your code to use a JFrame, rather than extend one. You should only extend a Swing component when you override one of the component methods.
You only need to define your Button listener once. You set the listener on your buttons.
I changed the JFrame default close operation to exit on close.
I added a main method so I could run your code.
Here's the code with the changes.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;
/**
*
* #author E-TECH
*/
public class ButtonsFrame{
private JButton scPerf, weekSc, both, cancel;
// private SchedulePerWeek week;
// private CoursesPerWeek course;
private JFrame frame;
private JPanel panel;
private String choice;
private File file;
public ButtonsFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scPerf = new JButton("Generate schedule/faculty");
weekSc = new JButton("Generate weekly class schedule");
both = new JButton("Generate Both");
cancel = new JButton("Cancel");
choice = "nothing";
ButtonListener listener = new ButtonListener();
scPerf.addActionListener(listener);
weekSc.addActionListener(listener);
both.addActionListener(listener);
cancel.addActionListener(listener);
frame.setResizable(false);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
panel = new JPanel();
panel.add(scPerf);
panel.add(weekSc);
panel.add(both);
panel.add(cancel);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == scPerf) {
frame.dispose();
choice = "faculty";
}
if (event.getSource() == weekSc) {
frame.dispose();
choice = "course";
}
if (event.getSource() == both) {
frame.dispose();
choice = "both";
}
if (event.getSource() == cancel) {
frame.dispose();
choice = "cancel";
}
}
}
public boolean Activated() {
return scPerf.isSelected() || weekSc.isSelected();
}
public String getChoice() {
return choice;
}
public File getFile() {
return file;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonsFrame();
}
});
}
}
Related
In my ActionListener class I have my if statements prompting the user to enter a string. When I try to execute the program, nothing happens. Before I added the JButton, the spelling game would appear in a small window and text could be entered, and a message displayed whether the correct spelling was given.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class spelling extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frame = new JFrame();
JButton button1;
public spelling() {
super("Question 1");
setLayout(new FlowLayout());
button1 = new JButton("Spelling game");
add(button1);
HandlerClass handler = new HandlerClass();
button1.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
JFrame frame2 = new JFrame();
String answer1 = JOptionPane.showInputDialog("recipracate, reciprocate, reciprokate");
if (answer1.equals("reciprocate")) {
JOptionPane.showMessageDialog(frame2, "recriprocate is the correct answer");
}
else {
JOptionPane.showMessageDialog(frame2, "is the wrong answer");
}
String answer2 = JOptionPane.showInputDialog("quintessence, quintessance, qwintessence");
if (answer2.equals("quintessence")) {
JOptionPane.showMessageDialog(frame2, "quintessence is the correct answer");
}
else {
JOptionPane.showMessageDialog(frame2, "That is the wrong answer");
}
}
}
}
import javax.swing.JFrame;
public class spellingmain {
public static void main(String[] args) {
spelling test = new spelling();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(300, 150);
test.setVisible(true);
}
}
Your complete example raises several issues that merit consideration going forward:
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
To avoid a NullPointerException, a common practice is to invoke the equals() method on the constant, which is known to be non-null.
"reciprocate".equals(answer1)
Make your error dialog easier to read by including relevant text.
answer1 + " is the wrong answer"
Don't extend JFrame unless you are adding new functionality.
Don't open a new frame needlessly; you can use the existing frame; a message dialog may have a parentComponent, but one is not required.
Test your program by clicking Cancel on a question to see the result. Consider how you intend to handle this.
Code as tested:
import java.awt.FlowLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class Spelling extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frame = new JFrame();
JButton button1;
public Spelling() {
super("Questionss");
setLayout(new FlowLayout());
button1 = new JButton("Spelling game");
add(button1);
HandlerClass handler = new HandlerClass();
button1.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
String answer1 = JOptionPane.showInputDialog("recipracate, reciprocate, reciprokate");
if ("reciprocate".equals(answer1)) {
JOptionPane.showMessageDialog(null, "recriprocate is the correct answer");
}
else {
JOptionPane.showMessageDialog(null, answer1 + " is the wrong answer");
}
String answer2 = JOptionPane.showInputDialog("quintessence, quintessance, qwintessence");
if ("quintessence".equals(answer2)) {
JOptionPane.showMessageDialog(null, "quintessence is the correct answer");
}
else {
JOptionPane.showMessageDialog(null, answer2 + " is the wrong answer");
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Spelling test = new Spelling();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
});
}
}
a basic problem that i can't figure out, tried a lot of things and can't get it to work, i need to be able to get the value/text of the variable
String input;
so that i can use it again in a different class in order to do an if statement based upon the result
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class pInterface extends JFrame {
String input;
private JTextField item1;
public pInterface() {
super("PAnnalyser");
setLayout(new FlowLayout());
item1 = new JTextField("enter text here", 10);
add(item1);
myhandler handler = new myhandler();
item1.addActionListener(handler);
System.out.println();
}
public class myhandler implements ActionListener {
// class that is going to handle the events
public void actionPerformed(ActionEvent event) {
// set the variable equal to empty
if (event.getSource() == item1)// find value in box number 1
input = String.format("%s", event.getActionCommand());
}
public String userValue(String input) {
return input;
}
}
}
You could display the window as a modal JDialog, not a JFrame and place the obtained String into a private field that can be accessed via a getter method. Then the calling code can easily obtain the String and use it. Note that there's no need for a separate String field, which you've called "input", since we can easily and simply extract a String directly from the JTextField (in our "getter" method).
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TestPInterface {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JFrame frame = new JFrame("TestPInterface");
// JDialog to hold our JPanel
final JDialog pInterestDialog = new JDialog(frame, "PInterest",
ModalityType.APPLICATION_MODAL);
final MyPInterface myPInterface = new MyPInterface();
// add JPanel to dialog
pInterestDialog.add(myPInterface);
pInterestDialog.pack();
pInterestDialog.setLocationByPlatform(true);
final JTextField textField = new JTextField(10);
textField.setEditable(false);
textField.setFocusable(false);
JPanel mainPanel = new JPanel();
mainPanel.add(textField);
mainPanel.add(new JButton(new AbstractAction("Get Input") {
#Override
public void actionPerformed(ActionEvent e) {
// show dialog
pInterestDialog.setVisible(true);
// dialog has returned, and so now extract Text
textField.setText(myPInterface.getText());
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// by making the class a JPanel, you can put it anywhere you want
// in a JFrame, a JDialog, a JOptionPane, another JPanel
#SuppressWarnings("serial")
class MyPInterface extends JPanel {
// no need for a String field since we can
// get our Strings directly from the JTextField
private JTextField textField = new JTextField(10);
public MyPInterface() {
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
add(new JLabel("Enter Text Here:"));
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = (Window) SwingUtilities.getWindowAncestor(MyPInterface.this);
win.dispose();
}
});
}
public String getText() {
return textField.getText();
}
}
A Good way of doing this is use Callback mechanism.
I have already posted an answer in the same context.
Please find it here JFrame in separate class, what about the ActionListener?.
Your method is a bit confusing:
public String userValue(String input) {
return input;
}
I guess you want to do something like this:
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
Also your JFrame is not visible yet. Set the visibility like this setVisible(true)
So I've built a very basic Web browser - I'm trying desperately to remove the contents of the address bar when a user clicks on it (JTextField) this appears with some text in as default. Any advice is appreciated.
Have a great day!
MY CODE
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Web_Browser extends JFrame {
private final JTextField addressBar;
private final JEditorPane display;
// Constructor
public Web_Browser() {
super("Web Browser");
addressBar = new JTextField("Click & Type Web Address e.g. http://www.google.com");
addressBar.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
loadGo(event.getActionCommand());
}
}
);
add(addressBar, BorderLayout.NORTH);
display = new JEditorPane();
display.setEditable(false);
display.addHyperlinkListener(
new HyperlinkListener(){
#Override
public void hyperlinkUpdate(HyperlinkEvent event){
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED){
loadGo(event.getURL().toString());
}
}
}
);
add(new JScrollPane(display), BorderLayout.CENTER);
setSize(500,300);
setVisible(true);
}
// loadGo to sisplay on the screen
private void loadGo(String userText) {
try{
display.setPage(userText);
addressBar.setText(userText);
}catch(IOException e){
System.out.println("Invalid URL, try again");
}
}
}
Use a FocusListener. On focusGained, select all.
addressBar.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComponent = (JTextComponent) e.getSource();
textComponent.selectAll();
}
});
For example:
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
#SuppressWarnings("serial")
public class FocusExample extends JPanel {
private static final int TF_COUNT = 5;
private JTextField[] textFields = new JTextField[TF_COUNT];
public FocusExample() {
for (int i = 0; i < textFields.length; i++) {
textFields[i] = new JTextField("Foo " + (i + 1), 10);
textFields[i].addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComponent = (JTextComponent) e.getSource();
textComponent.selectAll();
}
});
add(textFields[i]);
}
}
private static void createAndShowGui() {
FocusExample mainPanel = new FocusExample();
JFrame frame = new JFrame("FocusExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This gives the user the option of leaving the previous text in place, of adding to the previous text, or of simply over-writing it by typing.
new JTextField("Click & Type Web Address e.g. http://www.google.com");
Maybe you want the Text Prompt, which doesn't actually store any text in the text field. It just gives the user a hint what the text field is for.
This is beneficial so that you don't generate DocumentEvents etc., since you are not actually changing the Document.
Add a mouseListener instead of your actionListener method.
addressBar.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
addressBar.setText("");
}
I have a Java program which until now used to get the input from command line and then proceed accordingly.
Now, I want to have a basic GUI for this. It will need a few buttons which will trigger the events. I am experienced in HTML and JavaScript. Is it possible to write in HTML (or similar syntax) to generate the GUI?
I don't want to go in Swing and awt solution, because I would rather concentrate on the main program than on the GUI.
Here's another alternative. See also How to Use HTML in Swing Components.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* #see http://stackoverflow.com/a/10067256/230513
* #see http://stackoverflow.com/a/7454691/230513
*/
public class Pathfinder extends JPanel {
private static final int TEXT_SIZE = 32;
private JTextField srcField = new JTextField(TEXT_SIZE);
private JTextField dstField = new JTextField(TEXT_SIZE);
private JTextField valueField1 = new JTextField(TEXT_SIZE);
private JTextField valueField2 = new JTextField(TEXT_SIZE);
private String srcPath, dstPath, value1, value2;
public Pathfinder() {
super(new GridLayout(0, 1));
this.add(createPathPanel("Source Directory", srcField));
this.add(createPathPanel("Target Directory", dstField));
this.add(createFieldPanel("Some Value:", valueField1));
this.add(createFieldPanel("Another Value:", valueField2));
JPanel submitPanel = new JPanel();
submitPanel.add(new JButton(new AbstractAction("Submit") {
#Override
public void actionPerformed(ActionEvent e) {
srcPath = srcField.getText();
dstPath = dstField.getText();
value1 = valueField1.getText();
value2 = valueField2.getText();
process();
}
}));
this.add(submitPanel);
}
private void process() {
// see ProcessBuilder http://stackoverflow.com/questions/5740390
System.out.println(srcPath);
System.out.println(dstPath);
System.out.println(value1);
System.out.println(value2);
}
private JPanel createPathPanel(String name, final JTextField jtf) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
panel.add(new JButton(new AbstractAction(name) {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser(
new File(System.getProperty("user.dir")));
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = jfc.showOpenDialog(Pathfinder.this);
if (result == JFileChooser.APPROVE_OPTION) {
jtf.setText(jfc.getSelectedFile().getPath());
}
}
}));
panel.add(jtf);
return panel;
}
private JPanel createFieldPanel(String name, JTextField jtf) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
panel.add(new JLabel(name));
panel.add(jtf);
return panel;
}
private void display() {
JFrame f = new JFrame("Pathfinder");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Pathfinder pf = new Pathfinder();
if (args.length > 0) {
pf.srcPath = args[0];
pf.dstPath = args[1];
pf.process();
} else {
pf.display();
}
}
});
}
}
I want to have a basic GUI for this. It will need a few buttons which will trigger the events.
This 'basic GUI' goes slightly beyond the spec. to add an output area.
import java.awt.*;
import javax.swing.*;
class SimpleEventGUI {
SimpleEventGUI() {
JPanel gui = new JPanel(new BorderLayout());
JToolBar toolBar = new JToolBar();
for (int ii=1; ii<6; ii++) {
toolBar.add(new JButton("Event " + ii));
if (ii%2==0) {
toolBar.addSeparator();
}
}
gui.add(toolBar, BorderLayout.NORTH);
gui.add( new JScrollPane(new JTextArea(5,30)), BorderLayout.CENTER );
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new SimpleEventGUI();
}
});
}
}
You may consider Google Web Toolkit with Window Builder which allow you to build a rich internet interface using Java and interact with the existing logic.
If you want something quick, you can build a Swing GUI using Window Builder
I have made a program where the right and left arrows show the volume on the JSlider decreasing while the Up and Down arrow show the Channel being changed i.e different colours being shown on screen. I wanted that whenever the screen is stable for 10seconds or more, the "Volume is" and "Channel Is" text along with JSlider should disappear, as it happens in a Television Set. I am using Java Eclipse with VisualSwing as my GUI. My current code is:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
public class TVPanel extends JPanel {
private static JLabel vollab;
private int ChannelNo;
private static final long serialVersionUID = 1L;
private JLabel jLabel0;
private int VolumeMax=10;
private JButton jButton0;
private JSlider jSlider0;
private JMenuItem jMenuItem0;
private JPopupMenu jPopupMenu0;
private JLabel jLabel1;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public TVPanel() {
ChannelNo=0;
initComponents();
}
private void initComponents() {
setLayout(new GroupLayout());
add(getJButton0(), new Constraints(new Leading(100, 176, 10, 10), new Leading(39, 72, 10, 10)));
add(getJSlider0(), new Constraints(new Leading(46, 10, 10), new Leading(162, 10, 10)));
add(getJLabel1(), new Constraints(new Leading(111, 10, 10), new Leading(129, 12, 12)));
add(getJLabel0(), new Constraints(new Leading(37, 68, 12, 12), new Leading(129, 12, 12)));
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent event) {
keyKeyTyped(event);
}
public void keyPressed(KeyEvent event) {
keyKeyPressed(event);
}
});
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
mouseMouseClicked(event);
}
});
setSize(478, 240);
}
private JLabel getJLabel1() {
if (jLabel1 == null) {
jLabel1 = new JLabel();
jLabel1.setText("10");
}
return jLabel1;
}
private JSlider getJSlider0() {
if (jSlider0 == null) {
jSlider0 = new JSlider();
jSlider0.setMajorTickSpacing(1);
jSlider0.setMaximum(10);
jSlider0.setPaintLabels(true);
jSlider0.setPaintTicks(true);
jSlider0.setValue(10);
jSlider0.setAlignmentX(1.0f);
jSlider0.setInheritsPopupMenu(true);
jSlider0.setValueIsAdjusting(true);
}
return jSlider0;
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("");
jButton0.setSize(150, 150);
}
return jButton0;
}
private JLabel getJLabel0() {
if (jLabel0 == null) {
jLabel0 = new JLabel();
jLabel0.setText("Volume Is");
}
return jLabel0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class.
* Note: This class is only created so that you can easily preview the result at runtime.
* It is not expected to be managed by the designer.
* You can modify it as you like.
*/
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("TVPanel");
//JLabel volLab= new JLabel();
vollab= new JLabel("test");
frame.getContentPane().add(vollab);
frame.requestFocus();
frame.isFocusable();
vollab.isVisible();
TVPanel content = new TVPanel();
content.setPreferredSize(content.getSize());
frame.add(content, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
//Arrows
private void keyKeyPressed(KeyEvent event) {
jLabel0.setVisible(true);
jLabel1.setVisible(true);
Color colorarr[]= new Color[] {Color.BLACK,Color.WHITE,Color.BLUE,Color.CYAN,Color.RED,Color.GREEN,Color.GRAY,Color.MAGENTA,Color.ORANGE,Color.YELLOW};
//int Volume=10;
//int ChannelNo=10;
//jLabel0.setText(Integer.toString(event.getKeyCode()));
if(event.getKeyCode()== 37){
VolumeMax--;
jSlider0.setValue(VolumeMax);
jLabel0.setText("Volume Is");
jLabel1.setText(Integer.toString(jSlider0.getValue()));
}
else if(event.getKeyCode()==38)//UP{
{
ChannelNo++;
for(int i=0; i<ChannelNo;i++){
if(i<10){
jButton0.setBackground(colorarr[i]);
jLabel0.setText("Channel Is");
jLabel1.setText(Integer.toString(i+1));
}
}
}
else if(event.getKeyCode()==39){
//RIGHT
VolumeMax++;
jSlider0.setValue(VolumeMax);
jLabel1.setText(Integer.toString(jSlider0.getValue()));
}
else if(event.getKeyCode()==40){
ChannelNo--;
if(ChannelNo>0){
jButton0.setBackground(colorarr[ChannelNo-1]);
jLabel0.setText("Channel Is");
jLabel1.setText(Integer.toString(ChannelNo-1));
}
}
this.requestFocus();
}
private void mouseMouseClicked(MouseEvent event) {
//jLabel0.setText("mouse");
this.requestFocus();
}
//Other keys
private void keyKeyTyped(KeyEvent event) {
if(event.getKeyCode()==37){
//jLabel0.setText("uparrow");
jSlider0.setValue(9);
}
jLabel0.setText("keyType");
this.requestFocus();
}
}
else if(event.getKeyCode()==39){
Never use code with magic numbers. Define static variables if you need to. However, in this case you don't need to since it has already been done for you:
KeyEvent.VK_RIGHT
To have the panel disappear you need to start a Swing Timer to fire in 20 seconds once the panel is displayed. Then whenever a key event or mouse events changes a value on the panel you can restart the Timer.
Read the section from the Swing tutorial on How to Use Timers for more information.
If this is a modal dialog that you are using than maybe you can even use the Application Inacdtivity to help yoo out.