Extending Swing Components
I would like to create my own Swing components that I wish to use in my Java GUI programs. I would like to create my own lightweight components and also to create things such as:
Round buttons
Sliders
etc
I also need to know how to create metallic skins for my Swing application.
Please can someone give me any simple examples of how to create custom components and also how to create skins of interfaces or give me some URLs that teach you.
Thanks in advance
Riz
I think your best bet is to look at the source of the LookAndFeel's provided with the swing download, mac/windows/motif/metal/basic and figure it all out. I don't know of any detailed sites to help make look and feels.
Similar Messages
-
Extended Swing Components into Custom Component Palette
Hi
As part of my swing application I have a number of GUI components created as an extension of a normal swing component.
As example is below.
package com.myapp
import java.awt.Font;
import javax.swing.JLabel;
public class MLabel extends JLabel
public MLabel()
this.setFont(new Font("Tohoma",0,10));
this.setFocusable(false);
As you can see this simple sets some default attributes. How can I add this custom component into a palette for each access when using the GUI builder.
I've created a new page in the palette, but am unable to add my components.
Thanks for your help.
Nick.Hi,
- create a JAR file with your component(s) in it
- Create a custom Library in JDeveloper (Tools--> Managed Libraries)
- Select the JAR file
- On the component palette (the page you created), select the properties option of the context menu
- Your library now shows up in the drop down list to choose the component to add
Frank -
Swing components in applet not working in web browser
Hi Guys,
I've created an applet which makes use of some swing components, but unfortunately, not all of them function properly in my web browser (internet explorer or Mozilla Firefox). Its mainly the buttons; the last buttons works and displays the correct file within the broswer, but the first 5 buttons do not work...
any help please on how I can sort this problem out?
Heres the code for my applet:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class MainAppWindow extends JApplet
int gapBetweenButtons = 5;
final JPanel displayPanel = new JPanel(new BorderLayout());
public void init()
//Panel for overall display in applet window.
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/smalllogo2.gif"))),BorderLayout.NORTH);
//sub mainPanel which holds all mainPanels together.
JPanel holdingPanel = new JPanel(new BorderLayout());
//Panel for displaying all slide show and applications in.
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/IntroPage.jpg"))),BorderLayout.CENTER);
displayPanel.setPreferredSize(new Dimension(590,400));
JPanel buttonPanel = new JPanel(new GridLayout(6,1,0,gapBetweenButtons));
buttonPanel.setBackground(Color.white);
JButton button1 = new JButton("User guide");
button1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll(); // If there are any components in the mainPanel, remove them and then add label
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon("images/UserGuide.jpg")));
displayPanel.revalidate(); // Validates displayPanel to allow changes to occur onto it, allowing to add different number images/applicaions to it.
JButton button2 = new JButton("What is a Stack?");
button2.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon("images/WhatIsAStack.jpg")));
displayPanel.revalidate();
JButton button3 = new JButton("STACK(ADT)");
button3.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon("images/StackADT.jpg")));
displayPanel.revalidate();
JButton button4 = new JButton("Stacks in the Real World");
button4.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon("images/StacksInTheRealWorld.jpg")));
displayPanel.revalidate();
JButton button5 = new JButton("DEMONSTRATION");
button5.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
Demonstration app = new Demonstration();
JPanel appPanel = app.createComponents();//gets the created components from Demonstration application.
appPanel.setBackground(Color.pink);
displayPanel.add(appPanel);
displayPanel.revalidate();
JButton button6 = new JButton("Towers Of Hanoi");
button6.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
TowerOfHanoi app = new TowerOfHanoi();
JPanel appPanel = app.createComponents();//gets the created components from Towers of Hanoi
JPanel mainPanel = new JPanel();//panel used to centralise the application in center
mainPanel.add(appPanel);
mainPanel.setBackground(Color.pink); //sets mainPanel's background color for 'Towers Of Hanoi'
displayPanel.add(mainPanel);
displayPanel.revalidate();
//adding buttons to the buttonPanel.
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonPanel.add(button4);
buttonPanel.add(button5);
buttonPanel.add(button6);
JPanel p = new JPanel(); // Used so that the buttons maintain their default shape
p.setBackground(Color.white);
p.add(buttonPanel);
holdingPanel.add(p,BorderLayout.WEST);
holdingPanel.add(displayPanel,BorderLayout.CENTER);
//Positioning of holdingPanel in mainPanel.
mainPanel.add(holdingPanel,BorderLayout.CENTER);
//indent mainPanel so that its not touching the applet window frame.
mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
mainPanel.setBackground(Color.white);
mainPanel.setPreferredSize(new Dimension(850,600)); //size of applet window
mainPanel.setOpaque(false); // Needed for Applet
this.setContentPane(mainPanel);
}Thanks for the response. I don't quite understand what you're talking about though. I have, in my humble knowledge, done nothing with packages. I have put the applet class (WiaRekenToolActiz.class is the applet class) in the jar file wia_actiz_archive.jar. From what I read on the tutorial, java looks for the applet class in all the jar files specified. Since I put my CODEBASE as the main url, I thought it baiscally didn't matter where you out the html file.
I shall include the complete html page complete with applet tag to perhaps illuminate a bit more what I mean...
<html>
<head>
<title>Wia Rekenmodule hello!</title>
</head>
<body bgcolor="#C0C0C0">
<applet
CODEBASE= "http://www.creativemathsolutions.nl/test"
ARCHIVE= "Actiz/wia_actiz_archive.jar, Generic/wia_archive.jar"
CODE="WiaRekenToolActiz.class"
WIDTH=915 HEIGHT=555
>
<PARAM NAME = naam VALUE = "Piet Janssen">
<PARAM NAME = gebdag VALUE = "01">
<PARAM NAME = gebmaand VALUE = "06">
<PARAM NAME = gebjaar VALUE = "1970">
<PARAM NAME = geslacht VALUE = "man">
<PARAM NAME = dienstjaren VALUE = "10">
<PARAM NAME = salaris VALUE = "56500">
<PARAM NAME = deeltijdpercentage VALUE = "100">
<PARAM NAME = accountnaam VALUE = "Zorginstelling 'De Zonnebloem'">
</applet>
</body>
</html> -
Need help with using graphics in swing components
Hi. I'm new to Java and trying to learn it while also developing an application for class this semester. I've been following online tutorials for about 2 months now, though, and so I'm not sure my question counts as a "new to Java" question any more as the code is quite long.
Here is the basic problem. I started coding the application as a basic awt Applet (starting at "Hello World") and about a month in realized that Swing components offer better buttons, panels, layouts, etc. So I converted the application, called BsfAp, to a new JApplet and started adding JPanels and JComponents with layout managers. My problem is, none of the buffered graphics run in any kind of JPanel, only the buttons do. I assume the buffered graphics are written straight to the JApplet top level container instead but I'm not entirely sure.
So as to not inundate the forum with code, the JApplet runs online at:
http://mason.gmu.edu/~dho2/files/sensor.html
The source code is also online at:
http://mason.gmu.edu/~dho2/files/BsfAp.java
What I would like to do is this - take everything in the GUI left of the tabbed button pane and put it into a JScrollPane so that I can use a larger grid size with map display I can scroll around. The grid size I would like to use is more like 700x1000 pixels, but I only want to display about 400x400 pixels of it at a time in the JScrollPane. Then I could also move this JScrollPane around with layout manager. I think this is possible, but I don't know how to do it.
I'm sure the code is not organized or optimized appropriately to those of you who use Java every day, but again I'm trying to learn it. ;-)
Thanks for any help or insight you could provide in this.
MattCouple of recs:
* Don't override paint and paint directly on the JApplet. Paint on a JPanel and override paintComponent.
* The simplest way to display a graphic is to put an image into an ImageIcon and show this in a JLabel. This can then easily go inside of the JScrollPane.
* You can also create a graphics JPanel that overrides the paintComponent, draw the image in that and show that inside of the JScrollPane.
* don't call paint() directly. Call repaint if you want the graphic to repaint.
Here's a trivial example quickly put together:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class BsfCrap extends JApplet
private JPanel mainPanel = new JPanel();
private JScrollPane scrollPane;
private JPanel graphicsPanel = new JPanel()
@Override
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHints(rh);
Paint gPaint = new GradientPaint(0, 0, Color.blue,
40, 40, Color.magenta, true);
g2d.setPaint(gPaint);
g2d.fill(new Ellipse2D.Double(0, 0, 800, 800));
public BsfCrap()
mainPanel.setPreferredSize(new Dimension(400, 400));
mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
graphicsPanel.setPreferredSize(new Dimension(800, 800));
graphicsPanel.setBackground(Color.white);
scrollPane = new JScrollPane(graphicsPanel);
scrollPane.setPreferredSize(new Dimension(300, 300));
mainPanel.add(scrollPane);
public JPanel getMainPanel()
return mainPanel;
@Override
public void init()
try
SwingUtilities.invokeAndWait(new Runnable()
public void run()
setSize(new Dimension(400, 400));
getContentPane().add(new BsfCrap().getMainPanel());
catch (InterruptedException e)
e.printStackTrace();
catch (InvocationTargetException e)
e.printStackTrace();
} -
Swing Components not displaying in a JFrame
Hi,
I have a JFrame with a couple of JLabels, JButtons etc. and a Choice Combo Box
my problem is that when i run the program the only component that gets displayed at first is Choice and in order for me to see the swing components i have to roll over them with my mouse and the JLabels dont even display when i do that..
Does anyone know how i can fix this please?
here is my code
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import java.awt.Image.*;
import java.io.*;
import java.net.*;
public class ImageViewerAnim extends JFrame {
private JLabel perc, scale;
private JTextField inPercent;
private JButton draw, muteOn;
private JPanel sPanel;
private String[] pics = {"Earth", "Moon", "Jupiter", "Pluton", "Neptun"};
private String[] picsFile = {"images/earth.gif", "images/moon.gif", "images/jupiter.jpg", "images/pluton.jpg", "images/neptun.jpg"};
private String[] soundsFile = {"sounds/tada.wav", "sounds/notify.wav", "sounds/ding.wav", "sounds/chimes.wav", "sounds/chimes.wav"};
private Choice ch;
private Image pic;
private AudioClip sound = null;
private int scaleAm = 0;
private int origScale = 500;
private int finalScale = 0;
private boolean proceed = true;
public ImageViewerAnim() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
sPanel = new JPanel();
ch = new Choice();
for(int i = 0; i < pics.length; ++i) {
ch.add(pics);
scale = new JLabel("Scale");
perc = new JLabel("%");
inPercent = new JTextField(5); // scale value input field
draw = new JButton("Draw");
draw.setBorder(BorderFactory.createEtchedBorder());
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = 0;
index = ch.getSelectedIndex();
pic = null;
repaint();
pic = (Toolkit.getDefaultToolkit().getImage(picsFile[index]));
try{
File f = new File(soundsFile[index]);
sound = Applet.newAudioClip(f.toURL());
}catch(MalformedURLException mfe) {
mfe.printStackTrace();
if(!inPercent.getText().equals("")) {
scaleAm = Integer.parseInt(inPercent.getText()); // get the scale amount from the user
finalScale = ((origScale * scaleAm)/100); // calculate the final scale amount based on what the user entered
}else {
finalScale = origScale; // default to original size of the image if no value for scale was entered
// creates a scaled instance of an image and takes the amount of scale as an argument
repaint();
sound.loop();
muteOn = new JButton("Mute On");
muteOn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sound.stop();
muteOn.setText("MuteOff");
sPanel.add(ch);
sPanel.add(scale);
sPanel.add(inPercent);
sPanel.add(perc);
sPanel.add(draw);
sPanel.add(muteOn);
c.add(sPanel, BorderLayout.SOUTH);
repaint();
public void paint(Graphics g) {
if(pic!=null) {
g.drawImage(pic,0,0,this);
public static void main(String args[]) {
ImageViewerAnim app = new ImageViewerAnim();
app.setSize(500,500);
app.setVisible(true);
app.setDefaultCloseOperation(EXIT_ON_CLOSE);
app.show();
thank you in advance
Ivofor future reference
i was able to fix this by adding
super.paint(g);in the first line of my paint method
Ivo -
How to use Swing Components in JavaFX
Hi All,
I am new to JavaFx. I am trying to use java swing components in javafx.
I found a sample program in net and tried it. But it shows compile time error.
Code:
MySwingComponent .fx
import javafx.ext.swing.SwingComponent;
import javax.swing.JComponent;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
* @author nandha
class MySwingComponent extends SwingComponent{
var button: JButton;
public var text: String on replace {
button.setText(text);
public var action: function();
override protected function createJComponent () : JComponent {
button = new JButton();
button.addActionListener(ActionListener {
public override function actionPerformed(e:ActionEvent){
action();
return button;
The above code shows no error.
Test SwingButton.fx
import javafx.stage.Stage;
import javafx.scene.Scene;
import swingcomponents.MySwingButton;
* @author nandha
Stage {
title: "Swing Button Example"
scene: Scene {
width: 250
height: 80
content: [
MySwingButton{ // error message: imcompatible type. found MySwingButton. Required javafx.scene.Node[]
text: "Click Me!"
action: function(){
println("Hello World!");
This code which used the MySwingButton shows error: imcompatible type. found MySwingButton. Required javafx.scene.Node[] - where i have added the MySwingButton.
Please help me to fix the error.
Thanks &Regards,
Nandha KHi Sasa,
First thanks for your reply.
I found the problem and have fixed.
Problem:
There is no class MySwingButton in the package swingcomponents. Its MySwingComponent that i should have used, which is a big mistake that i have done. To my surprise i don't know NetBeans didn't show any error message at that line.
Thanks & Regards,
Nandha K -
JDBC-ODBC Bridge, Swing Components
This program displays information from the Access database Autos.mdb.
Uses the JDBC-ODBC Bridge.
Requires a DSN called Autos pointing to Auto.mdb
I am using the swing components and can't seem to set up my combobox to pull the right data which doesn't display any of the data from the database. I am able to do it using AWT but would like a sleeker look so I am trying to convert. I have made the text bold where I am having the problem. Any insight would be greatful! I am very new to JDBC-ODBC so please go easy on me...
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JDBCApp extends Frame implements ItemListener
//Declare database variables
Connection conVehicle;
Statement cmdVehicle;
ResultSet rsVehicle;
boolean blnSuccessfulOpen = false;
//Declare components
JComboBox lstManuf = new JComboBox();
JLabel lblModel = new JLabel(" ");
JLabel lblYear = new JLabel(" ");
JLabel lblCost = new JLabel(" ");
JLabel lblID = new JLabel(" ");
JLabel lblInstructions = new JLabel("Select Manufacturer to Display Record");
public static void main(String args[])
//Declare an instance of this application
JDBCApp thisApp = new JDBCApp();
thisApp.createInterface();
public void createInterface()
//Load the database and set up the frame
loadDatabase();
if (blnSuccessfulOpen)
setTitle("Display Auto's Database");
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent event)
stop();
System.exit(0);
setLayout(new FlowLayout());
add(new JLabel("Manufacturer"));
add(lstManuf);
lstManuf.addItemListener(this);
add(lblInstructions);
add(new JLabel("Model"));
add(lblModel);
add(new JLabel("Year"));
add(lblYear);
add(new JLabel("Cost"));
add(lblCost);
add(new JLabel("Vehicle Identification"));
add(lblID);
setSize(300,300);
setVisible(true);
else
stop(); //Close any open connection
System.exit(-1); //Exit with error status
public void loadDatabase()
try
//Load the MicroSoft drivers
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException err)
//No drivers found
System.err.println("Driver did not load properly");
try
//Connect to the database
conVehicle = DriverManager.getConnection("jdbc:odbc:Auto");
//Create a ResultSet
cmdVehicle = conVehicle.createStatement();
rsVehicle = cmdVehicle.executeQuery(
"Select * from Vehicle;");
loadNames(rsVehicle);
blnSuccessfulOpen = true;
catch(SQLException error)
System.err.println("Error: " + error.toString());
public void loadNames(ResultSet rsVehicle)
try
//Fill last name list box
while(rsVehicle.next())
lstManuf.addItem(rsVehicle.getString("Manufacturer"));
catch (SQLException error)
System.err.println("Error in display record");
public void itemStateChanged(ItemEvent event)
//Display the selected record
lblInstructions.setText(""); String strManufName = lstManuf.getText();
try
Statement cmdVehicle = conVehicle.createStatement();
ResultSet rsVehicle = cmdVehicle.executeQuery(
"Select * from Vehicle where [Manufacturer] = '" + strManufName + "';");
DisplayRecord(rsVehicle);
catch(SQLException error)
System.err.println("Error in recordset");
public void DisplayRecord(ResultSet rsVehicle)
try
//Display information
if(rsVehicle.next()) //If more records remain
lblModel.setText(rsVehicle.getString("ModelName"));
lblYear.setText(rsVehicle.getString("Year"));
lblCost.setText(rsVehicle.getString("CostValue"));
lblID.setText(rsVehicle.getString("VehicleID"));
else
System.err.println("No more records");
catch (SQLException error)
System.err.println("Error in display record");
public void stop()
try
//Terminate the connection
if (conVehicle != null)
conVehicle.close();
catch(SQLException error)
System.err.println("Unable to disconnect");
}I am going to help you out but first I would like to advise you not to do this.
Mixing JDBC and Swing (or any GUI for that matter) like this is not the preferred way to proceed. If you want to learn JDBC then command line/shell is fine. If you want to learn Swing learn Swing. When you want to use the two together learn about MVC first.
I am advising you to do this because nobody writes code like this (mixing GUI and database and business logic all in one class). So if you want real world training MVC should be what you look at next.
See http://en.wikipedia.org/wiki/Model-view-controller for more
As near as I can tell your problem is mostly just because you aren't using the combo box correctly. Try
String strManufName = lstManuf.getSelectedItem().toString();it's a bit of a hack but will work for your purposes. What you need in the eend is to use the methods JComboxBox has like getSelectedItem() or getSelectedIndex().
See http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html for more.
Some other comments.
1) It's nice to see you aren't just swallowing exceptions but some of them are kind of pointless if you just continue on. Like here
try
//Load the MicroSoft drivers
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException err)
//No drivers found
System.err.println("Driver did not load properly");
}And then you continue on with the method. What for? There's no point since the driver didn't load.
2) Please look into the use of PreparedStatements. Very good things those. You can use them in place of your Statements. They are safer but for your purposes help you by you not having to worry about the formatting of data you bind to queries. For example what happens if a manufacturer name contains a ' (single quote) ? Trouble that's what. PreparedStatements make that problem go away.
3) Don't use SELECT *. It is always good practice to put the names of the columns you are selecting. This prevents your code from breaking if the order of the columns should change in any way. -
Jre 15.0_22/Linux - Swing components error when using GTKLookAndFeel
Hello,
I'm not sure if it's a JRE bug or what, but on Linux platforms our applet fails when using swing components using the GTKLookAndFeel.
To demonstrate/test, I have the ff test applet:
import java.applet.Applet;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestApplet extends Applet {
@Override
public void init() {
super.init();
test();
public static void main(String[] args) {
(new TestApplet()).test();
public void test() {
try {
String className = UIManager.getSystemLookAndFeelClassName();
System.out.println(className);
javax.swing.LookAndFeel laf = (javax.swing.LookAndFeel) this.getClass().forName(className).newInstance();
UIManager.setLookAndFeel(laf);
System.out.println("setting classloader");
UIManager.put("ClassLoader", this.getClass().getClassLoader());
UIManager.getLookAndFeelDefaults().put("ClassLoader", this.getClass().getClassLoader());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(UIManager.getLookAndFeelDefaults().getUIClass("javax.swing.JTextField"));
UIManager.getLookAndFeelDefaults().getUI(new javax.swing.JTextField());
}The system look and feel here is GTKLookAndFeel. The problem is that the getUI() call in the last line is returning null and I can see in the console:
UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.JTextField
java.lang.Error
.. etc.
This is happening for different swing classes, I just used JTextField here as a simple test case.
This only happens if the applet is run from the browser (via the java plugin). If I run the above code from the command line, there is no error raised, and the actual component UI class is a Synth class.
This is only happening for us in Java 1.5.0_22 on Linux...on 1.5.0_15 and 1.6+ it seems to be fine. I'm using the 1.5.0_22 JDK downloaded from Sun.
Anyone have any idea how to fix this error or any workaround? As you can see in the code above, I tried specifying the classloader (I read it in some other thread on these forums), but no luck there.
Or is this a known problem in 1.5.0_22? Can anyone else replicate it?Installation howto you can find on http://www.puschitz.com
Try use "Search" function before you create new topic. This one was discussed many times. -
How can i understand swing components?
hi
i am tonmoy. i have some question about swing component
i,e JTextField,JListBox JTable etc.
1. i have made a class name StyledDOcument extends
DefaultStyledDocument so i can access any public method of
DefaultStyledDocument. but my problem is that i cannot understand
which method is implicitly called and whcih are not.
for example InsertString(int offs, String str, AttributeSet a)
is internally called because if i dont override it or call it using
super.insertstring(), it will be called internally everytime i press
char from keybord.
so i think there are many method of swing components that are called
internally but by reading java doc i can't understand
which method is internally called and which are not.
so plese answer my questions in details.
thank youTutorials, Teachers, and books are all good ways to learn these things.
-
Configuring Swing components from a database
Hi All
I'd like to be able to configure Swing components with information from a database e.g. text, color, editability etc. One approach I'm considering is extending existing components such a JTextField and adding a configure() method which takes as a parameter the primary key of the database record containing the config info.
Has anyone comes across alternative design patterns for solving this?
Regards
Terry Childthat is what I would do
-
Is it possible to create Thread for Swing Components or for JApplet?
Can i create a Thread by extending Thread class or implementing Runnable interface for Swing Components?
Can i create a Thread by extending Thread class or implementing Runnable interface with JApplet?
thanksDoes your website live on a Windows server? The above link you posted will require a Windows server for that to work but if you do, then you should be able to just follow the links instructions.
If your site is not on a Windows server (maybe it's on Linux?) then you would most likely need a PHP solution - something like this: http://www.w3schools.com/php/php_mail.asp. Depending on your host, they might actually have a ready-built form script for you to use so it might be best to ask them first.
You might also want some kind of validation to ensure you receive the correct information so something like jQuery Validate could work. -
Unicode font for swing components
Hi all,
I'd like to set a Swing component (a JLabel) to a particular font so it will properly display Unicode Greek text. I've been reading all about physical vs. logical fonts, and I've read through the various Sun docs/faqs on Internationalization, Fonts, and Unicode, but I just can't get this to work. I think I'm missing something more basic here about selecting my font. My test word is the Greek "khairete," with an accent over the iota. Here is the Unicode:
\u03c7\u03b1\u1f77\u03c1\u03b5\u03c4\u03b5
The trick is that accented iota.
I can launch an xterm that shows the characters I want like this:
$ xterm -fn -misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1 &
That tells me that if I can get Java to use that font, then I'm all set. I'm trying the following test program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
public class GUI extends JFrame {
public static final String MESSAGE = "\u03c7\u03b1\u1f77\u03c1\u03b5\u03c4\u03b5";
public GUI() throws Exception {
super();
Font[] fonts;
Container container;
JLabel label;
fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for (int j=0;j<fonts.length;j++) {
System.out.println(fonts[j]);
container = getContentPane();
container.setLayout(new GridLayout(0, 1));
// try with the default font
label = new JLabel(MESSAGE);
container.add(label);
printFont(label.getFont());
// see what the default font looks like when PLAIN (to compare with fonts below)
label = new JLabel(MESSAGE);
label.setFont(label.getFont().deriveFont(Font.PLAIN, 12));
container.add(label);
printFont(label.getFont());
// this looks the same as the default font, meaning we didn't find what we asked for.
label = new JLabel(MESSAGE);
label.setFont(new Font("-misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1", Font.PLAIN, 12));
container.add(label);
printFont(label.getFont());
// this also falls back to the default.
label = new JLabel(MESSAGE);
label.setFont(Font.getFont("-misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1"));
container.add(label);
printFont(label.getFont());
// this (of course) falls back to the default.
label = new JLabel(MESSAGE);
label.setFont(Font.getFont("not a font name"));
container.add(label);
printFont(label.getFont());
// try every font we've got!
for (int j = 0; j < fonts.length; j++) {
label = new JLabel(fonts[j] + ": " + MESSAGE);
label.setFont(fonts[j].deriveFont(Font.PLAIN, 12));
container.add(label);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
show();
public static void printFont(Font f) {
System.out.println(f);
if (f != null) {
public static void main(String[] args) throws Exception {
GUI me = new GUI();
But nothing in this code succeedings in printing \u1f77. As I've said, the plain old xterm can do it. I think my problem is that I haven't successfully referenced the desired font in the Java code. But how do I do this? These are the fonts available to me, according to the code above:
java.awt.Font[family=Bitstream Charter,name=Bitstream Charter,style=plain,size=1]
java.awt.Font[family=Bitstream Charter,name=Bitstream Charter Bold,style=plain,size=1]
java.awt.Font[family=Bitstream Charter,name=Bitstream Charter Bold Italic,style=plain,size=1]
java.awt.Font[family=Bitstream Charter,name=Bitstream Charter Italic,style=plain,size=1]
java.awt.Font[family=Courier,name=Courier,style=plain,size=1]
java.awt.Font[family=Courier 10 Pitch,name=Courier 10 Pitch,style=plain,size=1]
java.awt.Font[family=Courier 10 Pitch,name=Courier 10 Pitch Bold,style=plain,size=1]
java.awt.Font[family=Courier 10 Pitch,name=Courier 10 Pitch Bold Italic,style=plain,size=1]
java.awt.Font[family=Courier 10 Pitch,name=Courier 10 Pitch Italic,style=plain,size=1]
java.awt.Font[family=Courier,name=Courier Bold,style=plain,size=1]
java.awt.Font[family=Courier,name=Courier Bold Italic,style=plain,size=1]
java.awt.Font[family=Courier,name=Courier Italic,style=plain,size=1]
java.awt.Font[family=Cursor,name=Cursor,style=plain,size=1]
java.awt.Font[family=Lucida Bright,name=Lucida Bright Demibold,style=plain,size=1]
java.awt.Font[family=Lucida Bright,name=Lucida Bright Demibold Italic,style=plain,size=1]
java.awt.Font[family=Lucida Bright,name=Lucida Bright Italic,style=plain,size=1]
java.awt.Font[family=Lucida Bright,name=Lucida Bright Regular,style=plain,size=1]
java.awt.Font[family=Lucida Sans,name=Lucida Sans Demibold,style=plain,size=1]
java.awt.Font[family=Lucida Sans,name=Lucida Sans Demibold Oblique,style=plain,size=1]
java.awt.Font[family=Lucida Sans,name=Lucida Sans Oblique,style=plain,size=1]
java.awt.Font[family=Lucida Sans,name=Lucida Sans Regular,style=plain,size=1]
java.awt.Font[family=Lucida Sans Typewriter,name=Lucida Sans Typewriter Bold,style=plain,size=1]
java.awt.Font[family=Lucida Sans Typewriter,name=Lucida Sans Typewriter Bold Oblique,style=plain,size=1]
java.awt.Font[family=Lucida Sans Typewriter,name=Lucida Sans Typewriter Oblique,style=plain,size=1]
java.awt.Font[family=Lucida Sans Typewriter,name=Lucida Sans Typewriter Regular,style=plain,size=1]
java.awt.Font[family=Luxi Mono,name=Luxi Mono Bold,style=plain,size=1]
java.awt.Font[family=Luxi Mono,name=Luxi Mono Bold Oblique,style=plain,size=1]
java.awt.Font[family=Luxi Mono,name=Luxi Mono Oblique,style=plain,size=1]
java.awt.Font[family=Luxi Mono,name=Luxi Mono Regular,style=plain,size=1]
java.awt.Font[family=Luxi Sans,name=Luxi Sans Bold,style=plain,size=1]
java.awt.Font[family=Luxi Sans,name=Luxi Sans Bold Oblique,style=plain,size=1]
java.awt.Font[family=Luxi Sans,name=Luxi Sans Oblique,style=plain,size=1]
java.awt.Font[family=Luxi Sans,name=Luxi Sans Regular,style=plain,size=1]
java.awt.Font[family=Luxi Serif,name=Luxi Serif Bold,style=plain,size=1]
java.awt.Font[family=Luxi Serif,name=Luxi Serif Bold Oblique,style=plain,size=1]
java.awt.Font[family=Luxi Serif,name=Luxi Serif Oblique,style=plain,size=1]
java.awt.Font[family=Luxi Serif,name=Luxi Serif Regular,style=plain,size=1]
java.awt.Font[family=Utopia,name=Utopia Bold,style=plain,size=1]
java.awt.Font[family=Utopia,name=Utopia Bold Italic,style=plain,size=1]
java.awt.Font[family=Utopia,name=Utopia Italic,style=plain,size=1]
java.awt.Font[family=Utopia,name=Utopia Regular,style=plain,size=1]
java.awt.Font[family=dialog,name=dialog,style=plain,size=1]
java.awt.Font[family=dialog,name=dialog.bold,style=plain,size=1]
java.awt.Font[family=dialog,name=dialog.bolditalic,style=plain,size=1]
java.awt.Font[family=dialog,name=dialog.italic,style=plain,size=1]
java.awt.Font[family=dialoginput,name=dialoginput,style=plain,size=1]
java.awt.Font[family=dialoginput,name=dialoginput.bold,style=plain,size=1]
java.awt.Font[family=dialoginput,name=dialoginput.bolditalic,style=plain,size=1]
java.awt.Font[family=dialoginput,name=dialoginput.italic,style=plain,size=1]
java.awt.Font[family=monospaced,name=monospaced,style=plain,size=1]
java.awt.Font[family=monospaced,name=monospaced.bold,style=plain,size=1]
java.awt.Font[family=monospaced,name=monospaced.bolditalic,style=plain,size=1]
java.awt.Font[family=monospaced,name=monospaced.italic,style=plain,size=1]
java.awt.Font[family=sansserif,name=sansserif,style=plain,size=1]
java.awt.Font[family=sansserif,name=sansserif.bold,style=plain,size=1]
java.awt.Font[family=sansserif,name=sansserif.bolditalic,style=plain,size=1]
java.awt.Font[family=sansserif,name=sansserif.italic,style=plain,size=1]
java.awt.Font[family=serif,name=serif,style=plain,size=1]
java.awt.Font[family=serif,name=serif.bold,style=plain,size=1]
java.awt.Font[family=serif,name=serif.bolditalic,style=plain,size=1]
java.awt.Font[family=serif,name=serif.italic,style=plain,size=1]
javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=bold,size=12]
java.awt.Font[family=Dialog,name=Dialog,style=plain,size=12]
java.awt.Font[family=dialog,name=-misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1,style=plain,size=12]
javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=plain,size=12]
javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=plain,size=12]
Apparently, I need to use the correct "name" to specify the font. So my next try was this:
$ xlsfonts -ll -fn -misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1
name: -misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1
direction: left to right
indexing: matrix
rows: 0x00 thru 0x30 (0 thru 48)
columns: 0x00 thru 0xff (0 thru 255)
all chars exist: no
default char: 0x0000 (0)
ascent: 14
descent: 4
font type: Character Cell
bounds: width left right asc desc attr keysym
min 9 0 0 -3 -13 0x0000
max 9 8 9 14 4 0x0000
properties: 23
FONTNAME_REGISTRY
FOUNDRY Misc
FAMILY_NAME Fixed
WEIGHT_NAME Medium
SLANT R
SETWIDTH_NAME Normal
ADD_STYLE_NAME
PIXEL_SIZE 18
POINT_SIZE 120
RESOLUTION_X 100
RESOLUTION_Y 100
SPACING C
AVERAGE_WIDTH 90
CHARSET_REGISTRY ISO10646
CHARSET_ENCODING 1
COPYRIGHT Public domain font. Share and enjoy.
XMBDFEDINFO 654
CAP_HEIGHT 10
X_HEIGHT 7
FONT -Misc-Fixed-Medium-R-Normal--18-120-100-100-C-90-ISO10646-1
WEIGHT 10
RESOLUTION 138
QUAD_WIDTH 9
name: -misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1
direction: left to right
indexing: matrix
rows: 0x00 thru 0x30 (0 thru 48)
columns: 0x00 thru 0xff (0 thru 255)
all chars exist: no
default char: 0x0000 (0)
ascent: 14
descent: 4
font type: Character Cell
bounds: width left right asc desc attr keysym
min 9 0 0 -3 -13 0x0000
max 9 8 9 14 4 0x0000
properties: 23
FONTNAME_REGISTRY
FOUNDRY Misc
FAMILY_NAME Fixed
WEIGHT_NAME Medium
SLANT R
SETWIDTH_NAME Normal
ADD_STYLE_NAME
PIXEL_SIZE 18
POINT_SIZE 120
RESOLUTION_X 100
RESOLUTION_Y 100
SPACING C
AVERAGE_WIDTH 90
CHARSET_REGISTRY ISO10646
CHARSET_ENCODING 1
COPYRIGHT Public domain font. Share and enjoy.
XMBDFEDINFO 654
CAP_HEIGHT 10
X_HEIGHT 7
FONT -Misc-Fixed-Medium-R-Normal--18-120-100-100-C-90-ISO10646-1
WEIGHT 10
RESOLUTION 138
QUAD_WIDTH 9
(Yes, xlsfonts prints two entries.)
Here is a bit more data:
[pjungwir@mccurdy unicode_gui]$ uname -a
Linux mccurdy.nfic.com 2.4.18-14 #1 Wed Sep 4 13:35:50 EDT 2002 i686 i686 i386 GNU/Linux
[pjungwir@mccurdy unicode_gui]$ cat /etc/redhat-release
Red Hat Linux release 8.0 (Psyche)
[pjungwir@mccurdy unicode_gui]$ java -version
java version "1.4.2_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_01-b06)
Java HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)
If anyone has any suggestions, I would really appreciate it. I'd like to find an answer that doesn't involve editing the font.properties file.
Thanks,
--PaulHi Sojan,
first up, forget the notion of even tinkering with the font.properties file if you can. It's an old, outdated method of setting up the fonts that Sun doesn't even support any more. Use setFont() where you can, and die trying in the process! ;-)
One thing I would check is which font each AWT component currently thinks it has. It's easy enough to set the font system wide with Swing components, but I'm not sure if that capability extends to AWT components (I've certainly had trouble with it in various places in the past). While you've set up the Chinese font correctly, your AWT components might still be stuck with the Java default (Helvetica, or whatever it is, which is incapable of displaying Chinese), and hence displaying the rectangles because they don't know how to handle the foreign characters. You might need to set SimSun as the font for each of your AWT components individually at a worst-case scenario.
Hope that helps,
Martin Hughes -
Hello,
I am having problems with the XmlEncoder. I have created a GUI using and MVC pattern and I am trying to Serialize my view and model in a xml format so i can reload it at a later time. However, The XmlEncorder is not writing out my CustomTables (A class that extends JTable with a DefaultConstructor and bean properties), nor is it writing out the JList swing Components. Due to the fact that it writes out my TextFields, ComboBox, and Checkboxes. I have tried to recreate my tables using the Data from my Model. However, it is not writing out List<Object> types. I have followed the Java bean convention, all my fields have "getters & setters". All of my Classes extends Serializable. Is there anything I'm missing? Those the encoder persist inner class?Hi,
Thanks for the reply. I guess I was trying to take the other approach because the XmlEncoder tool is suppose to be able to persist swing components. However, I have also try to serialize the model with this tool and it is not Writing out all of my properties. I have used XStream to write the model out to xml and it works fine; so yes I can reinitialize my GUI with that. However, I am farely interested in the reason this XmlEncoder is not working. I have satisfied all of the requirements that has been define for this tool to work. -
Unable to init swing components because of LOOP... ???
Hi all,
I'm writing a simple client/server Instant Messenger with Java.
There is a problem with login - I cant init all swing components because of LOOP in class.
Structure of Logging:
(1) fill server name, connection port, user nick
(2) create messaging window, destroys login window
Structure of Client
(1) init components
(2) creates Socket with server
(3) checks if socket created
(3.1) if not - goes to (2)
(3.2) if yes - goes to (4)
(4) recieves message from server about esteblished connection.
If there is any suggestions...
Thnks in adv.
Kiril
(Simplified structure of classes. Full are here http://fmf.vtu.lt/~knugmanov/Elliptic%20curve%20cryptography%20instant%20messenger/main_package/ )
public class Login extends Frame
private static void init_components()
connect_button_login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
main_frame_login.dispose();
// init new Client class
new Client(server_name_field.getText(), Integer.parseInt(server_port_field.getText()), user_nick_field.getText());
public static void main(String[] args)
init_components();
public class Client extends Frame
Client(String server_name, int sever_p, String nick)
user_nick = nick;
server_ip = server_name;
server_port = sever_p;
//init SWING components
init_components();
// create Socket with server
start_client();
//LOOP
start_thread();
public void start_thread()
while (true)
// stop thread for 0.1 s
try
Thread.sleep(100);
}catch(Exception e){
continue;
// change window title
main_frame.setTitle("Client "+get_time());
// if there is connection with server - get the message from it
// if no - try to connect one more time
if (connected == true)
get_message();
}else{
start_client();
}Look at the API for Thread.
Create a class that extends Thread, write the constructor with a parameter that
uses main_frame and assign it to an attribute of this class. Write the run()
method with a while loop which checks a boolean attribute of this class and
which calls main_frame.setTitle() method and then call sleep. Write a method
exit() that sets the boolean attribute of this class to false so that your loop will
stop.
Somewhere instantiate this class and call it's start() method. Call the exit ()
method when you want it to stop.
That's the way I would do it. -
I can't use swing components in my applets
When I write an applet without any swing components, my browser never has any trouble finding the classes it needs, whether they're classes I've written or classes that came with Java. However, when I try to use swing components it cannot find them, because it is looking in the wrong place:
On my computer I have a directory called C:\Java, into which I installed my Java Development Kit (so Sun's classes are stored in the default location within that directory, wherever that is), and I store my classes in C:\Java\Files\[path depends on package]. My browser gives an error message along the lines of "Cannot find class JFrame at C:\Java\Files\javax\swing\JFrame.class"; it shouldn't be looking for this non-existent directory, it should find the swing components where it finds, for example, the Applet class and the Graphics class.
Is there any way I can set the classpath on my browser? Are the swing components stored separately from other classes (I'm using the J2SE v1.3)?
Thanks in advance.Without having complete information, it appears that you are running your applets using the browser's VM. Further, I assume you are using either IE or Netscape Navigator pre-v6. In that case, your browser only supports Java 1.1, and Swing was implemented in Java 1.2. You need to use the Java plug-in in order to use the Swing classes (see the Plug-in forum for more information), or else download the Swing classes from Sun and include them in your CLASSPATH.
HTH,
Carl Rapson
Maybe you are looking for
-
Battery doesn't charge on my newly purchased t500
when i discover my new t500 is completely out of battery the first time, i immediately plugged it in to charge. i notice it doesn't charge, if i doble click power management it recognizes the battery but it doens't chaqrge no matter what i do with th
-
Does anyone know anything about Mackeeper?
My imac is 2 years old now and im wondering about defragmenting the hard drive and I found Mackeeper and I am wondering if anyone knows anything about it, or if it is even necesary
-
Hi All, Scenario: XI -> R/3 (ABAP proxy) First question: While doing SLDCHECK in R/3 , I am getting the following error: Calling function LCR_GET_OWN_BUSINESS_SYSTEM Retrieving data from the SLD server... No corresponding business system found => Che
-
How do I know iCloud is working
is there a way to see what all is backing up in iCloud? also I have a iphone and ipad, how would i set them up to sync automatically together in the cloud
-
Overflow in SAP Interactive Forms by Adobe - Scripting problem
Dear Colleagues, in SAP Interactive Forms by Adobe i have to avoid or do a page break. How can i get the overflow information to use this in a script written in java script or form calc? Can somebody help me. Kind Regards Christian Peters