How to display different components in a JFrame? - java

I am very new to Java AWT. My question header must seem ridiculous to you, sorry about that. In my application I have three buttons which display different threads when clicked on. Now I want to add maybe a button or checkboxes or choicelist, etc when clicked on a particular button. For eg, if I click on yes button, it should display a choice list, something like that. How do I achieve something like that? Here is my code so far:
import java.awt.Button;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class AppWindow extends Frame implements ActionListener{
String keymsg = "Test message";
String mousemsg = "Nothing";
int mouseX=30, mouseY=30;
String msg;
public AppWindow(){
//addKeyListener(new MyKeyAdapter(this));
//addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g){
g.drawString(msg, 150, 100);
}
//Here the window is created:
public static void main(String args[]){
AppWindow appwin = new AppWindow();
appwin.setSize(new Dimension(300,200));
appwin.setTitle("My first AWT Application");
appwin.setLayout(new FlowLayout(FlowLayout.LEFT));
appwin.setVisible(true);
Button yes,no,maybe;
yes = new Button("yes");
no = new Button("no");
maybe = new Button("maybe");
appwin.add(yes);
appwin.add(no);
appwin.add(maybe);
yes.addActionListener(appwin);
no.addActionListener(appwin);
maybe.addActionListener(appwin);
}
#Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
String str = ae.getActionCommand();
if(str.equals("yes")){
msg = "You pressed Yes";
}
if(str.equals("no")){
msg = "You pressed No";
}
if(str.equals("maybe")){
msg = "You pressed Maybe";
}
repaint();
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we){
System.exit(0);
}
}

Points describing what you should be doing :
As already mentioned by others, better to use Swing over AWT, since Swing is more advanced.
As much as possible, always try to Paint on top of a JPanel or a
JComponent, instead of Painting right on top of your JFrame, by
overriding the paintComponent(Graphics g) method of the said
JComponent/JPanel
Never call setVisible(true) on the JFrame until and unless it's
size has been established. So in general terms, this has to be the
last call, once you are done adding components to the JFrame and
the size of the JFrame has been realized by the LayoutManager.
Inside your actionPerformed(...), instead of writing all if
statement blocks, you should adhere to the if-else if statement
blocks. The benefit of this, over the former is that, at any given
time, only one event will be fired, hence once the said condition is
satisfied, you don't want your code to keep checking other
conditions, which in general is really not a good programming
practice, IMHO.
MOST IMPORTANT THING : Never make calls like pack()/setVisible(...) from within the main method, such calls belong
to the Event Dispatch Thread, and must be done on the same. Please
read Concurrency in Swing for more detail.
Have a look at the example program, for better understanding.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ComponentExample
{
private CustomPanel drawingBoard;
private JPanel contentPane;
private JButton yesButton;
private JButton noButton;
private JButton maybeButton;
private JComboBox cbox;
private ActionListener buttonAction = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (cbox.isShowing())
contentPane.remove(cbox);
if (button == yesButton)
{
drawingBoard.setText("You Pressed YES.");
contentPane.add(cbox, BorderLayout.PAGE_END);
}
else if (button == noButton)
drawingBoard.setText("You Pressed NO.");
else if (button == maybeButton)
drawingBoard.setText("You Pressed MAYBE.");
/*
* revalidate()/repaint() is needed
* when the JComponent is added or
* removed from the already
* visible Container.
*/
contentPane.revalidate();
contentPane.repaint();
}
};
public ComponentExample()
{
cbox = new JComboBox(
new String[]{"I GOT IT"
, "I STILL HAD DOUBT"});
}
private void displayGUI()
{
JFrame frame = new JFrame("Component Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(5, 5));
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.WHITE);
yesButton = new JButton("YES");
yesButton.addActionListener(buttonAction);
noButton = new JButton("NO");
noButton.addActionListener(buttonAction);
maybeButton = new JButton("MAY BE");
maybeButton.addActionListener(buttonAction);
buttonPanel.add(yesButton);
buttonPanel.add(noButton);
buttonPanel.add(maybeButton);
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
drawingBoard = new CustomPanel();
contentPane.add(drawingBoard, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ComponentExample().displayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
private String msg;
public CustomPanel()
{
msg = "";
setOpaque(true);
setBackground(Color.WHITE);
}
public void setText(String msg)
{
this.msg = msg;
repaint();
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(msg, getWidth() / 3, getHeight() / 3);
}
}

I don't know if I have understood the question well but... couldn't you create those elements and call their setVisible(boolean) methods to make them not visible at first, and them make them visible when user pushes buttons?

Related

Swing mouseEntered strange behavior

I have a jframe with some JComponents, with some mouseListener. My aim is to show a little jframe with a specified text, when the mouse enter on a jlabel, and to show off it when the mouse is exited.
Jframe is supposed to be shown near the mouse.
Anyway that does not happen, and the programm behaves in a very strange way.
Why?
the bug
That's my code
package finestrina;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class finestra implements MouseListener{
private JFrame finestra = new JFrame();
private JFrame pagina = new JFrame();
private JButton submit1 = new JButton("press");
private JTextField text = new JTextField();
finestra(){
pagina.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pagina.setSize(500, 500);
JPanel cont = new JPanel();
cont.setLayout(new GridLayout(3,4));
JLabel label = new JLabel();
label.setText("ON MOUSEROVER THIS");
cont.add(label);
label.addMouseListener(this);
submit1.addMouseListener(this);
text.addMouseListener(this);
cont.add(submit1);
cont.add(text);
pagina.add(cont);
pagina.setVisible(true);
finestra.setUndecorated(true);
}
#Override
public void mouseClicked(MouseEvent arg0) {}
#Override
public void mouseEntered(MouseEvent event) {
if(event.getSource() instanceof JLabel){
JLabel event_casted = (JLabel)event.getSource();
if(event_casted.getText().equals("ON MOUSEROVER THIS")){
Point punto = event.getLocationOnScreen();
punto.setLocation(punto.getX()+20, punto.getY()+20);
JLabel littlelabel = new JLabel();
littlelabel.setText("your mouse is on the jlabel");
finestra.add(littlelabel);
finestra.setLocation(punto);
finestra.setSize(100,100);
finestra.setVisible(true);
}
}
}
#Override
public void mouseExited(MouseEvent event) {
if(event.getSource() instanceof JLabel){
JLabel event_casted = (JLabel)event.getSource();
if(event_casted.getText().equals("ON MOUSEROVER THIS")){
finestra.setVisible(false);
}
}
}
#Override
public void mousePressed(MouseEvent event) {
}
#Override
public void mouseReleased(MouseEvent arg0) {}
public static void main(String[] args0){
new finestra();
};
}
There are a number of (possible) issues
The GridLayout will cause the component to occupy most of the space of the container, which might cause the window to "appear" to popup earlier then you expect
finestra.add(event_casted); is causing the label to be removed from it's current parent container (the main window), as a component can only belong to a single container
It would, generally be better to use the tooltip support provided by the API. Maybe have a look at How to Use Tool Tips, remember, they can also support HTML.
If that's not functionality what you want, then maybe a JPopupMenu might be better

Tanslucent Java Chat showing duplicate components?

Pretty much, once I make my JTextArea and my JTextField transparent, as I type it looks as if all of my components are being duplicated and added to the screen. Am I doing something wrong, or is this a NetBeans bug?
package game;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
*
* #author xDaegothx
*/
public class Game extends JFrame
{
JLayeredPane LP;
Game_Chat GC;
public Game()
{
LP = new JLayeredPane();
LP.setBackground(Color.black);
LP.setOpaque(true);
GC = new Game_Chat();
GC.setBounds(0,350,400,250);
LP.add(GC);
this.getContentPane().add(LP);
this.setBounds(0,0,1200,700);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args)
{
new Game();
}
public class Game_Chat extends JLabel
{
JTextArea TA;
JScrollPane JSP;
JTextField TF;
JButton Submit_btn;
public Game_Chat()
{
TA = new JTextArea();
TA.setForeground(new Color(255,255,255,0));
TA.setBackground(new Color(255,255,255,0));
TA.setOpaque(true);
TA.setText("Welcome to 'Game'!");
JSP = new JScrollPane(TA);
JSP.setOpaque(true);
JSP.setForeground(new Color(255,255,255,0));
JSP.setBackground(new Color(255,255,255,0));
JSP.setBounds(0,0,400,225);
TF = new JTextField();
TF.setOpaque(true);
//TF.setBackground(new Color(255,255,255,0));
TF.setBounds(0,225,350,25);
Submit_btn = new JButton("Send");
Submit_btn.setBorder(null);
Submit_btn.setBounds(350,225,50,25);
TF.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
Submit();
}
});
Submit_btn.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent me)
{
Submit();
}
});
add(JSP);
add(TF);
add(Submit_btn);
setBackground(Color.gray);
setOpaque(true);
}
public void Submit()
{
String charname = "MyName";
TA.append("\n"+charname+": "+TF.getText());
}
}
}
What is the point of setting both the foreground and background transparent? You will never see the text if it is transparent!
Anyway to make a component completely transparent you don't play with the background. Instead you just use:
textArea.setOpaque(false);
If you want partially transparent backgrounds then you do use the setBackground() method. But you will have painting problems. See Backgrounds With Transparency for an explanation of the problems and some potential solutions.
Also, you should NOT be using setBounds() to set the size/location of a component. Swing was designed to be used with layout managers. So take the time to learn how to use them for better functioning programs.

Java / Swing / WebcamCapture : When I disable a JLabel, an other image appears

I come to you because I have a strange issue, for which I don't find any solution...
I build an application using a webcam, in order to take some photographs.
I use WebcamCapture to do that, and I don't encounter any issues with it.
The only "weird" thing that happens is the following :
I use a JDialog in which I make photograph. In its JFrame parent, I display those photographs in JLabel.
Then, i need to disable those JLabel, and I do that by calling a method which disable all components. The weird thing is, when I disable JLabel, the JLabel display the last image capture by the webcam. Not the last photographs, but really the last captured image.
It's seems that BufferedImage (used by WebcamPanel) are linked to the issue.
Here is the SSCE :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
#SuppressWarnings("serial")
public class CameraFrame extends JFrame implements ActionListener{
public Webcam webcam;
Boolean enabled = true;
CameraFrame frame;
private JButton btnSaveVerso;
private JLabel lblVerso;
private JButton btnEnable;
private JButton btnQuit;
private JPanel mainPanel;
private WebcamPanel streamPanel;
public static void main(String[] args){
CameraFrame frame = new CameraFrame();
frame.setVisible(true);
}
public CameraFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setMinimumSize(new Dimension(800, 600));
setPreferredSize(new Dimension(800,600));
buildPanel();
setContentPane(mainPanel);
}
});
}
public void buildPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
Border blackline = BorderFactory.createLineBorder(Color.black, 1, true);
webcam = Webcam.getDefault();
webcam.open();
streamPanel = new WebcamPanel(webcam);
streamPanel.setPreferredSize(new Dimension(webcam.getViewSize()));
streamPanel.setMaximumSize(new Dimension(webcam.getViewSize()));
btnSaveVerso = new JButton("Take pic");
btnSaveVerso.setActionCommand("take");
btnSaveVerso.addActionListener(this);
lblVerso = new JLabel("Here will be the pic taken by the camera");
lblVerso.setBorder(blackline);
btnEnable = new JButton("Disable");
btnEnable.setActionCommand("disable");
btnEnable.addActionListener(this);
btnQuit = new JButton("Quit");
btnQuit.setActionCommand("quit");
btnQuit.addActionListener(this);
mainPanel.add(streamPanel);
mainPanel.add(btnSaveVerso);
mainPanel.add(lblVerso);
mainPanel.add(btnEnable);
mainPanel.add(btnQuit);
}
#Override
public void actionPerformed(final ActionEvent e) {
Thread newThread = new Thread(){
public void run(){
if(e.getActionCommand().equals("take")){
ImageIcon icon = new ImageIcon(webcam.getImage().getScaledInstance(100, 150, Image.SCALE_SMOOTH ));
lblVerso.setIcon(new ImageIcon(icon.getImage()));
lblVerso.revalidate();
lblVerso.repaint();
}
else if(e.getActionCommand().equals("disable")){
if(enabled){
lblVerso.setEnabled(false);
enabled = false;
btnEnable.setText("Enable");
}
else{
lblVerso.setEnabled(true);
enabled = true;
btnEnable.setText("Disable");
}
}
}
};
newThread.run();
if(e.getActionCommand().equals("quit")){
webcam.close();
this.setVisible(false);
}
}
}
I hope you will compile it without issues. Don't forget to link the librairies.
Thanks in advance
I finally resolved the problem : you simply need to close the webcam after each pictures, as follows :
BufferedImage picture = webcam.getImage();
webcam.close();
webcam.open();
... Do what you need with picture
(You don't even need to convert BufferedImage picture in an other type.)

accessing swing component of other class

I have two classes mainpanel.java and subpanel.java. The subpanel.class contains a checkbox and some labels. I want to change the setSelected() and setText() of these components when i click some buttons in the mainpanel.java .
I have created a method in subpanel.java which i call from mainpanel.java and pass the boolean values.
public void schedulerchange(boolean check){
System.out.println("checked"+check);
scheduleenabler.setEnabled(check);
scheduleenabler.setSelected(check);
scheduleinfo.setText("Scheduler in On");
//subpanel21.updateUI();
}
When i call this function from mainpanel.java the function is called but the values don't change unless i make jcheckbox and jlabel static. But from what i learned we should not use static components unless very necessary.
Is there some other way to change the components?
If I have understood your question then I think you want to write a separate ActionListener class and perform action there which will enable or disable the JCheckBox in the UI-class. The below code shows that. Pass your checkbox reference to that PerformAction class and make it enabled or disabled by clicking on the button.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainClass {
MainClass() {
JFrame jfrm = new JFrame("JTable Demo");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(460, 180);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox check = null;
// Get the Panel from the subclass;
JPanel panel = new CheckBox().getCheckBoxPanel();
// From the compoenents present in the panel get the CheckBox compoenent.
for(int i = 0; i < panel.getComponentCount(); i++) {
if(panel.getComponent(i) instanceof JCheckBox) {
check = (JCheckBox) panel.getComponent(i);
}
}
JButton button = new JButton("Click");
// Pass the CheckBox Compoenent to the ActionListener.
button.addActionListener(new PerformAction(check));
jfrm.add(button);
jfrm.add(panel);
jfrm.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MainClass();
}
});
}
}
class PerformAction implements ActionListener {
JCheckBox check = null;
public PerformAction(JCheckBox checkBox) {
check = checkBox;
}
#Override
public void actionPerformed(ActionEvent e) {
boolean checkStatus = check.isSelected();
if(checkStatus == true) {
check.setEnabled(false);
check.setSelected(false);
} else {
check.setEnabled(true);
check.setSelected(true);
}
}
}
class CheckBox {
public JPanel getCheckBoxPanel() {
JPanel checkPanel = new JPanel();
JCheckBox check = new JCheckBox();
checkPanel.add(new JLabel("CheckBox"));
checkPanel.add(check);
return checkPanel;
}
}
This is not an appropriate use of updateUI(), which "Resets the UI property to a value from the current look and feel." Using revalidate(), as suggested in a comment, would be helpful only if components are added to, or removed from, the enclosing Container. Instead, invoke repaint() directly on the sub-panel instance. For greater flexibility, use the observer pettern suggested here.
Addendum: This example use Action to encapsulate the button's behavior. Because the checkbox's selected state is a bound property, the component is repainted automatically, but you can invoke repaint() explicitly if needed.
Addendum: Update to pass a reference as a parameter.
Addendum: In this variation, the parameter is a reference to the exported Action.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/a/14412516/230513 */
public class Example {
private void display() {
JFrame f = new JFrame("Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 1));
JPanel panel = new JPanel();
final JCheckBox check = new JCheckBox("Check");
Action checkAction = new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
check.setSelected(!check.isSelected());
}
};
panel.add(check);
f.add(panel);
f.add(new SubPanel(checkAction));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class SubPanel extends JPanel {
public SubPanel(final Action action) {
this.add(new JButton(action));
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example().display();
}
});
}
}

java, apple default look and feel: How to set color of a button

i want to know how to set the color of a button (in example, but i will need to set every component color) with the apple look and feel.
I found an answer in stackoverflow that suggest to change to the standard look and feel, that works for me, but i prefer not to change because I like apple's one.
Is there any solution?
I know there is because I saw many apps written in java that have colored buttons and also that use particular styles or images as background.
Can you tell me a solution?
Extend the Jbutton class and in that override the repaint() method and call setBackground(COLOR.ORANGE), to change the button color.
Now use this class to create all your buttons. If you wish to change color of a specific button, call the setBackground(COLOR.ORANGE) method on that specific button. Hope this helps. Have a look at the code below
package solutions;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class VerifierTest extends JFrame {
private static final long serialVersionUID = 1L;
public VerifierTest() {
final JTextField tf = new JTextField("TextField1");
getContentPane().add(tf, BorderLayout.NORTH);
tf.setInputVerifier(new PassVerifier());
final JTextField tf2 = new JTextField("TextField2");
getContentPane().add(tf2, BorderLayout.SOUTH);
tf2.setInputVerifier(new PassVerifier());
final JButton b = new JButton("Button");
b.setBackground(Color.ORANGE);
b.setVerifyInputWhenFocusTarget(true);
getContentPane().add(b, BorderLayout.EAST);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!tf.getInputVerifier().verify(tf)) {
JOptionPane.showMessageDialog(tf.getParent(), "illegal value: " + tf.getText(), "Illegal Value",
JOptionPane.ERROR_MESSAGE);
}
if (b.isFocusOwner()) {
System.out.println("Button clicked");
}
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Frame frame = new VerifierTest();
frame.setSize(400, 200);
frame.setVisible(true);
}
class PassVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
final JTextField tf = (JTextField) input;
String pass = tf.getText();
if (pass.equals("Manish")) {
return true;
} else {
return false;
}
}
}
}
Comment the line "b.setBackground(Color.ORANGE);" and see the difference.

Categories